blob: 8f3676e7d2e3e5a073eb1fa4b01ac961c94baacd [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000017#include "CGBlocks.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000018#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000019#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000020#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000023#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000024#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000025#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000026#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000027#include "llvm/ADT/Triple.h"
Yaxun Liu98f0c432017-10-14 12:51:52 +000028#include "llvm/ADT/Twine.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000031#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000032#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000033
Anton Korobeynikov244360d2009-06-05 22:08:42 +000034using namespace clang;
35using namespace CodeGen;
36
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000037// Helper for coercing an aggregate argument or return value into an integer
38// array of the same size (including padding) and alignment. This alternate
39// coercion happens only for the RenderScript ABI and can be removed after
40// runtimes that rely on it are no longer supported.
41//
42// RenderScript assumes that the size of the argument / return value in the IR
43// is the same as the size of the corresponding qualified type. This helper
44// coerces the aggregate type into an array of the same size (including
45// padding). This coercion is used in lieu of expansion of struct members or
46// other canonical coercions that return a coerced-type of larger size.
47//
48// Ty - The argument / return value type
49// Context - The associated ASTContext
50// LLVMContext - The associated LLVMContext
51static ABIArgInfo coerceToIntArray(QualType Ty,
52 ASTContext &Context,
53 llvm::LLVMContext &LLVMContext) {
54 // Alignment and Size are measured in bits.
55 const uint64_t Size = Context.getTypeSize(Ty);
56 const uint64_t Alignment = Context.getTypeAlign(Ty);
57 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
58 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
59 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
60}
61
John McCall943fae92010-05-27 06:19:26 +000062static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
63 llvm::Value *Array,
64 llvm::Value *Value,
65 unsigned FirstIndex,
66 unsigned LastIndex) {
67 // Alternatively, we could emit this as a loop in the source.
68 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000069 llvm::Value *Cell =
70 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000071 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000072 }
73}
74
John McCalla1dee5302010-08-22 10:59:02 +000075static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000076 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000077 T->isMemberFunctionPointerType();
78}
79
John McCall7f416cc2015-09-08 08:05:57 +000080ABIArgInfo
81ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
82 llvm::Type *Padding) const {
83 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
84 ByRef, Realign, Padding);
85}
86
87ABIArgInfo
88ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
89 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
90 /*ByRef*/ false, Realign);
91}
92
Charles Davisc7d5c942015-09-17 20:55:33 +000093Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
94 QualType Ty) const {
95 return Address::invalid();
96}
97
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000098ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000099
John McCall12f23522016-04-04 18:33:08 +0000100/// Does the given lowering require more than the given number of
101/// registers when expanded?
102///
103/// This is intended to be the basis of a reasonable basic implementation
104/// of should{Pass,Return}IndirectlyForSwift.
105///
106/// For most targets, a limit of four total registers is reasonable; this
107/// limits the amount of code required in order to move around the value
108/// in case it wasn't produced immediately prior to the call by the caller
109/// (or wasn't produced in exactly the right registers) or isn't used
110/// immediately within the callee. But some targets may need to further
111/// limit the register count due to an inability to support that many
112/// return registers.
113static bool occupiesMoreThan(CodeGenTypes &cgt,
114 ArrayRef<llvm::Type*> scalarTypes,
115 unsigned maxAllRegisters) {
116 unsigned intCount = 0, fpCount = 0;
117 for (llvm::Type *type : scalarTypes) {
118 if (type->isPointerTy()) {
119 intCount++;
120 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
121 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
122 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
123 } else {
124 assert(type->isVectorTy() || type->isFloatingPointTy());
125 fpCount++;
126 }
127 }
128
129 return (intCount + fpCount > maxAllRegisters);
130}
131
132bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
133 llvm::Type *eltTy,
134 unsigned numElts) const {
135 // The default implementation of this assumes that the target guarantees
136 // 128-bit SIMD support but nothing more.
137 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
138}
139
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000140static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000141 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000142 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
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 {
Petar Jovanovic402257b2015-12-04 00:26:47 +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;
372
373}
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
723class WebAssemblyABIInfo final : public DefaultABIInfo {
724public:
725 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
726 : DefaultABIInfo(CGT) {}
727
728private:
729 ABIArgInfo classifyReturnType(QualType RetTy) const;
730 ABIArgInfo classifyArgumentType(QualType Ty) const;
731
732 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000733 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000734 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000735 void computeInfo(CGFunctionInfo &FI) const override {
736 if (!getCXXABI().classifyReturnType(FI))
737 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
738 for (auto &Arg : FI.arguments())
739 Arg.info = classifyArgumentType(Arg.type);
740 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000741
742 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
743 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000744};
745
746class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
747public:
748 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
749 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
750};
751
752/// \brief Classify argument of given type \p Ty.
753ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
754 Ty = useFirstFieldIfTransparentUnion(Ty);
755
756 if (isAggregateTypeForABI(Ty)) {
757 // Records with non-trivial destructors/copy-constructors should not be
758 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000759 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000760 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000761 // Ignore empty structs/unions.
762 if (isEmptyRecord(getContext(), Ty, true))
763 return ABIArgInfo::getIgnore();
764 // Lower single-element structs to just pass a regular value. TODO: We
765 // could do reasonable-size multiple-element structs too, using getExpand(),
766 // though watch out for things like bitfields.
767 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
768 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000769 }
770
771 // Otherwise just do the default thing.
772 return DefaultABIInfo::classifyArgumentType(Ty);
773}
774
775ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
776 if (isAggregateTypeForABI(RetTy)) {
777 // Records with non-trivial destructors/copy-constructors should not be
778 // returned by value.
779 if (!getRecordArgABI(RetTy, getCXXABI())) {
780 // Ignore empty structs/unions.
781 if (isEmptyRecord(getContext(), RetTy, true))
782 return ABIArgInfo::getIgnore();
783 // Lower single-element structs to just return a regular value. TODO: We
784 // could do reasonable-size multiple-element structs too, using
785 // ABIArgInfo::getDirect().
786 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
787 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
788 }
789 }
790
791 // Otherwise just do the default thing.
792 return DefaultABIInfo::classifyReturnType(RetTy);
793}
794
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000795Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
796 QualType Ty) const {
797 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
798 getContext().getTypeInfoInChars(Ty),
799 CharUnits::fromQuantity(4),
800 /*AllowHigherAlign=*/ true);
801}
802
Dan Gohmanc2853072015-09-03 22:51:53 +0000803//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000804// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000805//
806// This is a simplified version of the x86_32 ABI. Arguments and return values
807// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000808//===----------------------------------------------------------------------===//
809
810class PNaClABIInfo : public ABIInfo {
811 public:
812 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
813
814 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000815 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000816
Craig Topper4f12f102014-03-12 06:41:41 +0000817 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000818 Address EmitVAArg(CodeGenFunction &CGF,
819 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000820};
821
822class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
823 public:
824 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
825 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
826};
827
828void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000829 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000830 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
831
Reid Kleckner40ca9132014-05-13 22:05:45 +0000832 for (auto &I : FI.arguments())
833 I.info = classifyArgumentType(I.type);
834}
Derek Schuff09338a22012-09-06 17:37:28 +0000835
John McCall7f416cc2015-09-08 08:05:57 +0000836Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
837 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000838 // The PNaCL ABI is a bit odd, in that varargs don't use normal
839 // function classification. Structs get passed directly for varargs
840 // functions, through a rewriting transform in
841 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
842 // this target to actually support a va_arg instructions with an
843 // aggregate type, unlike other targets.
844 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000845}
846
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000847/// \brief Classify argument of given type \p Ty.
848ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000849 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000850 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000851 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
852 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000853 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
854 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000855 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000856 } else if (Ty->isFloatingType()) {
857 // Floating-point types don't go inreg.
858 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000859 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000860
Alex Bradburye41a5e22018-01-12 20:08:16 +0000861 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
862 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000863}
864
865ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
866 if (RetTy->isVoidType())
867 return ABIArgInfo::getIgnore();
868
Eli Benderskye20dad62013-04-04 22:49:35 +0000869 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000870 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000871 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000872
873 // Treat an enum type as its underlying type.
874 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
875 RetTy = EnumTy->getDecl()->getIntegerType();
876
Alex Bradburye41a5e22018-01-12 20:08:16 +0000877 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
878 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000879}
880
Chad Rosier651c1832013-03-25 21:00:27 +0000881/// IsX86_MMXType - Return true if this is an MMX type.
882bool IsX86_MMXType(llvm::Type *IRType) {
883 // 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 +0000884 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
885 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
886 IRType->getScalarSizeInBits() != 64;
887}
888
Jay Foad7c57be32011-07-11 09:56:20 +0000889static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000890 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000891 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000892 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
893 .Cases("y", "&y", "^Ym", true)
894 .Default(false);
895 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000896 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
897 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000898 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000899 }
900
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000901 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000902 }
903
904 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000905 return Ty;
906}
907
Reid Kleckner80944df2014-10-31 22:00:51 +0000908/// Returns true if this type can be passed in SSE registers with the
909/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
910static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
911 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000912 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
913 if (BT->getKind() == BuiltinType::LongDouble) {
914 if (&Context.getTargetInfo().getLongDoubleFormat() ==
915 &llvm::APFloat::x87DoubleExtended())
916 return false;
917 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000918 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000919 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000920 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
921 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
922 // registers specially.
923 unsigned VecSize = Context.getTypeSize(VT);
924 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
925 return true;
926 }
927 return false;
928}
929
930/// Returns true if this aggregate is small enough to be passed in SSE registers
931/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
932static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
933 return NumMembers <= 4;
934}
935
Erich Keane521ed962017-01-05 00:20:51 +0000936/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
937static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
938 auto AI = ABIArgInfo::getDirect(T);
939 AI.setInReg(true);
940 AI.setCanBeFlattened(false);
941 return AI;
942}
943
Chris Lattner0cf24192010-06-28 20:05:43 +0000944//===----------------------------------------------------------------------===//
945// X86-32 ABI Implementation
946//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000947
Reid Kleckner661f35b2014-01-18 01:12:41 +0000948/// \brief Similar to llvm::CCState, but for Clang.
949struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000950 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000951
952 unsigned CC;
953 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000954 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000955};
956
Erich Keane521ed962017-01-05 00:20:51 +0000957enum {
958 // Vectorcall only allows the first 6 parameters to be passed in registers.
959 VectorcallMaxParamNumAsReg = 6
960};
961
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000962/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000963class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000964 enum Class {
965 Integer,
966 Float
967 };
968
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000969 static const unsigned MinABIStackAlignInBytes = 4;
970
David Chisnallde3a0692009-08-17 23:08:21 +0000971 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000972 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000973 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000974 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000975 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000976 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000977
978 static bool isRegisterSize(unsigned Size) {
979 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
980 }
981
Reid Kleckner80944df2014-10-31 22:00:51 +0000982 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
983 // FIXME: Assumes vectorcall is in use.
984 return isX86VectorTypeForVectorCall(getContext(), Ty);
985 }
986
987 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
988 uint64_t NumMembers) const override {
989 // FIXME: Assumes vectorcall is in use.
990 return isX86VectorCallAggregateSmallEnough(NumMembers);
991 }
992
Reid Kleckner40ca9132014-05-13 22:05:45 +0000993 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000994
Daniel Dunbar557893d2010-04-21 19:10:51 +0000995 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
996 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000997 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
998
John McCall7f416cc2015-09-08 08:05:57 +0000999 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001000
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001001 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001002 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001003
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001004 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001005 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001006 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001007
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001008 /// \brief Updates the number of available free registers, returns
1009 /// true if any registers were allocated.
1010 bool updateFreeRegs(QualType Ty, CCState &State) const;
1011
1012 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1013 bool &NeedsPadding) const;
1014 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001015
Reid Kleckner04046052016-05-02 17:41:07 +00001016 bool canExpandIndirectArgument(QualType Ty) const;
1017
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001018 /// \brief Rewrite the function info so that all memory arguments use
1019 /// inalloca.
1020 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1021
1022 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001023 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001024 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001025 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1026 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001027
Rafael Espindola75419dc2012-07-23 23:30:29 +00001028public:
1029
Craig Topper4f12f102014-03-12 06:41:41 +00001030 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001031 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1032 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001033
Michael Kupersteindc745202015-10-19 07:52:25 +00001034 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1035 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001036 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001037 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001038 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1039 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001040 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001041 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001042 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001043
John McCall56331e22018-01-07 06:28:49 +00001044 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001045 bool asReturnValue) const override {
1046 // LLVM's x86-32 lowering currently only assigns up to three
1047 // integer registers and three fp registers. Oddly, it'll use up to
1048 // four vector registers for vectors, but those can overlap with the
1049 // scalar registers.
1050 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1051 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001052
1053 bool isSwiftErrorInRegister() const override {
1054 // x86-32 lowering does not support passing swifterror in a register.
1055 return false;
1056 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001057};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001058
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001059class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1060public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001061 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1062 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001063 unsigned NumRegisterParameters, bool SoftFloatABI)
1064 : TargetCodeGenInfo(new X86_32ABIInfo(
1065 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1066 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001067
John McCall1fe2a8c2013-06-18 02:46:29 +00001068 static bool isStructReturnInRegABI(
1069 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1070
Eric Christopher162c91c2015-06-05 22:03:00 +00001071 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001072 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001073
Craig Topper4f12f102014-03-12 06:41:41 +00001074 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001075 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001076 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001077 return 4;
1078 }
1079
1080 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001081 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001082
Jay Foad7c57be32011-07-11 09:56:20 +00001083 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001084 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001085 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001086 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1087 }
1088
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001089 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1090 std::string &Constraints,
1091 std::vector<llvm::Type *> &ResultRegTypes,
1092 std::vector<llvm::Type *> &ResultTruncRegTypes,
1093 std::vector<LValue> &ResultRegDests,
1094 std::string &AsmString,
1095 unsigned NumOutputs) const override;
1096
Craig Topper4f12f102014-03-12 06:41:41 +00001097 llvm::Constant *
1098 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001099 unsigned Sig = (0xeb << 0) | // jmp rel8
1100 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001101 ('v' << 16) |
1102 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001103 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1104 }
John McCall01391782016-02-05 21:37:38 +00001105
1106 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1107 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001108 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001109 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001110};
1111
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001112}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001113
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001114/// Rewrite input constraint references after adding some output constraints.
1115/// In the case where there is one output and one input and we add one output,
1116/// we need to replace all operand references greater than or equal to 1:
1117/// mov $0, $1
1118/// mov eax, $1
1119/// The result will be:
1120/// mov $0, $2
1121/// mov eax, $2
1122static void rewriteInputConstraintReferences(unsigned FirstIn,
1123 unsigned NumNewOuts,
1124 std::string &AsmString) {
1125 std::string Buf;
1126 llvm::raw_string_ostream OS(Buf);
1127 size_t Pos = 0;
1128 while (Pos < AsmString.size()) {
1129 size_t DollarStart = AsmString.find('$', Pos);
1130 if (DollarStart == std::string::npos)
1131 DollarStart = AsmString.size();
1132 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1133 if (DollarEnd == std::string::npos)
1134 DollarEnd = AsmString.size();
1135 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1136 Pos = DollarEnd;
1137 size_t NumDollars = DollarEnd - DollarStart;
1138 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1139 // We have an operand reference.
1140 size_t DigitStart = Pos;
1141 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1142 if (DigitEnd == std::string::npos)
1143 DigitEnd = AsmString.size();
1144 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1145 unsigned OperandIndex;
1146 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1147 if (OperandIndex >= FirstIn)
1148 OperandIndex += NumNewOuts;
1149 OS << OperandIndex;
1150 } else {
1151 OS << OperandStr;
1152 }
1153 Pos = DigitEnd;
1154 }
1155 }
1156 AsmString = std::move(OS.str());
1157}
1158
1159/// Add output constraints for EAX:EDX because they are return registers.
1160void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1161 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1162 std::vector<llvm::Type *> &ResultRegTypes,
1163 std::vector<llvm::Type *> &ResultTruncRegTypes,
1164 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1165 unsigned NumOutputs) const {
1166 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1167
1168 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1169 // larger.
1170 if (!Constraints.empty())
1171 Constraints += ',';
1172 if (RetWidth <= 32) {
1173 Constraints += "={eax}";
1174 ResultRegTypes.push_back(CGF.Int32Ty);
1175 } else {
1176 // Use the 'A' constraint for EAX:EDX.
1177 Constraints += "=A";
1178 ResultRegTypes.push_back(CGF.Int64Ty);
1179 }
1180
1181 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1182 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1183 ResultTruncRegTypes.push_back(CoerceTy);
1184
1185 // Coerce the integer by bitcasting the return slot pointer.
1186 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1187 CoerceTy->getPointerTo()));
1188 ResultRegDests.push_back(ReturnSlot);
1189
1190 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1191}
1192
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001193/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001194/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001195bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1196 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001197 uint64_t Size = Context.getTypeSize(Ty);
1198
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001199 // For i386, type must be register sized.
1200 // For the MCU ABI, it only needs to be <= 8-byte
1201 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1202 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001203
1204 if (Ty->isVectorType()) {
1205 // 64- and 128- bit vectors inside structures are not returned in
1206 // registers.
1207 if (Size == 64 || Size == 128)
1208 return false;
1209
1210 return true;
1211 }
1212
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001213 // If this is a builtin, pointer, enum, complex type, member pointer, or
1214 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001215 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001216 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001217 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001218 return true;
1219
1220 // Arrays are treated like records.
1221 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001222 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223
1224 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001225 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226 if (!RT) return false;
1227
Anders Carlsson40446e82010-01-27 03:25:19 +00001228 // FIXME: Traverse bases here too.
1229
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001230 // Structure types are passed in register if all fields would be
1231 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001232 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001233 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001234 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001235 continue;
1236
1237 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001238 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001239 return false;
1240 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001241 return true;
1242}
1243
Reid Kleckner04046052016-05-02 17:41:07 +00001244static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1245 // Treat complex types as the element type.
1246 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1247 Ty = CTy->getElementType();
1248
1249 // Check for a type which we know has a simple scalar argument-passing
1250 // convention without any padding. (We're specifically looking for 32
1251 // and 64-bit integer and integer-equivalents, float, and double.)
1252 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1253 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1254 return false;
1255
1256 uint64_t Size = Context.getTypeSize(Ty);
1257 return Size == 32 || Size == 64;
1258}
1259
Reid Kleckner791bbf62017-01-13 17:18:19 +00001260static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1261 uint64_t &Size) {
1262 for (const auto *FD : RD->fields()) {
1263 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1264 // argument is smaller than 32-bits, expanding the struct will create
1265 // alignment padding.
1266 if (!is32Or64BitBasicType(FD->getType(), Context))
1267 return false;
1268
1269 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1270 // how to expand them yet, and the predicate for telling if a bitfield still
1271 // counts as "basic" is more complicated than what we were doing previously.
1272 if (FD->isBitField())
1273 return false;
1274
1275 Size += Context.getTypeSize(FD->getType());
1276 }
1277 return true;
1278}
1279
1280static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1281 uint64_t &Size) {
1282 // Don't do this if there are any non-empty bases.
1283 for (const CXXBaseSpecifier &Base : RD->bases()) {
1284 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1285 Size))
1286 return false;
1287 }
1288 if (!addFieldSizes(Context, RD, Size))
1289 return false;
1290 return true;
1291}
1292
Reid Kleckner04046052016-05-02 17:41:07 +00001293/// Test whether an argument type which is to be passed indirectly (on the
1294/// stack) would have the equivalent layout if it was expanded into separate
1295/// arguments. If so, we prefer to do the latter to avoid inhibiting
1296/// optimizations.
1297bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1298 // We can only expand structure types.
1299 const RecordType *RT = Ty->getAs<RecordType>();
1300 if (!RT)
1301 return false;
1302 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001303 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001304 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001305 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001306 // On non-Windows, we have to conservatively match our old bitcode
1307 // prototypes in order to be ABI-compatible at the bitcode level.
1308 if (!CXXRD->isCLike())
1309 return false;
1310 } else {
1311 // Don't do this for dynamic classes.
1312 if (CXXRD->isDynamicClass())
1313 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001314 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001315 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001316 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001317 } else {
1318 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001319 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001320 }
1321
1322 // We can do this if there was no alignment padding.
1323 return Size == getContext().getTypeSize(Ty);
1324}
1325
John McCall7f416cc2015-09-08 08:05:57 +00001326ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001327 // If the return value is indirect, then the hidden argument is consuming one
1328 // integer register.
1329 if (State.FreeRegs) {
1330 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001331 if (!IsMCUABI)
1332 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001333 }
John McCall7f416cc2015-09-08 08:05:57 +00001334 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001335}
1336
Eric Christopher7565e0d2015-05-29 23:09:49 +00001337ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1338 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001339 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001340 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001341
Reid Kleckner80944df2014-10-31 22:00:51 +00001342 const Type *Base = nullptr;
1343 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001344 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1345 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001346 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1347 // The LLVM struct type for such an aggregate should lower properly.
1348 return ABIArgInfo::getDirect();
1349 }
1350
Chris Lattner458b2aa2010-07-29 02:16:43 +00001351 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001352 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001353 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001354 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001355
1356 // 128-bit vectors are a special case; they are returned in
1357 // registers and we need to make sure to pick a type the LLVM
1358 // backend will like.
1359 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001360 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001361 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001362
1363 // Always return in register if it fits in a general purpose
1364 // register, or if it is 64 bits and has a single element.
1365 if ((Size == 8 || Size == 16 || Size == 32) ||
1366 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001367 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001368 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001369
John McCall7f416cc2015-09-08 08:05:57 +00001370 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001371 }
1372
1373 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001374 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001375
John McCalla1dee5302010-08-22 10:59:02 +00001376 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001377 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001378 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001380 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001381 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001382
David Chisnallde3a0692009-08-17 23:08:21 +00001383 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001384 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001385 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001386
Denis Zobnin380b2242016-02-11 11:26:03 +00001387 // Ignore empty structs/unions.
1388 if (isEmptyRecord(getContext(), RetTy, true))
1389 return ABIArgInfo::getIgnore();
1390
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001391 // Small structures which are register sized are generally returned
1392 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001393 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001394 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001395
1396 // As a special-case, if the struct is a "single-element" struct, and
1397 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001398 // floating-point register. (MSVC does not apply this special case.)
1399 // We apply a similar transformation for pointer types to improve the
1400 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001401 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001402 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001403 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001404 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1405
1406 // FIXME: We should be able to narrow this integer in cases with dead
1407 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001408 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001409 }
1410
John McCall7f416cc2015-09-08 08:05:57 +00001411 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001412 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001413
Chris Lattner458b2aa2010-07-29 02:16:43 +00001414 // Treat an enum type as its underlying type.
1415 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1416 RetTy = EnumTy->getDecl()->getIntegerType();
1417
Alex Bradburye41a5e22018-01-12 20:08:16 +00001418 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1419 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420}
1421
Eli Friedman7919bea2012-06-05 19:40:46 +00001422static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1423 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1424}
1425
Daniel Dunbared23de32010-09-16 20:42:00 +00001426static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1427 const RecordType *RT = Ty->getAs<RecordType>();
1428 if (!RT)
1429 return 0;
1430 const RecordDecl *RD = RT->getDecl();
1431
1432 // If this is a C++ record, check the bases first.
1433 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001434 for (const auto &I : CXXRD->bases())
1435 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001436 return false;
1437
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001438 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001439 QualType FT = i->getType();
1440
Eli Friedman7919bea2012-06-05 19:40:46 +00001441 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001442 return true;
1443
1444 if (isRecordWithSSEVectorType(Context, FT))
1445 return true;
1446 }
1447
1448 return false;
1449}
1450
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001451unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1452 unsigned Align) const {
1453 // Otherwise, if the alignment is less than or equal to the minimum ABI
1454 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001455 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001456 return 0; // Use default alignment.
1457
1458 // On non-Darwin, the stack type alignment is always 4.
1459 if (!IsDarwinVectorABI) {
1460 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001461 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001462 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001463
Daniel Dunbared23de32010-09-16 20:42:00 +00001464 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001465 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1466 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001467 return 16;
1468
1469 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001470}
1471
Rafael Espindola703c47f2012-10-19 05:04:37 +00001472ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001473 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001474 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001475 if (State.FreeRegs) {
1476 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001477 if (!IsMCUABI)
1478 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001479 }
John McCall7f416cc2015-09-08 08:05:57 +00001480 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001481 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001482
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001483 // Compute the byval alignment.
1484 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1485 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1486 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001487 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001488
1489 // If the stack alignment is less than the type alignment, realign the
1490 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001491 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001492 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1493 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001494}
1495
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001496X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1497 const Type *T = isSingleElementStruct(Ty, getContext());
1498 if (!T)
1499 T = Ty.getTypePtr();
1500
1501 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1502 BuiltinType::Kind K = BT->getKind();
1503 if (K == BuiltinType::Float || K == BuiltinType::Double)
1504 return Float;
1505 }
1506 return Integer;
1507}
1508
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001509bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001510 if (!IsSoftFloatABI) {
1511 Class C = classify(Ty);
1512 if (C == Float)
1513 return false;
1514 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001515
Rafael Espindola077dd592012-10-24 01:58:58 +00001516 unsigned Size = getContext().getTypeSize(Ty);
1517 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001518
1519 if (SizeInRegs == 0)
1520 return false;
1521
Michael Kuperstein68901882015-10-25 08:18:20 +00001522 if (!IsMCUABI) {
1523 if (SizeInRegs > State.FreeRegs) {
1524 State.FreeRegs = 0;
1525 return false;
1526 }
1527 } else {
1528 // The MCU psABI allows passing parameters in-reg even if there are
1529 // earlier parameters that are passed on the stack. Also,
1530 // it does not allow passing >8-byte structs in-register,
1531 // even if there are 3 free registers available.
1532 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1533 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001534 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001535
Reid Kleckner661f35b2014-01-18 01:12:41 +00001536 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 return true;
1538}
1539
1540bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1541 bool &InReg,
1542 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001543 // On Windows, aggregates other than HFAs are never passed in registers, and
1544 // they do not consume register slots. Homogenous floating-point aggregates
1545 // (HFAs) have already been dealt with at this point.
1546 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1547 return false;
1548
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 NeedsPadding = false;
1550 InReg = !IsMCUABI;
1551
1552 if (!updateFreeRegs(Ty, State))
1553 return false;
1554
1555 if (IsMCUABI)
1556 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001557
Reid Kleckner80944df2014-10-31 22:00:51 +00001558 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001559 State.CC == llvm::CallingConv::X86_VectorCall ||
1560 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001561 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001562 NeedsPadding = true;
1563
Rafael Espindola077dd592012-10-24 01:58:58 +00001564 return false;
1565 }
1566
Rafael Espindola703c47f2012-10-19 05:04:37 +00001567 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001568}
1569
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001570bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1571 if (!updateFreeRegs(Ty, State))
1572 return false;
1573
1574 if (IsMCUABI)
1575 return false;
1576
1577 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001578 State.CC == llvm::CallingConv::X86_VectorCall ||
1579 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001580 if (getContext().getTypeSize(Ty) > 32)
1581 return false;
1582
1583 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1584 Ty->isReferenceType());
1585 }
1586
1587 return true;
1588}
1589
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001590ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1591 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001592 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001593
Reid Klecknerb1be6832014-11-15 01:41:41 +00001594 Ty = useFirstFieldIfTransparentUnion(Ty);
1595
Reid Kleckner80944df2014-10-31 22:00:51 +00001596 // Check with the C++ ABI first.
1597 const RecordType *RT = Ty->getAs<RecordType>();
1598 if (RT) {
1599 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1600 if (RAA == CGCXXABI::RAA_Indirect) {
1601 return getIndirectResult(Ty, false, State);
1602 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1603 // The field index doesn't matter, we'll fix it up later.
1604 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1605 }
1606 }
1607
Erich Keane4bd39302017-06-21 16:37:22 +00001608 // Regcall uses the concept of a homogenous vector aggregate, similar
1609 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001610 const Type *Base = nullptr;
1611 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001612 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001613 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001614
Erich Keane4bd39302017-06-21 16:37:22 +00001615 if (State.FreeSSERegs >= NumElts) {
1616 State.FreeSSERegs -= NumElts;
1617 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001618 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001619 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001620 }
Erich Keane4bd39302017-06-21 16:37:22 +00001621 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001622 }
1623
1624 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001625 // Structures with flexible arrays are always indirect.
1626 // FIXME: This should not be byval!
1627 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1628 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001629
Reid Kleckner04046052016-05-02 17:41:07 +00001630 // Ignore empty structs/unions on non-Windows.
1631 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632 return ABIArgInfo::getIgnore();
1633
Rafael Espindolafad28de2012-10-24 01:59:00 +00001634 llvm::LLVMContext &LLVMContext = getVMContext();
1635 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001636 bool NeedsPadding = false;
1637 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001638 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001639 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001640 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001641 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001642 if (InReg)
1643 return ABIArgInfo::getDirectInReg(Result);
1644 else
1645 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001646 }
Craig Topper8a13c412014-05-21 05:09:00 +00001647 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001648
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001649 // Expand small (<= 128-bit) record types when we know that the stack layout
1650 // of those arguments will match the struct. This is important because the
1651 // LLVM backend isn't smart enough to remove byval, which inhibits many
1652 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001653 // Don't do this for the MCU if there are still free integer registers
1654 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001655 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1656 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001657 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001658 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001659 State.CC == llvm::CallingConv::X86_VectorCall ||
1660 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001661 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001662
Reid Kleckner661f35b2014-01-18 01:12:41 +00001663 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001664 }
1665
Chris Lattnerd774ae92010-08-26 20:05:13 +00001666 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001667 // On Darwin, some vectors are passed in memory, we handle this by passing
1668 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001669 if (IsDarwinVectorABI) {
1670 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001671 if ((Size == 8 || Size == 16 || Size == 32) ||
1672 (Size == 64 && VT->getNumElements() == 1))
1673 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1674 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001675 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001676
Chad Rosier651c1832013-03-25 21:00:27 +00001677 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1678 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001679
Chris Lattnerd774ae92010-08-26 20:05:13 +00001680 return ABIArgInfo::getDirect();
1681 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001682
1683
Chris Lattner458b2aa2010-07-29 02:16:43 +00001684 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1685 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001686
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001687 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001688
1689 if (Ty->isPromotableIntegerType()) {
1690 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001691 return ABIArgInfo::getExtendInReg(Ty);
1692 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001693 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001694
Rafael Espindola703c47f2012-10-19 05:04:37 +00001695 if (InReg)
1696 return ABIArgInfo::getDirectInReg();
1697 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698}
1699
Erich Keane521ed962017-01-05 00:20:51 +00001700void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1701 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001702 // Vectorcall x86 works subtly different than in x64, so the format is
1703 // a bit different than the x64 version. First, all vector types (not HVAs)
1704 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1705 // This differs from the x64 implementation, where the first 6 by INDEX get
1706 // registers.
1707 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1708 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1709 // first take up the remaining YMM/XMM registers. If insufficient registers
1710 // remain but an integer register (ECX/EDX) is available, it will be passed
1711 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001712 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001713 // First pass do all the vector types.
1714 const Type *Base = nullptr;
1715 uint64_t NumElts = 0;
1716 const QualType& Ty = I.type;
1717 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1718 isHomogeneousAggregate(Ty, Base, NumElts)) {
1719 if (State.FreeSSERegs >= NumElts) {
1720 State.FreeSSERegs -= NumElts;
1721 I.info = ABIArgInfo::getDirect();
1722 } else {
1723 I.info = classifyArgumentType(Ty, State);
1724 }
1725 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1726 }
Erich Keane521ed962017-01-05 00:20:51 +00001727 }
Erich Keane4bd39302017-06-21 16:37:22 +00001728
Erich Keane521ed962017-01-05 00:20:51 +00001729 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001730 // Second pass, do the rest!
1731 const Type *Base = nullptr;
1732 uint64_t NumElts = 0;
1733 const QualType& Ty = I.type;
1734 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1735
1736 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1737 // Assign true HVAs (non vector/native FP types).
1738 if (State.FreeSSERegs >= NumElts) {
1739 State.FreeSSERegs -= NumElts;
1740 I.info = getDirectX86Hva();
1741 } else {
1742 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1743 }
1744 } else if (!IsHva) {
1745 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1746 I.info = classifyArgumentType(Ty, State);
1747 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1748 }
Erich Keane521ed962017-01-05 00:20:51 +00001749 }
1750}
1751
Rafael Espindolaa6472962012-07-24 00:01:07 +00001752void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001753 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001754 if (IsMCUABI)
1755 State.FreeRegs = 3;
1756 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001757 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001758 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1759 State.FreeRegs = 2;
1760 State.FreeSSERegs = 6;
1761 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001762 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001763 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1764 State.FreeRegs = 5;
1765 State.FreeSSERegs = 8;
1766 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001767 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001768
Akira Hatanakad791e922018-03-19 17:38:40 +00001769 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001770 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001771 } else if (FI.getReturnInfo().isIndirect()) {
1772 // The C++ ABI is not aware of register usage, so we have to check if the
1773 // return value was sret and put it in a register ourselves if appropriate.
1774 if (State.FreeRegs) {
1775 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001776 if (!IsMCUABI)
1777 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001778 }
1779 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001780
Peter Collingbournef7706832014-12-12 23:41:25 +00001781 // The chain argument effectively gives us another free register.
1782 if (FI.isChainCall())
1783 ++State.FreeRegs;
1784
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001785 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001786 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1787 computeVectorCallArgs(FI, State, UsedInAlloca);
1788 } else {
1789 // If not vectorcall, revert to normal behavior.
1790 for (auto &I : FI.arguments()) {
1791 I.info = classifyArgumentType(I.type, State);
1792 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1793 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 }
1795
1796 // If we needed to use inalloca for any argument, do a second pass and rewrite
1797 // all the memory arguments to use inalloca.
1798 if (UsedInAlloca)
1799 rewriteWithInAlloca(FI);
1800}
1801
1802void
1803X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001804 CharUnits &StackOffset, ABIArgInfo &Info,
1805 QualType Type) const {
1806 // Arguments are always 4-byte-aligned.
1807 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1808
1809 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001810 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1811 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001812 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001813
John McCall7f416cc2015-09-08 08:05:57 +00001814 // Insert padding bytes to respect alignment.
1815 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001816 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001817 if (StackOffset != FieldEnd) {
1818 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001819 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001820 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001821 FrameFields.push_back(Ty);
1822 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001823}
1824
Reid Kleckner852361d2014-07-26 00:12:26 +00001825static bool isArgInAlloca(const ABIArgInfo &Info) {
1826 // Leave ignored and inreg arguments alone.
1827 switch (Info.getKind()) {
1828 case ABIArgInfo::InAlloca:
1829 return true;
1830 case ABIArgInfo::Indirect:
1831 assert(Info.getIndirectByVal());
1832 return true;
1833 case ABIArgInfo::Ignore:
1834 return false;
1835 case ABIArgInfo::Direct:
1836 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001837 if (Info.getInReg())
1838 return false;
1839 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001840 case ABIArgInfo::Expand:
1841 case ABIArgInfo::CoerceAndExpand:
1842 // These are aggregate types which are never passed in registers when
1843 // inalloca is involved.
1844 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001845 }
1846 llvm_unreachable("invalid enum");
1847}
1848
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001849void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1850 assert(IsWin32StructABI && "inalloca only supported on win32");
1851
1852 // Build a packed struct type for all of the arguments in memory.
1853 SmallVector<llvm::Type *, 6> FrameFields;
1854
John McCall7f416cc2015-09-08 08:05:57 +00001855 // The stack alignment is always 4.
1856 CharUnits StackAlign = CharUnits::fromQuantity(4);
1857
1858 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001859 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1860
1861 // Put 'this' into the struct before 'sret', if necessary.
1862 bool IsThisCall =
1863 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1864 ABIArgInfo &Ret = FI.getReturnInfo();
1865 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1866 isArgInAlloca(I->info)) {
1867 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1868 ++I;
1869 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001870
1871 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001872 if (Ret.isIndirect() && !Ret.getInReg()) {
1873 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1874 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001875 // On Windows, the hidden sret parameter is always returned in eax.
1876 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001877 }
1878
1879 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001880 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001881 ++I;
1882
1883 // Put arguments passed in memory into the struct.
1884 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001885 if (isArgInAlloca(I->info))
1886 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001887 }
1888
1889 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001890 /*isPacked=*/true),
1891 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001892}
1893
John McCall7f416cc2015-09-08 08:05:57 +00001894Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1895 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001896
John McCall7f416cc2015-09-08 08:05:57 +00001897 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001898
John McCall7f416cc2015-09-08 08:05:57 +00001899 // x86-32 changes the alignment of certain arguments on the stack.
1900 //
1901 // Just messing with TypeInfo like this works because we never pass
1902 // anything indirectly.
1903 TypeInfo.second = CharUnits::fromQuantity(
1904 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001905
John McCall7f416cc2015-09-08 08:05:57 +00001906 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1907 TypeInfo, CharUnits::fromQuantity(4),
1908 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001909}
1910
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001911bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1912 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1913 assert(Triple.getArch() == llvm::Triple::x86);
1914
1915 switch (Opts.getStructReturnConvention()) {
1916 case CodeGenOptions::SRCK_Default:
1917 break;
1918 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1919 return false;
1920 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1921 return true;
1922 }
1923
Michael Kupersteind749f232015-10-27 07:46:22 +00001924 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001925 return true;
1926
1927 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001928 case llvm::Triple::DragonFly:
1929 case llvm::Triple::FreeBSD:
1930 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001931 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001932 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001933 default:
1934 return false;
1935 }
1936}
1937
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001938void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001939 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1940 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001941 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001942 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001943 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1944 // Get the LLVM function.
1945 llvm::Function *Fn = cast<llvm::Function>(GV);
1946
1947 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001948 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001949 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001950 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001951 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001952 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1953 llvm::Function *Fn = cast<llvm::Function>(GV);
1954 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1955 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001956 }
1957}
1958
John McCallbeec5a02010-03-06 00:35:14 +00001959bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1960 CodeGen::CodeGenFunction &CGF,
1961 llvm::Value *Address) const {
1962 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001963
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001965
John McCallbeec5a02010-03-06 00:35:14 +00001966 // 0-7 are the eight integer registers; the order is different
1967 // on Darwin (for EH), but the range is the same.
1968 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001969 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001970
John McCallc8e01702013-04-16 22:48:15 +00001971 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001972 // 12-16 are st(0..4). Not sure why we stop at 4.
1973 // These have size 16, which is sizeof(long double) on
1974 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001975 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001976 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001977
John McCallbeec5a02010-03-06 00:35:14 +00001978 } else {
1979 // 9 is %eflags, which doesn't get a size on Darwin for some
1980 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001981 Builder.CreateAlignedStore(
1982 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1983 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001984
1985 // 11-16 are st(0..5). Not sure why we stop at 5.
1986 // These have size 12, which is sizeof(long double) on
1987 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001988 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001989 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1990 }
John McCallbeec5a02010-03-06 00:35:14 +00001991
1992 return false;
1993}
1994
Chris Lattner0cf24192010-06-28 20:05:43 +00001995//===----------------------------------------------------------------------===//
1996// X86-64 ABI Implementation
1997//===----------------------------------------------------------------------===//
1998
1999
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002000namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002001/// The AVX ABI level for X86 targets.
2002enum class X86AVXABILevel {
2003 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002004 AVX,
2005 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002006};
2007
2008/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2009static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2010 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002011 case X86AVXABILevel::AVX512:
2012 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002013 case X86AVXABILevel::AVX:
2014 return 256;
2015 case X86AVXABILevel::None:
2016 return 128;
2017 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002018 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002019}
2020
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002022class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002023 enum Class {
2024 Integer = 0,
2025 SSE,
2026 SSEUp,
2027 X87,
2028 X87Up,
2029 ComplexX87,
2030 NoClass,
2031 Memory
2032 };
2033
2034 /// merge - Implement the X86_64 ABI merging algorithm.
2035 ///
2036 /// Merge an accumulating classification \arg Accum with a field
2037 /// classification \arg Field.
2038 ///
2039 /// \param Accum - The accumulating classification. This should
2040 /// always be either NoClass or the result of a previous merge
2041 /// call. In addition, this should never be Memory (the caller
2042 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002043 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002044
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002045 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2046 ///
2047 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2048 /// final MEMORY or SSE classes when necessary.
2049 ///
2050 /// \param AggregateSize - The size of the current aggregate in
2051 /// the classification process.
2052 ///
2053 /// \param Lo - The classification for the parts of the type
2054 /// residing in the low word of the containing object.
2055 ///
2056 /// \param Hi - The classification for the parts of the type
2057 /// residing in the higher words of the containing object.
2058 ///
2059 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2060
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002061 /// classify - Determine the x86_64 register classes in which the
2062 /// given type T should be passed.
2063 ///
2064 /// \param Lo - The classification for the parts of the type
2065 /// residing in the low word of the containing object.
2066 ///
2067 /// \param Hi - The classification for the parts of the type
2068 /// residing in the high word of the containing object.
2069 ///
2070 /// \param OffsetBase - The bit offset of this type in the
2071 /// containing object. Some parameters are classified different
2072 /// depending on whether they straddle an eightbyte boundary.
2073 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002074 /// \param isNamedArg - Whether the argument in question is a "named"
2075 /// argument, as used in AMD64-ABI 3.5.7.
2076 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002077 /// If a word is unused its result will be NoClass; if a type should
2078 /// be passed in Memory then at least the classification of \arg Lo
2079 /// will be Memory.
2080 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002081 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002082 ///
2083 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2084 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002085 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2086 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002087
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002088 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002089 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2090 unsigned IROffset, QualType SourceTy,
2091 unsigned SourceOffset) const;
2092 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2093 unsigned IROffset, QualType SourceTy,
2094 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002095
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002096 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002097 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002098 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002099
2100 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002102 ///
2103 /// \param freeIntRegs - The number of free integer registers remaining
2104 /// available.
2105 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002106
Chris Lattner458b2aa2010-07-29 02:16:43 +00002107 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002108
Erich Keane757d3172016-11-02 18:29:35 +00002109 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2110 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002111 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112
Erich Keane757d3172016-11-02 18:29:35 +00002113 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2114 unsigned &NeededSSE) const;
2115
2116 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2117 unsigned &NeededSSE) const;
2118
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002119 bool IsIllegalVectorType(QualType Ty) const;
2120
John McCalle0fda732011-04-21 01:20:55 +00002121 /// The 0.98 ABI revision clarified a lot of ambiguities,
2122 /// unfortunately in ways that were not always consistent with
2123 /// certain previous compilers. In particular, platforms which
2124 /// required strict binary compatibility with older versions of GCC
2125 /// may need to exempt themselves.
2126 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002127 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002128 }
2129
Richard Smithf667ad52017-08-26 01:04:35 +00002130 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2131 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002132 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002133 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002134 if (getContext().getLangOpts().getClangABICompat() <=
2135 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002136 return false;
2137
David Majnemere2ae2282016-03-04 05:26:16 +00002138 const llvm::Triple &Triple = getTarget().getTriple();
2139 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2140 return false;
2141 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2142 return false;
2143 return true;
2144 }
2145
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002146 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002147 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2148 // 64-bit hardware.
2149 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002150
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002151public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002152 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002153 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002154 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002155 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002156
John McCalla729c622012-02-17 03:33:10 +00002157 bool isPassedUsingAVXType(QualType type) const {
2158 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002159 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002160 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2161 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002162 if (info.isDirect()) {
2163 llvm::Type *ty = info.getCoerceToType();
2164 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2165 return (vectorTy->getBitWidth() > 128);
2166 }
2167 return false;
2168 }
2169
Craig Topper4f12f102014-03-12 06:41:41 +00002170 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002171
John McCall7f416cc2015-09-08 08:05:57 +00002172 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2173 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002174 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2175 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002176
2177 bool has64BitPointers() const {
2178 return Has64BitPointers;
2179 }
John McCall12f23522016-04-04 18:33:08 +00002180
John McCall56331e22018-01-07 06:28:49 +00002181 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002182 bool asReturnValue) const override {
2183 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2184 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002185 bool isSwiftErrorInRegister() const override {
2186 return true;
2187 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002188};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002189
Chris Lattner04dc9572010-08-31 16:44:54 +00002190/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002191class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002192public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002193 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002194 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002195 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002196
Craig Topper4f12f102014-03-12 06:41:41 +00002197 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002198
John McCall7f416cc2015-09-08 08:05:57 +00002199 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2200 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002201
2202 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2203 // FIXME: Assumes vectorcall is in use.
2204 return isX86VectorTypeForVectorCall(getContext(), Ty);
2205 }
2206
2207 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2208 uint64_t NumMembers) const override {
2209 // FIXME: Assumes vectorcall is in use.
2210 return isX86VectorCallAggregateSmallEnough(NumMembers);
2211 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002212
John McCall56331e22018-01-07 06:28:49 +00002213 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002214 bool asReturnValue) const override {
2215 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2216 }
2217
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002218 bool isSwiftErrorInRegister() const override {
2219 return true;
2220 }
2221
Reid Kleckner11a17192015-10-28 22:29:52 +00002222private:
Erich Keane521ed962017-01-05 00:20:51 +00002223 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2224 bool IsVectorCall, bool IsRegCall) const;
2225 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2226 const ABIArgInfo &current) const;
2227 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2228 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002229
Erich Keane521ed962017-01-05 00:20:51 +00002230 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002231};
2232
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002233class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2234public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002235 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002236 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002237
John McCalla729c622012-02-17 03:33:10 +00002238 const X86_64ABIInfo &getABIInfo() const {
2239 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2240 }
2241
Craig Topper4f12f102014-03-12 06:41:41 +00002242 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002243 return 7;
2244 }
2245
2246 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002247 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002248 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002249
John McCall943fae92010-05-27 06:19:26 +00002250 // 0-15 are the 16 integer registers.
2251 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002252 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002253 return false;
2254 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002255
Jay Foad7c57be32011-07-11 09:56:20 +00002256 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002257 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002258 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002259 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2260 }
2261
John McCalla729c622012-02-17 03:33:10 +00002262 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002263 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002264 // The default CC on x86-64 sets %al to the number of SSA
2265 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002266 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002267 // that when AVX types are involved: the ABI explicitly states it is
2268 // undefined, and it doesn't work in practice because of how the ABI
2269 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002270 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002271 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002272 for (CallArgList::const_iterator
2273 it = args.begin(), ie = args.end(); it != ie; ++it) {
2274 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2275 HasAVXType = true;
2276 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002277 }
2278 }
John McCalla729c622012-02-17 03:33:10 +00002279
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002280 if (!HasAVXType)
2281 return true;
2282 }
John McCallcbc038a2011-09-21 08:08:30 +00002283
John McCalla729c622012-02-17 03:33:10 +00002284 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002285 }
2286
Craig Topper4f12f102014-03-12 06:41:41 +00002287 llvm::Constant *
2288 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002289 unsigned Sig = (0xeb << 0) | // jmp rel8
2290 (0x06 << 8) | // .+0x08
2291 ('v' << 16) |
2292 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002293 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2294 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002295
2296 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002297 CodeGen::CodeGenModule &CGM) const override {
2298 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002299 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002300 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002301 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2302 // Get the LLVM function.
2303 auto *Fn = cast<llvm::Function>(GV);
2304
2305 // Now add the 'alignstack' attribute with a value of 16.
2306 llvm::AttrBuilder B;
2307 B.addStackAlignmentAttr(16);
2308 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2309 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002310 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2311 llvm::Function *Fn = cast<llvm::Function>(GV);
2312 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2313 }
2314 }
2315 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002316};
2317
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002318class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2319public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002320 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2321 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002322
2323 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002324 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002325 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002326 // If the argument contains a space, enclose it in quotes.
2327 if (Lib.find(" ") != StringRef::npos)
2328 Opt += "\"" + Lib.str() + "\"";
2329 else
2330 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002331 }
2332};
2333
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002334static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002335 // If the argument does not end in .lib, automatically add the suffix.
2336 // If the argument contains a space, enclose it in quotes.
2337 // This matches the behavior of MSVC.
2338 bool Quote = (Lib.find(" ") != StringRef::npos);
2339 std::string ArgStr = Quote ? "\"" : "";
2340 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002341 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002342 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002343 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002344 return ArgStr;
2345}
2346
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002347class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2348public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002349 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002350 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2351 unsigned NumRegisterParameters)
2352 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002353 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002354
Eric Christopher162c91c2015-06-05 22:03:00 +00002355 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002356 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002357
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002358 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002359 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002360 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002361 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002362 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002363
2364 void getDetectMismatchOption(llvm::StringRef Name,
2365 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002366 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002367 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002368 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002369};
2370
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002371static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2372 CodeGen::CodeGenModule &CGM) {
2373 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002374
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002375 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002376 Fn->addFnAttr("stack-probe-size",
2377 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002378 if (CGM.getCodeGenOpts().NoStackArgProbe)
2379 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002380 }
2381}
2382
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002383void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002384 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2385 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2386 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002387 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002388 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002389}
2390
Chris Lattner04dc9572010-08-31 16:44:54 +00002391class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2392public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002393 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2394 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002395 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002396
Eric Christopher162c91c2015-06-05 22:03:00 +00002397 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002398 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002399
Craig Topper4f12f102014-03-12 06:41:41 +00002400 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002401 return 7;
2402 }
2403
2404 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002405 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002406 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002407
Chris Lattner04dc9572010-08-31 16:44:54 +00002408 // 0-15 are the 16 integer registers.
2409 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002410 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002411 return false;
2412 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002413
2414 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002415 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002416 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002417 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002418 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002419
2420 void getDetectMismatchOption(llvm::StringRef Name,
2421 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002422 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002423 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002424 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002425};
2426
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002427void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002428 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2429 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2430 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002431 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002432 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002433 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2434 // Get the LLVM function.
2435 auto *Fn = cast<llvm::Function>(GV);
2436
2437 // Now add the 'alignstack' attribute with a value of 16.
2438 llvm::AttrBuilder B;
2439 B.addStackAlignmentAttr(16);
2440 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2441 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002442 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2443 llvm::Function *Fn = cast<llvm::Function>(GV);
2444 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2445 }
2446 }
2447
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002448 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002449}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002450}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002451
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002452void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2453 Class &Hi) const {
2454 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2455 //
2456 // (a) If one of the classes is Memory, the whole argument is passed in
2457 // memory.
2458 //
2459 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2460 // memory.
2461 //
2462 // (c) If the size of the aggregate exceeds two eightbytes and the first
2463 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2464 // argument is passed in memory. NOTE: This is necessary to keep the
2465 // ABI working for processors that don't support the __m256 type.
2466 //
2467 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2468 //
2469 // Some of these are enforced by the merging logic. Others can arise
2470 // only with unions; for example:
2471 // union { _Complex double; unsigned; }
2472 //
2473 // Note that clauses (b) and (c) were added in 0.98.
2474 //
2475 if (Hi == Memory)
2476 Lo = Memory;
2477 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2478 Lo = Memory;
2479 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2480 Lo = Memory;
2481 if (Hi == SSEUp && Lo != SSE)
2482 Hi = SSE;
2483}
2484
Chris Lattnerd776fb12010-06-28 21:43:59 +00002485X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2487 // classified recursively so that always two fields are
2488 // considered. The resulting class is calculated according to
2489 // the classes of the fields in the eightbyte:
2490 //
2491 // (a) If both classes are equal, this is the resulting class.
2492 //
2493 // (b) If one of the classes is NO_CLASS, the resulting class is
2494 // the other class.
2495 //
2496 // (c) If one of the classes is MEMORY, the result is the MEMORY
2497 // class.
2498 //
2499 // (d) If one of the classes is INTEGER, the result is the
2500 // INTEGER.
2501 //
2502 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2503 // MEMORY is used as class.
2504 //
2505 // (f) Otherwise class SSE is used.
2506
2507 // Accum should never be memory (we should have returned) or
2508 // ComplexX87 (because this cannot be passed in a structure).
2509 assert((Accum != Memory && Accum != ComplexX87) &&
2510 "Invalid accumulated classification during merge.");
2511 if (Accum == Field || Field == NoClass)
2512 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002513 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002514 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002515 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002517 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002519 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2520 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002521 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002522 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523}
2524
Chris Lattner5c740f12010-06-30 19:14:05 +00002525void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002526 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 // FIXME: This code can be simplified by introducing a simple value class for
2528 // Class pairs with appropriate constructor methods for the various
2529 // situations.
2530
2531 // FIXME: Some of the split computations are wrong; unaligned vectors
2532 // shouldn't be passed in registers for example, so there is no chance they
2533 // can straddle an eightbyte. Verify & simplify.
2534
2535 Lo = Hi = NoClass;
2536
2537 Class &Current = OffsetBase < 64 ? Lo : Hi;
2538 Current = Memory;
2539
John McCall9dd450b2009-09-21 23:43:11 +00002540 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 BuiltinType::Kind k = BT->getKind();
2542
2543 if (k == BuiltinType::Void) {
2544 Current = NoClass;
2545 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2546 Lo = Integer;
2547 Hi = Integer;
2548 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2549 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002550 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002551 Current = SSE;
2552 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002553 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002554 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002555 Lo = SSE;
2556 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002557 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002558 Lo = X87;
2559 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002560 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002561 Current = SSE;
2562 } else
2563 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002564 }
2565 // FIXME: _Decimal32 and _Decimal64 are SSE.
2566 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002567 return;
2568 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002569
Chris Lattnerd776fb12010-06-28 21:43:59 +00002570 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002571 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002572 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002573 return;
2574 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002575
Chris Lattnerd776fb12010-06-28 21:43:59 +00002576 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002577 Current = Integer;
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->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002582 if (Ty->isMemberFunctionPointerType()) {
2583 if (Has64BitPointers) {
2584 // If Has64BitPointers, this is an {i64, i64}, so classify both
2585 // Lo and Hi now.
2586 Lo = Hi = Integer;
2587 } else {
2588 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2589 // straddles an eightbyte boundary, Hi should be classified as well.
2590 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2591 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2592 if (EB_FuncPtr != EB_ThisAdj) {
2593 Lo = Hi = Integer;
2594 } else {
2595 Current = Integer;
2596 }
2597 }
2598 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002599 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002600 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002601 return;
2602 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002603
Chris Lattnerd776fb12010-06-28 21:43:59 +00002604 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002605 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002606 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2607 // gcc passes the following as integer:
2608 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2609 // 2 bytes - <2 x char>, <1 x short>
2610 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 Current = Integer;
2612
2613 // If this type crosses an eightbyte boundary, it should be
2614 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002615 uint64_t EB_Lo = (OffsetBase) / 64;
2616 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2617 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 Hi = Lo;
2619 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002620 QualType ElementType = VT->getElementType();
2621
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002623 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002624 return;
2625
David Majnemere2ae2282016-03-04 05:26:16 +00002626 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2627 // pass them as integer. For platforms where clang is the de facto
2628 // platform compiler, we must continue to use integer.
2629 if (!classifyIntegerMMXAsSSE() &&
2630 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2631 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2632 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2633 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002634 Current = Integer;
2635 else
2636 Current = SSE;
2637
2638 // If this type crosses an eightbyte boundary, it should be
2639 // split.
2640 if (OffsetBase && OffsetBase != 64)
2641 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002642 } else if (Size == 128 ||
2643 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002644 // Arguments of 256-bits are split into four eightbyte chunks. The
2645 // least significant one belongs to class SSE and all the others to class
2646 // SSEUP. The original Lo and Hi design considers that types can't be
2647 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2648 // This design isn't correct for 256-bits, but since there're no cases
2649 // where the upper parts would need to be inspected, avoid adding
2650 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002651 //
2652 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2653 // registers if they are "named", i.e. not part of the "..." of a
2654 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002655 //
2656 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2657 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002658 Lo = SSE;
2659 Hi = SSEUp;
2660 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002661 return;
2662 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002663
Chris Lattnerd776fb12010-06-28 21:43:59 +00002664 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002665 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666
Chris Lattner2b037972010-07-29 02:01:43 +00002667 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002668 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002669 if (Size <= 64)
2670 Current = Integer;
2671 else if (Size <= 128)
2672 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002673 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002675 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002676 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002677 } else if (ET == getContext().LongDoubleTy) {
2678 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002679 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002680 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002681 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002682 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002683 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002684 Lo = Hi = SSE;
2685 else
2686 llvm_unreachable("unexpected long double representation!");
2687 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688
2689 // If this complex type crosses an eightbyte boundary then it
2690 // should be split.
2691 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002692 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 if (Hi == NoClass && EB_Real != EB_Imag)
2694 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002695
Chris Lattnerd776fb12010-06-28 21:43:59 +00002696 return;
2697 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002698
Chris Lattner2b037972010-07-29 02:01:43 +00002699 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 // Arrays are treated like structures.
2701
Chris Lattner2b037972010-07-29 02:01:43 +00002702 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002703
2704 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002705 // than eight eightbytes, ..., it has class MEMORY.
2706 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 return;
2708
2709 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2710 // fields, it has class MEMORY.
2711 //
2712 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002713 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714 return;
2715
2716 // Otherwise implement simplified merge. We could be smarter about
2717 // this, but it isn't worth it and would be harder to verify.
2718 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002719 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002720 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002721
2722 // The only case a 256-bit wide vector could be used is when the array
2723 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2724 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002725 //
2726 if (Size > 128 &&
2727 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002728 return;
2729
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2731 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002732 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733 Lo = merge(Lo, FieldLo);
2734 Hi = merge(Hi, FieldHi);
2735 if (Lo == Memory || Hi == Memory)
2736 break;
2737 }
2738
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002739 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002740 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002741 return;
2742 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002743
Chris Lattnerd776fb12010-06-28 21:43:59 +00002744 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002745 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002746
2747 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002748 // than eight eightbytes, ..., it has class MEMORY.
2749 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 return;
2751
Anders Carlsson20759ad2009-09-16 15:53:40 +00002752 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2753 // copy constructor or a non-trivial destructor, it is passed by invisible
2754 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002755 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002756 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002757
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002758 const RecordDecl *RD = RT->getDecl();
2759
2760 // Assume variable sized types are passed in memory.
2761 if (RD->hasFlexibleArrayMember())
2762 return;
2763
Chris Lattner2b037972010-07-29 02:01:43 +00002764 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002765
2766 // Reset Lo class, this will be recomputed.
2767 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002768
2769 // If this is a C++ record, classify the bases first.
2770 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002771 for (const auto &I : CXXRD->bases()) {
2772 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002773 "Unexpected base class!");
2774 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002775 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002776
2777 // Classify this field.
2778 //
2779 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2780 // single eightbyte, each is classified separately. Each eightbyte gets
2781 // initialized to class NO_CLASS.
2782 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002783 uint64_t Offset =
2784 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002785 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002786 Lo = merge(Lo, FieldLo);
2787 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002788 if (Lo == Memory || Hi == Memory) {
2789 postMerge(Size, Lo, Hi);
2790 return;
2791 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002792 }
2793 }
2794
2795 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002796 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002797 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002798 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002799 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2800 bool BitField = i->isBitField();
2801
David Majnemerb439dfe2016-08-15 07:20:40 +00002802 // Ignore padding bit-fields.
2803 if (BitField && i->isUnnamedBitfield())
2804 continue;
2805
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002806 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2807 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002808 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002809 // The only case a 256-bit wide vector could be used is when the struct
2810 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2811 // to work for sizes wider than 128, early check and fallback to memory.
2812 //
David Majnemerb229cb02016-08-15 06:39:18 +00002813 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2814 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002815 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002816 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002817 return;
2818 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002819 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002820 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002821 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002822 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002823 return;
2824 }
2825
2826 // Classify this field.
2827 //
2828 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2829 // exceeds a single eightbyte, each is classified
2830 // separately. Each eightbyte gets initialized to class
2831 // NO_CLASS.
2832 Class FieldLo, FieldHi;
2833
2834 // Bit-fields require special handling, they do not force the
2835 // structure to be passed in memory even if unaligned, and
2836 // therefore they can straddle an eightbyte.
2837 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002838 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002839 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002840 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841
2842 uint64_t EB_Lo = Offset / 64;
2843 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002844
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845 if (EB_Lo) {
2846 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2847 FieldLo = NoClass;
2848 FieldHi = Integer;
2849 } else {
2850 FieldLo = Integer;
2851 FieldHi = EB_Hi ? Integer : NoClass;
2852 }
2853 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002854 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002855 Lo = merge(Lo, FieldLo);
2856 Hi = merge(Hi, FieldHi);
2857 if (Lo == Memory || Hi == Memory)
2858 break;
2859 }
2860
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002861 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002862 }
2863}
2864
Chris Lattner22a931e2010-06-29 06:01:59 +00002865ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002866 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2867 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002868 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002869 // Treat an enum type as its underlying type.
2870 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2871 Ty = EnumTy->getDecl()->getIntegerType();
2872
Alex Bradburye41a5e22018-01-12 20:08:16 +00002873 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2874 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002875 }
2876
John McCall7f416cc2015-09-08 08:05:57 +00002877 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002878}
2879
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002880bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2881 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2882 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002883 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002884 if (Size <= 64 || Size > LargestVector)
2885 return true;
2886 }
2887
2888 return false;
2889}
2890
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002891ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2892 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002893 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2894 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002895 //
2896 // This assumption is optimistic, as there could be free registers available
2897 // when we need to pass this argument in memory, and LLVM could try to pass
2898 // the argument in the free register. This does not seem to happen currently,
2899 // but this code would be much safer if we could mark the argument with
2900 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002901 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002902 // Treat an enum type as its underlying type.
2903 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2904 Ty = EnumTy->getDecl()->getIntegerType();
2905
Alex Bradburye41a5e22018-01-12 20:08:16 +00002906 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2907 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002908 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002909
Mark Lacey3825e832013-10-06 01:33:34 +00002910 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002911 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002912
Chris Lattner44c2b902011-05-22 23:21:23 +00002913 // Compute the byval alignment. We specify the alignment of the byval in all
2914 // cases so that the mid-level optimizer knows the alignment of the byval.
2915 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002916
2917 // Attempt to avoid passing indirect results using byval when possible. This
2918 // is important for good codegen.
2919 //
2920 // We do this by coercing the value into a scalar type which the backend can
2921 // handle naturally (i.e., without using byval).
2922 //
2923 // For simplicity, we currently only do this when we have exhausted all of the
2924 // free integer registers. Doing this when there are free integer registers
2925 // would require more care, as we would have to ensure that the coerced value
2926 // did not claim the unused register. That would require either reording the
2927 // arguments to the function (so that any subsequent inreg values came first),
2928 // or only doing this optimization when there were no following arguments that
2929 // might be inreg.
2930 //
2931 // We currently expect it to be rare (particularly in well written code) for
2932 // arguments to be passed on the stack when there are still free integer
2933 // registers available (this would typically imply large structs being passed
2934 // by value), so this seems like a fair tradeoff for now.
2935 //
2936 // We can revisit this if the backend grows support for 'onstack' parameter
2937 // attributes. See PR12193.
2938 if (freeIntRegs == 0) {
2939 uint64_t Size = getContext().getTypeSize(Ty);
2940
2941 // If this type fits in an eightbyte, coerce it into the matching integral
2942 // type, which will end up on the stack (with alignment 8).
2943 if (Align == 8 && Size <= 64)
2944 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2945 Size));
2946 }
2947
John McCall7f416cc2015-09-08 08:05:57 +00002948 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002949}
2950
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002951/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2952/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002953llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002954 // Wrapper structs/arrays that only contain vectors are passed just like
2955 // vectors; strip them off if present.
2956 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2957 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002958
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002959 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002960 if (isa<llvm::VectorType>(IRType) ||
2961 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002962 return IRType;
2963
2964 // We couldn't find the preferred IR vector type for 'Ty'.
2965 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002966 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002967
2968 // Return a LLVM IR vector type based on the size of 'Ty'.
2969 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2970 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002971}
2972
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002973/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2974/// is known to either be off the end of the specified type or being in
2975/// alignment padding. The user type specified is known to be at most 128 bits
2976/// in size, and have passed through X86_64ABIInfo::classify with a successful
2977/// classification that put one of the two halves in the INTEGER class.
2978///
2979/// It is conservatively correct to return false.
2980static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2981 unsigned EndBit, ASTContext &Context) {
2982 // If the bytes being queried are off the end of the type, there is no user
2983 // data hiding here. This handles analysis of builtins, vectors and other
2984 // types that don't contain interesting padding.
2985 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2986 if (TySize <= StartBit)
2987 return true;
2988
Chris Lattner98076a22010-07-29 07:43:55 +00002989 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2990 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2991 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2992
2993 // Check each element to see if the element overlaps with the queried range.
2994 for (unsigned i = 0; i != NumElts; ++i) {
2995 // If the element is after the span we care about, then we're done..
2996 unsigned EltOffset = i*EltSize;
2997 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002998
Chris Lattner98076a22010-07-29 07:43:55 +00002999 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3000 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3001 EndBit-EltOffset, Context))
3002 return false;
3003 }
3004 // If it overlaps no elements, then it is safe to process as padding.
3005 return true;
3006 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003007
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003008 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3009 const RecordDecl *RD = RT->getDecl();
3010 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003011
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003012 // If this is a C++ record, check the bases first.
3013 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003014 for (const auto &I : CXXRD->bases()) {
3015 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003016 "Unexpected base class!");
3017 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003018 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003019
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003020 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003021 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003024 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003025 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003026 EndBit-BaseOffset, Context))
3027 return false;
3028 }
3029 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003030
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003031 // Verify that no field has data that overlaps the region of interest. Yes
3032 // this could be sped up a lot by being smarter about queried fields,
3033 // however we're only looking at structs up to 16 bytes, so we don't care
3034 // much.
3035 unsigned idx = 0;
3036 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3037 i != e; ++i, ++idx) {
3038 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003040 // If we found a field after the region we care about, then we're done.
3041 if (FieldOffset >= EndBit) break;
3042
3043 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3044 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3045 Context))
3046 return false;
3047 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003048
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003049 // If nothing in this record overlapped the area of interest, then we're
3050 // clean.
3051 return true;
3052 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003053
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003054 return false;
3055}
3056
Chris Lattnere556a712010-07-29 18:39:32 +00003057/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3058/// float member at the specified offset. For example, {int,{float}} has a
3059/// float at offset 4. It is conservatively correct for this routine to return
3060/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003061static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003062 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003063 // Base case if we find a float.
3064 if (IROffset == 0 && IRType->isFloatTy())
3065 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003066
Chris Lattnere556a712010-07-29 18:39:32 +00003067 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003068 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003069 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3070 unsigned Elt = SL->getElementContainingOffset(IROffset);
3071 IROffset -= SL->getElementOffset(Elt);
3072 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3073 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003074
Chris Lattnere556a712010-07-29 18:39:32 +00003075 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003076 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3077 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003078 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3079 IROffset -= IROffset/EltSize*EltSize;
3080 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3081 }
3082
3083 return false;
3084}
3085
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003086
3087/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3088/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003089llvm::Type *X86_64ABIInfo::
3090GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003091 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003092 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003093 // pass as float if the last 4 bytes is just padding. This happens for
3094 // structs that contain 3 floats.
3095 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3096 SourceOffset*8+64, getContext()))
3097 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003098
Chris Lattnere556a712010-07-29 18:39:32 +00003099 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3100 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3101 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003102 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3103 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003104 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003105
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003106 return llvm::Type::getDoubleTy(getVMContext());
3107}
3108
3109
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003110/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3111/// an 8-byte GPR. This means that we either have a scalar or we are talking
3112/// about the high or low part of an up-to-16-byte struct. This routine picks
3113/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003114/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3115/// etc).
3116///
3117/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3118/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3119/// the 8-byte value references. PrefType may be null.
3120///
Alp Toker9907f082014-07-09 14:06:35 +00003121/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003122/// an offset into this that we're processing (which is always either 0 or 8).
3123///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003124llvm::Type *X86_64ABIInfo::
3125GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003126 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003127 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3128 // returning an 8-byte unit starting with it. See if we can safely use it.
3129 if (IROffset == 0) {
3130 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003131 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3132 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003133 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003134
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003135 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3136 // goodness in the source type is just tail padding. This is allowed to
3137 // kick in for struct {double,int} on the int, but not on
3138 // struct{double,int,int} because we wouldn't return the second int. We
3139 // have to do this analysis on the source type because we can't depend on
3140 // unions being lowered a specific way etc.
3141 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003142 IRType->isIntegerTy(32) ||
3143 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3144 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3145 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003146
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003147 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3148 SourceOffset*8+64, getContext()))
3149 return IRType;
3150 }
3151 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003152
Chris Lattner2192fe52011-07-18 04:24:23 +00003153 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003154 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003155 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003156 if (IROffset < SL->getSizeInBytes()) {
3157 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3158 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003159
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003160 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3161 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003162 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003163 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003164
Chris Lattner2192fe52011-07-18 04:24:23 +00003165 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003166 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003167 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003168 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003169 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3170 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003171 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003172
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003173 // Okay, we don't have any better idea of what to pass, so we pass this in an
3174 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003175 unsigned TySizeInBytes =
3176 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003177
Chris Lattner3f763422010-07-29 17:34:39 +00003178 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003179
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003180 // It is always safe to classify this as an integer type up to i64 that
3181 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003182 return llvm::IntegerType::get(getVMContext(),
3183 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003184}
3185
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003186
3187/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3188/// be used as elements of a two register pair to pass or return, return a
3189/// first class aggregate to represent them. For example, if the low part of
3190/// a by-value argument should be passed as i32* and the high part as float,
3191/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003192static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003193GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003194 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003195 // In order to correctly satisfy the ABI, we need to the high part to start
3196 // at offset 8. If the high and low parts we inferred are both 4-byte types
3197 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3198 // the second element at offset 8. Check for this:
3199 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3200 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003201 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003202 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003203
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003204 // To handle this, we have to increase the size of the low part so that the
3205 // second element will start at an 8 byte offset. We can't increase the size
3206 // of the second element because it might make us access off the end of the
3207 // struct.
3208 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003209 // There are usually two sorts of types the ABI generation code can produce
3210 // for the low part of a pair that aren't 8 bytes in size: float or
3211 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3212 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003213 // Promote these to a larger type.
3214 if (Lo->isFloatTy())
3215 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3216 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003217 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3218 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003219 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3220 }
3221 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003222
Serge Guelton1d993272017-05-09 19:31:30 +00003223 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003224
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003225 // Verify that the second element is at an 8-byte offset.
3226 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3227 "Invalid x86-64 argument pair!");
3228 return Result;
3229}
3230
Chris Lattner31faff52010-07-28 23:06:14 +00003231ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003232classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003233 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3234 // classification algorithm.
3235 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003236 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003237
3238 // Check some invariants.
3239 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003240 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3241
Craig Topper8a13c412014-05-21 05:09:00 +00003242 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003243 switch (Lo) {
3244 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003245 if (Hi == NoClass)
3246 return ABIArgInfo::getIgnore();
3247 // If the low part is just padding, it takes no register, leave ResType
3248 // null.
3249 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3250 "Unknown missing lo part");
3251 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003252
3253 case SSEUp:
3254 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003255 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003256
3257 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3258 // hidden argument.
3259 case Memory:
3260 return getIndirectReturnResult(RetTy);
3261
3262 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3263 // available register of the sequence %rax, %rdx is used.
3264 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003265 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003266
Chris Lattner1f3a0632010-07-29 21:42:50 +00003267 // If we have a sign or zero extended integer, make sure to return Extend
3268 // so that the parameter gets the right LLVM IR attributes.
3269 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3270 // Treat an enum type as its underlying type.
3271 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3272 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003273
Chris Lattner1f3a0632010-07-29 21:42:50 +00003274 if (RetTy->isIntegralOrEnumerationType() &&
3275 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003276 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003277 }
Chris Lattner31faff52010-07-28 23:06:14 +00003278 break;
3279
3280 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3281 // available SSE register of the sequence %xmm0, %xmm1 is used.
3282 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003283 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003284 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003285
3286 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3287 // returned on the X87 stack in %st0 as 80-bit x87 number.
3288 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003289 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003290 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003291
3292 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3293 // part of the value is returned in %st0 and the imaginary part in
3294 // %st1.
3295 case ComplexX87:
3296 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003297 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003298 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003299 break;
3300 }
3301
Craig Topper8a13c412014-05-21 05:09:00 +00003302 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003303 switch (Hi) {
3304 // Memory was handled previously and X87 should
3305 // never occur as a hi class.
3306 case Memory:
3307 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003308 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003309
3310 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003311 case NoClass:
3312 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003313
Chris Lattner52b3c132010-09-01 00:20:33 +00003314 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003315 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003316 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3317 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003318 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003319 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003320 HighPart = GetSSETypeAtOffset(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;
3324
3325 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003326 // is passed in the next available eightbyte chunk if the last used
3327 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003328 //
Chris Lattner57540c52011-04-15 05:22:18 +00003329 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003330 case SSEUp:
3331 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003332 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003333 break;
3334
3335 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3336 // returned together with the previous X87 value in %st0.
3337 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003338 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003339 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003340 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003341 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003342 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003343 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003344 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3345 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003346 }
Chris Lattner31faff52010-07-28 23:06:14 +00003347 break;
3348 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003349
Chris Lattner52b3c132010-09-01 00:20:33 +00003350 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003351 // known to pass in the high eightbyte of the result. We do this by forming a
3352 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003353 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003354 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003355
Chris Lattner1f3a0632010-07-29 21:42:50 +00003356 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003357}
3358
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003359ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003360 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3361 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003362 const
3363{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003364 Ty = useFirstFieldIfTransparentUnion(Ty);
3365
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003367 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003369 // Check some invariants.
3370 // FIXME: Enforce these by construction.
3371 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003372 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3373
3374 neededInt = 0;
3375 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003376 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377 switch (Lo) {
3378 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003379 if (Hi == NoClass)
3380 return ABIArgInfo::getIgnore();
3381 // If the low part is just padding, it takes no register, leave ResType
3382 // null.
3383 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3384 "Unknown missing lo part");
3385 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003386
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003387 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3388 // on the stack.
3389 case Memory:
3390
3391 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3392 // COMPLEX_X87, it is passed in memory.
3393 case X87:
3394 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003395 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003396 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003397 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003398
3399 case SSEUp:
3400 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003401 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003402
3403 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3404 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3405 // and %r9 is used.
3406 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003407 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003408
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003409 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003410 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003411
3412 // If we have a sign or zero extended integer, make sure to return Extend
3413 // so that the parameter gets the right LLVM IR attributes.
3414 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3415 // Treat an enum type as its underlying type.
3416 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3417 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003418
Chris Lattner1f3a0632010-07-29 21:42:50 +00003419 if (Ty->isIntegralOrEnumerationType() &&
3420 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003421 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003422 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003423
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424 break;
3425
3426 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3427 // available SSE register is used, the registers are taken in the
3428 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003429 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003430 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003431 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003432 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433 break;
3434 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003435 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436
Craig Topper8a13c412014-05-21 05:09:00 +00003437 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003438 switch (Hi) {
3439 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003440 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441 // which is passed in memory.
3442 case Memory:
3443 case X87:
3444 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003445 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003446
3447 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003448
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003449 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003451 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003452 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003453
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003454 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3455 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003456 break;
3457
3458 // X87Up generally doesn't occur here (long double is passed in
3459 // memory), except in situations involving unions.
3460 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003461 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003462 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003463
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003464 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3465 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003466
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003467 ++neededSSE;
3468 break;
3469
3470 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3471 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003472 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003473 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003474 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003475 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003476 break;
3477 }
3478
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003479 // If a high part was specified, merge it together with the low part. It is
3480 // known to pass in the high eightbyte of the result. We do this by forming a
3481 // first class struct aggregate with the high and low part: {low, high}
3482 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003483 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003484
Chris Lattner1f3a0632010-07-29 21:42:50 +00003485 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003486}
3487
Erich Keane757d3172016-11-02 18:29:35 +00003488ABIArgInfo
3489X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3490 unsigned &NeededSSE) const {
3491 auto RT = Ty->getAs<RecordType>();
3492 assert(RT && "classifyRegCallStructType only valid with struct types");
3493
3494 if (RT->getDecl()->hasFlexibleArrayMember())
3495 return getIndirectReturnResult(Ty);
3496
3497 // Sum up bases
3498 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3499 if (CXXRD->isDynamicClass()) {
3500 NeededInt = NeededSSE = 0;
3501 return getIndirectReturnResult(Ty);
3502 }
3503
3504 for (const auto &I : CXXRD->bases())
3505 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3506 .isIndirect()) {
3507 NeededInt = NeededSSE = 0;
3508 return getIndirectReturnResult(Ty);
3509 }
3510 }
3511
3512 // Sum up members
3513 for (const auto *FD : RT->getDecl()->fields()) {
3514 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3515 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3516 .isIndirect()) {
3517 NeededInt = NeededSSE = 0;
3518 return getIndirectReturnResult(Ty);
3519 }
3520 } else {
3521 unsigned LocalNeededInt, LocalNeededSSE;
3522 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3523 LocalNeededSSE, true)
3524 .isIndirect()) {
3525 NeededInt = NeededSSE = 0;
3526 return getIndirectReturnResult(Ty);
3527 }
3528 NeededInt += LocalNeededInt;
3529 NeededSSE += LocalNeededSSE;
3530 }
3531 }
3532
3533 return ABIArgInfo::getDirect();
3534}
3535
3536ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3537 unsigned &NeededInt,
3538 unsigned &NeededSSE) const {
3539
3540 NeededInt = 0;
3541 NeededSSE = 0;
3542
3543 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3544}
3545
Chris Lattner22326a12010-07-29 02:31:05 +00003546void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003547
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003548 const unsigned CallingConv = FI.getCallingConvention();
3549 // It is possible to force Win64 calling convention on any x86_64 target by
3550 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3551 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3552 if (CallingConv == llvm::CallingConv::Win64) {
3553 WinX86_64ABIInfo Win64ABIInfo(CGT);
3554 Win64ABIInfo.computeInfo(FI);
3555 return;
3556 }
3557
3558 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003559
3560 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003561 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3562 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3563 unsigned NeededInt, NeededSSE;
3564
Akira Hatanakad791e922018-03-19 17:38:40 +00003565 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003566 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3567 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3568 FI.getReturnInfo() =
3569 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3570 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3571 FreeIntRegs -= NeededInt;
3572 FreeSSERegs -= NeededSSE;
3573 } else {
3574 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3575 }
3576 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3577 // Complex Long Double Type is passed in Memory when Regcall
3578 // calling convention is used.
3579 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3580 if (getContext().getCanonicalType(CT->getElementType()) ==
3581 getContext().LongDoubleTy)
3582 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3583 } else
3584 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3585 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003586
3587 // If the return value is indirect, then the hidden argument is consuming one
3588 // integer register.
3589 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003590 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003591
Peter Collingbournef7706832014-12-12 23:41:25 +00003592 // The chain argument effectively gives us another free register.
3593 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003594 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003595
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003596 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003597 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3598 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003599 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003600 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003601 it != ie; ++it, ++ArgNo) {
3602 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003603
Erich Keane757d3172016-11-02 18:29:35 +00003604 if (IsRegCall && it->type->isStructureOrClassType())
3605 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3606 else
3607 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3608 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003609
3610 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3611 // eightbyte of an argument, the whole argument is passed on the
3612 // stack. If registers have already been assigned for some
3613 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003614 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3615 FreeIntRegs -= NeededInt;
3616 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003617 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003618 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003619 }
3620 }
3621}
3622
John McCall7f416cc2015-09-08 08:05:57 +00003623static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3624 Address VAListAddr, QualType Ty) {
3625 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3626 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003627 llvm::Value *overflow_arg_area =
3628 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3629
3630 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3631 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003632 // It isn't stated explicitly in the standard, but in practice we use
3633 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003634 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3635 if (Align > CharUnits::fromQuantity(8)) {
3636 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3637 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003638 }
3639
3640 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003641 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003642 llvm::Value *Res =
3643 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003644 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003645
3646 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3647 // l->overflow_arg_area + sizeof(type).
3648 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3649 // an 8 byte boundary.
3650
3651 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003652 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003653 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3655 "overflow_arg_area.next");
3656 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3657
3658 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003659 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003660}
3661
John McCall7f416cc2015-09-08 08:05:57 +00003662Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3663 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003664 // Assume that va_list type is correct; should be pointer to LLVM type:
3665 // struct {
3666 // i32 gp_offset;
3667 // i32 fp_offset;
3668 // i8* overflow_arg_area;
3669 // i8* reg_save_area;
3670 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003671 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003672
John McCall7f416cc2015-09-08 08:05:57 +00003673 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003674 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003675 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003676
3677 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3678 // in the registers. If not go to step 7.
3679 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003680 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003681
3682 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3683 // general purpose registers needed to pass type and num_fp to hold
3684 // the number of floating point registers needed.
3685
3686 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3687 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3688 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3689 //
3690 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3691 // register save space).
3692
Craig Topper8a13c412014-05-21 05:09:00 +00003693 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003694 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3695 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003696 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003697 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003698 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3699 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003700 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003701 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3702 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003703 }
3704
3705 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003706 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003707 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3708 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003709 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3710 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003711 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3712 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003713 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3714 }
3715
3716 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3717 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3718 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3719 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3720
3721 // Emit code to load the value if it was passed in registers.
3722
3723 CGF.EmitBlock(InRegBlock);
3724
3725 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3726 // an offset of l->gp_offset and/or l->fp_offset. This may require
3727 // copying to a temporary location in case the parameter is passed
3728 // in different register classes or requires an alignment greater
3729 // than 8 for general purpose registers and 16 for XMM registers.
3730 //
3731 // FIXME: This really results in shameful code when we end up needing to
3732 // collect arguments from different places; often what should result in a
3733 // simple assembling of a structure from scattered addresses has many more
3734 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003735 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003736 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3737 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3738 "reg_save_area");
3739
3740 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003741 if (neededInt && neededSSE) {
3742 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003743 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003744 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003745 Address Tmp = CGF.CreateMemTemp(Ty);
3746 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003747 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003748 llvm::Type *TyLo = ST->getElementType(0);
3749 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003750 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003751 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003752 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3753 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003754 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3755 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003756 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3757 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003758
John McCall7f416cc2015-09-08 08:05:57 +00003759 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003760 // FIXME: Our choice of alignment here and below is probably pessimistic.
3761 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3762 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3763 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003764 CGF.Builder.CreateStore(V,
3765 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3766
3767 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003768 V = CGF.Builder.CreateAlignedLoad(
3769 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3770 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003771 CharUnits Offset = CharUnits::fromQuantity(
3772 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3773 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3774
3775 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003776 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003777 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3778 CharUnits::fromQuantity(8));
3779 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003780
3781 // Copy to a temporary if necessary to ensure the appropriate alignment.
3782 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003783 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003784 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003785 CharUnits TyAlign = SizeAlign.second;
3786
3787 // Copy into a temporary if the type is more aligned than the
3788 // register save area.
3789 if (TyAlign.getQuantity() > 8) {
3790 Address Tmp = CGF.CreateMemTemp(Ty);
3791 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003792 RegAddr = Tmp;
3793 }
John McCall7f416cc2015-09-08 08:05:57 +00003794
Chris Lattner0cf24192010-06-28 20:05:43 +00003795 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003796 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3797 CharUnits::fromQuantity(16));
3798 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003799 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003800 assert(neededSSE == 2 && "Invalid number of needed registers!");
3801 // SSE registers are spaced 16 bytes apart in the register save
3802 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003803 // The ABI isn't explicit about this, but it seems reasonable
3804 // to assume that the slots are 16-byte aligned, since the stack is
3805 // naturally 16-byte aligned and the prologue is expected to store
3806 // all the SSE registers to the RSA.
3807 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3808 CharUnits::fromQuantity(16));
3809 Address RegAddrHi =
3810 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3811 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003812 llvm::Type *ST = AI.canHaveCoerceToType()
3813 ? AI.getCoerceToType()
3814 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003815 llvm::Value *V;
3816 Address Tmp = CGF.CreateMemTemp(Ty);
3817 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003818 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3819 RegAddrLo, ST->getStructElementType(0)));
John McCall7f416cc2015-09-08 08:05:57 +00003820 CGF.Builder.CreateStore(V,
3821 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
Erich Keane24e68402018-02-02 15:53:35 +00003822 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3823 RegAddrHi, ST->getStructElementType(1)));
John McCall7f416cc2015-09-08 08:05:57 +00003824 CGF.Builder.CreateStore(V,
3825 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3826
3827 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003828 }
3829
3830 // AMD64-ABI 3.5.7p5: Step 5. Set:
3831 // l->gp_offset = l->gp_offset + num_gp * 8
3832 // l->fp_offset = l->fp_offset + num_fp * 16.
3833 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003834 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003835 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3836 gp_offset_p);
3837 }
3838 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003839 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003840 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3841 fp_offset_p);
3842 }
3843 CGF.EmitBranch(ContBlock);
3844
3845 // Emit code to load the value if it was passed in memory.
3846
3847 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003848 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003849
3850 // Return the appropriate result.
3851
3852 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003853 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3854 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003855 return ResAddr;
3856}
3857
Charles Davisc7d5c942015-09-17 20:55:33 +00003858Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3859 QualType Ty) const {
3860 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3861 CGF.getContext().getTypeInfoInChars(Ty),
3862 CharUnits::fromQuantity(8),
3863 /*allowHigherAlign*/ false);
3864}
3865
Erich Keane521ed962017-01-05 00:20:51 +00003866ABIArgInfo
3867WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3868 const ABIArgInfo &current) const {
3869 // Assumes vectorCall calling convention.
3870 const Type *Base = nullptr;
3871 uint64_t NumElts = 0;
3872
3873 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3874 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3875 FreeSSERegs -= NumElts;
3876 return getDirectX86Hva();
3877 }
3878 return current;
3879}
3880
Reid Kleckner80944df2014-10-31 22:00:51 +00003881ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003882 bool IsReturnType, bool IsVectorCall,
3883 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003884
3885 if (Ty->isVoidType())
3886 return ABIArgInfo::getIgnore();
3887
3888 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3889 Ty = EnumTy->getDecl()->getIntegerType();
3890
Reid Kleckner80944df2014-10-31 22:00:51 +00003891 TypeInfo Info = getContext().getTypeInfo(Ty);
3892 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003893 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003894
Reid Kleckner9005f412014-05-02 00:51:20 +00003895 const RecordType *RT = Ty->getAs<RecordType>();
3896 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003897 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003898 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003899 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003900 }
3901
3902 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003903 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003904
Reid Kleckner9005f412014-05-02 00:51:20 +00003905 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003906
Reid Kleckner80944df2014-10-31 22:00:51 +00003907 const Type *Base = nullptr;
3908 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003909 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3910 // other targets.
3911 if ((IsVectorCall || IsRegCall) &&
3912 isHomogeneousAggregate(Ty, Base, NumElts)) {
3913 if (IsRegCall) {
3914 if (FreeSSERegs >= NumElts) {
3915 FreeSSERegs -= NumElts;
3916 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3917 return ABIArgInfo::getDirect();
3918 return ABIArgInfo::getExpand();
3919 }
3920 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3921 } else if (IsVectorCall) {
3922 if (FreeSSERegs >= NumElts &&
3923 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3924 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003925 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003926 } else if (IsReturnType) {
3927 return ABIArgInfo::getExpand();
3928 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3929 // HVAs are delayed and reclassified in the 2nd step.
3930 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3931 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003932 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003933 }
3934
Reid Klecknerec87fec2014-05-02 01:17:12 +00003935 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003936 // If the member pointer is represented by an LLVM int or ptr, pass it
3937 // directly.
3938 llvm::Type *LLTy = CGT.ConvertType(Ty);
3939 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3940 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003941 }
3942
Michael Kuperstein4f818702015-02-24 09:35:58 +00003943 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003944 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3945 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003946 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003947 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003948
Reid Kleckner9005f412014-05-02 00:51:20 +00003949 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003950 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003951 }
3952
Julien Lerouge10dcff82014-08-27 00:36:55 +00003953 // Bool type is always extended to the ABI, other builtin types are not
3954 // extended.
3955 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3956 if (BT && BT->getKind() == BuiltinType::Bool)
Alex Bradburye41a5e22018-01-12 20:08:16 +00003957 return ABIArgInfo::getExtend(Ty);
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003958
Reid Kleckner11a17192015-10-28 22:29:52 +00003959 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3960 // passes them indirectly through memory.
3961 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3962 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003963 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003964 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3965 }
3966
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003967 return ABIArgInfo::getDirect();
3968}
3969
Erich Keane521ed962017-01-05 00:20:51 +00003970void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3971 unsigned FreeSSERegs,
3972 bool IsVectorCall,
3973 bool IsRegCall) const {
3974 unsigned Count = 0;
3975 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003976 // Vectorcall in x64 only permits the first 6 arguments to be passed
3977 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003978 if (Count < VectorcallMaxParamNumAsReg)
3979 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3980 else {
3981 // Since these cannot be passed in registers, pretend no registers
3982 // are left.
3983 unsigned ZeroSSERegsAvail = 0;
3984 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3985 IsVectorCall, IsRegCall);
3986 }
3987 ++Count;
3988 }
3989
Erich Keane521ed962017-01-05 00:20:51 +00003990 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003991 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003992 }
3993}
3994
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003995void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003996 bool IsVectorCall =
3997 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003998 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003999
Erich Keane757d3172016-11-02 18:29:35 +00004000 unsigned FreeSSERegs = 0;
4001 if (IsVectorCall) {
4002 // We can use up to 4 SSE return registers with vectorcall.
4003 FreeSSERegs = 4;
4004 } else if (IsRegCall) {
4005 // RegCall gives us 16 SSE registers.
4006 FreeSSERegs = 16;
4007 }
4008
Reid Kleckner80944df2014-10-31 22:00:51 +00004009 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004010 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4011 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004012
Erich Keane757d3172016-11-02 18:29:35 +00004013 if (IsVectorCall) {
4014 // We can use up to 6 SSE register parameters with vectorcall.
4015 FreeSSERegs = 6;
4016 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004017 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004018 FreeSSERegs = 16;
4019 }
4020
Erich Keane521ed962017-01-05 00:20:51 +00004021 if (IsVectorCall) {
4022 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4023 } else {
4024 for (auto &I : FI.arguments())
4025 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4026 }
4027
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004028}
4029
John McCall7f416cc2015-09-08 08:05:57 +00004030Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4031 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004032
4033 bool IsIndirect = false;
4034
4035 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4036 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4037 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4038 uint64_t Width = getContext().getTypeSize(Ty);
4039 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4040 }
4041
4042 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004043 CGF.getContext().getTypeInfoInChars(Ty),
4044 CharUnits::fromQuantity(8),
4045 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004046}
Chris Lattner0cf24192010-06-28 20:05:43 +00004047
John McCallea8d8bb2010-03-11 00:10:12 +00004048// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004049namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004050/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4051class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004052 bool IsSoftFloatABI;
4053
4054 CharUnits getParamTypeAlignment(QualType Ty) const;
4055
John McCallea8d8bb2010-03-11 00:10:12 +00004056public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004057 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4058 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004059
John McCall7f416cc2015-09-08 08:05:57 +00004060 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4061 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004062};
4063
4064class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4065public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004066 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4067 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004068
Craig Topper4f12f102014-03-12 06:41:41 +00004069 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004070 // This is recovered from gcc output.
4071 return 1; // r1 is the dedicated stack pointer
4072 }
4073
4074 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004075 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004076};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004077}
John McCallea8d8bb2010-03-11 00:10:12 +00004078
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004079CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4080 // Complex types are passed just like their elements
4081 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4082 Ty = CTy->getElementType();
4083
4084 if (Ty->isVectorType())
4085 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4086 : 4);
4087
4088 // For single-element float/vector structs, we consider the whole type
4089 // to have the same alignment requirements as its single element.
4090 const Type *AlignTy = nullptr;
4091 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4092 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4093 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4094 (BT && BT->isFloatingPoint()))
4095 AlignTy = EltType;
4096 }
4097
4098 if (AlignTy)
4099 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4100 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004101}
John McCallea8d8bb2010-03-11 00:10:12 +00004102
James Y Knight29b5f082016-02-24 02:59:33 +00004103// TODO: this implementation is now likely redundant with
4104// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004105Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4106 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004107 if (getTarget().getTriple().isOSDarwin()) {
4108 auto TI = getContext().getTypeInfoInChars(Ty);
4109 TI.second = getParamTypeAlignment(Ty);
4110
4111 CharUnits SlotSize = CharUnits::fromQuantity(4);
4112 return emitVoidPtrVAArg(CGF, VAList, Ty,
4113 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4114 /*AllowHigherAlign=*/true);
4115 }
4116
Roman Divacky039b9702016-02-20 08:31:24 +00004117 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004118 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4119 // TODO: Implement this. For now ignore.
4120 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004121 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004122 }
4123
John McCall7f416cc2015-09-08 08:05:57 +00004124 // struct __va_list_tag {
4125 // unsigned char gpr;
4126 // unsigned char fpr;
4127 // unsigned short reserved;
4128 // void *overflow_arg_area;
4129 // void *reg_save_area;
4130 // };
4131
Roman Divacky8a12d842014-11-03 18:32:54 +00004132 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004133 bool isInt =
4134 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004135 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004136
4137 // All aggregates are passed indirectly? That doesn't seem consistent
4138 // with the argument-lowering code.
4139 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004140
4141 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004142
4143 // The calling convention either uses 1-2 GPRs or 1 FPR.
4144 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004145 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004146 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4147 } else {
4148 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004149 }
John McCall7f416cc2015-09-08 08:05:57 +00004150
4151 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4152
4153 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004154 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004155 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4156 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4157 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004158
Eric Christopher7565e0d2015-05-29 23:09:49 +00004159 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004160 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004161
4162 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4163 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4164 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4165
4166 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4167
John McCall7f416cc2015-09-08 08:05:57 +00004168 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4169 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004170
John McCall7f416cc2015-09-08 08:05:57 +00004171 // Case 1: consume registers.
4172 Address RegAddr = Address::invalid();
4173 {
4174 CGF.EmitBlock(UsingRegs);
4175
4176 Address RegSaveAreaPtr =
4177 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4178 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4179 CharUnits::fromQuantity(8));
4180 assert(RegAddr.getElementType() == CGF.Int8Ty);
4181
4182 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004183 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004184 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4185 CharUnits::fromQuantity(32));
4186 }
4187
4188 // Get the address of the saved value by scaling the number of
4189 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004190 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004191 llvm::Value *RegOffset =
4192 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4193 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4194 RegAddr.getPointer(), RegOffset),
4195 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4196 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4197
4198 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004199 NumRegs =
4200 Builder.CreateAdd(NumRegs,
4201 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004202 Builder.CreateStore(NumRegs, NumRegsAddr);
4203
4204 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004205 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004206
John McCall7f416cc2015-09-08 08:05:57 +00004207 // Case 2: consume space in the overflow area.
4208 Address MemAddr = Address::invalid();
4209 {
4210 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004211
Roman Divacky039b9702016-02-20 08:31:24 +00004212 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4213
John McCall7f416cc2015-09-08 08:05:57 +00004214 // Everything in the overflow area is rounded up to a size of at least 4.
4215 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4216
4217 CharUnits Size;
4218 if (!isIndirect) {
4219 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004220 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004221 } else {
4222 Size = CGF.getPointerSize();
4223 }
4224
4225 Address OverflowAreaAddr =
4226 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004227 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004228 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004229 // Round up address of argument to alignment
4230 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4231 if (Align > OverflowAreaAlign) {
4232 llvm::Value *Ptr = OverflowArea.getPointer();
4233 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4234 Align);
4235 }
4236
John McCall7f416cc2015-09-08 08:05:57 +00004237 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4238
4239 // Increase the overflow area.
4240 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4241 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4242 CGF.EmitBranch(Cont);
4243 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004244
4245 CGF.EmitBlock(Cont);
4246
John McCall7f416cc2015-09-08 08:05:57 +00004247 // Merge the cases with a phi.
4248 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4249 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004250
John McCall7f416cc2015-09-08 08:05:57 +00004251 // Load the pointer if the argument was passed indirectly.
4252 if (isIndirect) {
4253 Result = Address(Builder.CreateLoad(Result, "aggr"),
4254 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004255 }
4256
4257 return Result;
4258}
4259
John McCallea8d8bb2010-03-11 00:10:12 +00004260bool
4261PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4262 llvm::Value *Address) const {
4263 // This is calculated from the LLVM and GCC tables and verified
4264 // against gcc output. AFAIK all ABIs use the same encoding.
4265
4266 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004267
Chris Lattnerece04092012-02-07 00:39:47 +00004268 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004269 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4270 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4271 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4272
4273 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004274 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004275
4276 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004277 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004278
4279 // 64-76 are various 4-byte special-purpose registers:
4280 // 64: mq
4281 // 65: lr
4282 // 66: ctr
4283 // 67: ap
4284 // 68-75 cr0-7
4285 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004286 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004287
4288 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004289 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004290
4291 // 109: vrsave
4292 // 110: vscr
4293 // 111: spe_acc
4294 // 112: spefscr
4295 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004296 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004297
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004298 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004299}
4300
Roman Divackyd966e722012-05-09 18:22:46 +00004301// PowerPC-64
4302
4303namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004304/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004305class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004306public:
4307 enum ABIKind {
4308 ELFv1 = 0,
4309 ELFv2
4310 };
4311
4312private:
4313 static const unsigned GPRBits = 64;
4314 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004315 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004316 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004317
4318 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4319 // will be passed in a QPX register.
4320 bool IsQPXVectorTy(const Type *Ty) const {
4321 if (!HasQPX)
4322 return false;
4323
4324 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4325 unsigned NumElements = VT->getNumElements();
4326 if (NumElements == 1)
4327 return false;
4328
4329 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4330 if (getContext().getTypeSize(Ty) <= 256)
4331 return true;
4332 } else if (VT->getElementType()->
4333 isSpecificBuiltinType(BuiltinType::Float)) {
4334 if (getContext().getTypeSize(Ty) <= 128)
4335 return true;
4336 }
4337 }
4338
4339 return false;
4340 }
4341
4342 bool IsQPXVectorTy(QualType Ty) const {
4343 return IsQPXVectorTy(Ty.getTypePtr());
4344 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004345
4346public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004347 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4348 bool SoftFloatABI)
4349 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4350 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004351
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004352 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004353 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004354
4355 ABIArgInfo classifyReturnType(QualType RetTy) const;
4356 ABIArgInfo classifyArgumentType(QualType Ty) const;
4357
Reid Klecknere9f6a712014-10-31 17:10:41 +00004358 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4359 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4360 uint64_t Members) const override;
4361
Bill Schmidt84d37792012-10-12 19:26:17 +00004362 // TODO: We can add more logic to computeInfo to improve performance.
4363 // Example: For aggregate arguments that fit in a register, we could
4364 // use getDirectInReg (as is done below for structs containing a single
4365 // floating-point value) to avoid pushing them to memory on function
4366 // entry. This would require changing the logic in PPCISelLowering
4367 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004368 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004369 if (!getCXXABI().classifyReturnType(FI))
4370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004371 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004372 // We rely on the default argument classification for the most part.
4373 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004374 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004375 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004376 if (T) {
4377 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004378 if (IsQPXVectorTy(T) ||
4379 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004380 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004381 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004382 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004383 continue;
4384 }
4385 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004386 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004387 }
4388 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004389
John McCall7f416cc2015-09-08 08:05:57 +00004390 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4391 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004392};
4393
4394class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004395
Bill Schmidt25cb3492012-10-03 19:18:57 +00004396public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004397 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004398 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4399 bool SoftFloatABI)
4400 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4401 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004402
Craig Topper4f12f102014-03-12 06:41:41 +00004403 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004404 // This is recovered from gcc output.
4405 return 1; // r1 is the dedicated stack pointer
4406 }
4407
4408 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004409 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004410};
4411
Roman Divackyd966e722012-05-09 18:22:46 +00004412class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4413public:
4414 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4415
Craig Topper4f12f102014-03-12 06:41:41 +00004416 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004417 // This is recovered from gcc output.
4418 return 1; // r1 is the dedicated stack pointer
4419 }
4420
4421 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004422 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004423};
4424
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004425}
Roman Divackyd966e722012-05-09 18:22:46 +00004426
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004427// Return true if the ABI requires Ty to be passed sign- or zero-
4428// extended to 64 bits.
4429bool
4430PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4431 // Treat an enum type as its underlying type.
4432 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4433 Ty = EnumTy->getDecl()->getIntegerType();
4434
4435 // Promotable integer types are required to be promoted by the ABI.
4436 if (Ty->isPromotableIntegerType())
4437 return true;
4438
4439 // In addition to the usual promotable integer types, we also need to
4440 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4441 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4442 switch (BT->getKind()) {
4443 case BuiltinType::Int:
4444 case BuiltinType::UInt:
4445 return true;
4446 default:
4447 break;
4448 }
4449
4450 return false;
4451}
4452
John McCall7f416cc2015-09-08 08:05:57 +00004453/// isAlignedParamType - Determine whether a type requires 16-byte or
4454/// higher alignment in the parameter area. Always returns at least 8.
4455CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004456 // Complex types are passed just like their elements.
4457 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4458 Ty = CTy->getElementType();
4459
4460 // Only vector types of size 16 bytes need alignment (larger types are
4461 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004462 if (IsQPXVectorTy(Ty)) {
4463 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004464 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004465
John McCall7f416cc2015-09-08 08:05:57 +00004466 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004467 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004468 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004469 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004470
4471 // For single-element float/vector structs, we consider the whole type
4472 // to have the same alignment requirements as its single element.
4473 const Type *AlignAsType = nullptr;
4474 const Type *EltType = isSingleElementStruct(Ty, getContext());
4475 if (EltType) {
4476 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004477 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004478 getContext().getTypeSize(EltType) == 128) ||
4479 (BT && BT->isFloatingPoint()))
4480 AlignAsType = EltType;
4481 }
4482
Ulrich Weigandb7122372014-07-21 00:48:09 +00004483 // Likewise for ELFv2 homogeneous aggregates.
4484 const Type *Base = nullptr;
4485 uint64_t Members = 0;
4486 if (!AlignAsType && Kind == ELFv2 &&
4487 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4488 AlignAsType = Base;
4489
Ulrich Weigand581badc2014-07-10 17:20:07 +00004490 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004491 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4492 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004493 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004494
John McCall7f416cc2015-09-08 08:05:57 +00004495 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004496 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004497 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004498 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004499
4500 // Otherwise, we only need alignment for any aggregate type that
4501 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004502 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4503 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004504 return CharUnits::fromQuantity(32);
4505 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004506 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004507
John McCall7f416cc2015-09-08 08:05:57 +00004508 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004509}
4510
Ulrich Weigandb7122372014-07-21 00:48:09 +00004511/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4512/// aggregate. Base is set to the base element type, and Members is set
4513/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004514bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4515 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004516 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4517 uint64_t NElements = AT->getSize().getZExtValue();
4518 if (NElements == 0)
4519 return false;
4520 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4521 return false;
4522 Members *= NElements;
4523 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4524 const RecordDecl *RD = RT->getDecl();
4525 if (RD->hasFlexibleArrayMember())
4526 return false;
4527
4528 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004529
4530 // If this is a C++ record, check the bases first.
4531 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4532 for (const auto &I : CXXRD->bases()) {
4533 // Ignore empty records.
4534 if (isEmptyRecord(getContext(), I.getType(), true))
4535 continue;
4536
4537 uint64_t FldMembers;
4538 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4539 return false;
4540
4541 Members += FldMembers;
4542 }
4543 }
4544
Ulrich Weigandb7122372014-07-21 00:48:09 +00004545 for (const auto *FD : RD->fields()) {
4546 // Ignore (non-zero arrays of) empty records.
4547 QualType FT = FD->getType();
4548 while (const ConstantArrayType *AT =
4549 getContext().getAsConstantArrayType(FT)) {
4550 if (AT->getSize().getZExtValue() == 0)
4551 return false;
4552 FT = AT->getElementType();
4553 }
4554 if (isEmptyRecord(getContext(), FT, true))
4555 continue;
4556
4557 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4558 if (getContext().getLangOpts().CPlusPlus &&
4559 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4560 continue;
4561
4562 uint64_t FldMembers;
4563 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4564 return false;
4565
4566 Members = (RD->isUnion() ?
4567 std::max(Members, FldMembers) : Members + FldMembers);
4568 }
4569
4570 if (!Base)
4571 return false;
4572
4573 // Ensure there is no padding.
4574 if (getContext().getTypeSize(Base) * Members !=
4575 getContext().getTypeSize(Ty))
4576 return false;
4577 } else {
4578 Members = 1;
4579 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4580 Members = 2;
4581 Ty = CT->getElementType();
4582 }
4583
Reid Klecknere9f6a712014-10-31 17:10:41 +00004584 // Most ABIs only support float, double, and some vector type widths.
4585 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004586 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004587
4588 // The base type must be the same for all members. Types that
4589 // agree in both total size and mode (float vs. vector) are
4590 // treated as being equivalent here.
4591 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004592 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004593 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004594 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4595 // so make sure to widen it explicitly.
4596 if (const VectorType *VT = Base->getAs<VectorType>()) {
4597 QualType EltTy = VT->getElementType();
4598 unsigned NumElements =
4599 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4600 Base = getContext()
4601 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4602 .getTypePtr();
4603 }
4604 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004605
4606 if (Base->isVectorType() != TyPtr->isVectorType() ||
4607 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4608 return false;
4609 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004610 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4611}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004612
Reid Klecknere9f6a712014-10-31 17:10:41 +00004613bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4614 // Homogeneous aggregates for ELFv2 must have base types of float,
4615 // double, long double, or 128-bit vectors.
4616 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4617 if (BT->getKind() == BuiltinType::Float ||
4618 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004619 BT->getKind() == BuiltinType::LongDouble) {
4620 if (IsSoftFloatABI)
4621 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004622 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004623 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004624 }
4625 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004626 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004627 return true;
4628 }
4629 return false;
4630}
4631
4632bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4633 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004634 // Vector types require one register, floating point types require one
4635 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004636 uint32_t NumRegs =
4637 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004638
4639 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004640 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004641}
4642
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004643ABIArgInfo
4644PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004645 Ty = useFirstFieldIfTransparentUnion(Ty);
4646
Bill Schmidt90b22c92012-11-27 02:46:43 +00004647 if (Ty->isAnyComplexType())
4648 return ABIArgInfo::getDirect();
4649
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004650 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4651 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004652 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004653 uint64_t Size = getContext().getTypeSize(Ty);
4654 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004655 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004656 else if (Size < 128) {
4657 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4658 return ABIArgInfo::getDirect(CoerceTy);
4659 }
4660 }
4661
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004662 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004663 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004664 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004665
John McCall7f416cc2015-09-08 08:05:57 +00004666 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4667 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004668
4669 // ELFv2 homogeneous aggregates are passed as array types.
4670 const Type *Base = nullptr;
4671 uint64_t Members = 0;
4672 if (Kind == ELFv2 &&
4673 isHomogeneousAggregate(Ty, Base, Members)) {
4674 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4675 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4676 return ABIArgInfo::getDirect(CoerceTy);
4677 }
4678
Ulrich Weigand601957f2014-07-21 00:56:36 +00004679 // If an aggregate may end up fully in registers, we do not
4680 // use the ByVal method, but pass the aggregate as array.
4681 // This is usually beneficial since we avoid forcing the
4682 // back-end to store the argument to memory.
4683 uint64_t Bits = getContext().getTypeSize(Ty);
4684 if (Bits > 0 && Bits <= 8 * GPRBits) {
4685 llvm::Type *CoerceTy;
4686
4687 // Types up to 8 bytes are passed as integer type (which will be
4688 // properly aligned in the argument save area doubleword).
4689 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004690 CoerceTy =
4691 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004692 // Larger types are passed as arrays, with the base type selected
4693 // according to the required alignment in the save area.
4694 else {
4695 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004696 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004697 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4698 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4699 }
4700
4701 return ABIArgInfo::getDirect(CoerceTy);
4702 }
4703
Ulrich Weigandb7122372014-07-21 00:48:09 +00004704 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004705 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4706 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004707 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004708 }
4709
Alex Bradburye41a5e22018-01-12 20:08:16 +00004710 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4711 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004712}
4713
4714ABIArgInfo
4715PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4716 if (RetTy->isVoidType())
4717 return ABIArgInfo::getIgnore();
4718
Bill Schmidta3d121c2012-12-17 04:20:17 +00004719 if (RetTy->isAnyComplexType())
4720 return ABIArgInfo::getDirect();
4721
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004722 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4723 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004724 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004725 uint64_t Size = getContext().getTypeSize(RetTy);
4726 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004727 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004728 else if (Size < 128) {
4729 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4730 return ABIArgInfo::getDirect(CoerceTy);
4731 }
4732 }
4733
Ulrich Weigandb7122372014-07-21 00:48:09 +00004734 if (isAggregateTypeForABI(RetTy)) {
4735 // ELFv2 homogeneous aggregates are returned as array types.
4736 const Type *Base = nullptr;
4737 uint64_t Members = 0;
4738 if (Kind == ELFv2 &&
4739 isHomogeneousAggregate(RetTy, Base, Members)) {
4740 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4741 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4742 return ABIArgInfo::getDirect(CoerceTy);
4743 }
4744
4745 // ELFv2 small aggregates are returned in up to two registers.
4746 uint64_t Bits = getContext().getTypeSize(RetTy);
4747 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4748 if (Bits == 0)
4749 return ABIArgInfo::getIgnore();
4750
4751 llvm::Type *CoerceTy;
4752 if (Bits > GPRBits) {
4753 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004754 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004755 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004756 CoerceTy =
4757 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004758 return ABIArgInfo::getDirect(CoerceTy);
4759 }
4760
4761 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004762 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004763 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004764
Alex Bradburye41a5e22018-01-12 20:08:16 +00004765 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4766 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004767}
4768
Bill Schmidt25cb3492012-10-03 19:18:57 +00004769// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004770Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4771 QualType Ty) const {
4772 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4773 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004774
John McCall7f416cc2015-09-08 08:05:57 +00004775 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004776
Bill Schmidt924c4782013-01-14 17:45:36 +00004777 // If we have a complex type and the base type is smaller than 8 bytes,
4778 // the ABI calls for the real and imaginary parts to be right-adjusted
4779 // in separate doublewords. However, Clang expects us to produce a
4780 // pointer to a structure with the two parts packed tightly. So generate
4781 // loads of the real and imaginary parts relative to the va_list pointer,
4782 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004783 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4784 CharUnits EltSize = TypeInfo.first / 2;
4785 if (EltSize < SlotSize) {
4786 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4787 SlotSize * 2, SlotSize,
4788 SlotSize, /*AllowHigher*/ true);
4789
4790 Address RealAddr = Addr;
4791 Address ImagAddr = RealAddr;
4792 if (CGF.CGM.getDataLayout().isBigEndian()) {
4793 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4794 SlotSize - EltSize);
4795 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4796 2 * SlotSize - EltSize);
4797 } else {
4798 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4799 }
4800
4801 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4802 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4803 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4804 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4805 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4806
4807 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4808 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4809 /*init*/ true);
4810 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004811 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004812 }
4813
John McCall7f416cc2015-09-08 08:05:57 +00004814 // Otherwise, just use the general rule.
4815 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4816 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004817}
4818
4819static bool
4820PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4821 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004822 // This is calculated from the LLVM and GCC tables and verified
4823 // against gcc output. AFAIK all ABIs use the same encoding.
4824
4825 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4826
4827 llvm::IntegerType *i8 = CGF.Int8Ty;
4828 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4829 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4830 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4831
4832 // 0-31: r0-31, the 8-byte general-purpose registers
4833 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4834
4835 // 32-63: fp0-31, the 8-byte floating-point registers
4836 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4837
Hal Finkel84832a72016-08-30 02:38:34 +00004838 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004839 // 64: mq
4840 // 65: lr
4841 // 66: ctr
4842 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004843 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4844
4845 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004846 // 68-75 cr0-7
4847 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004848 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004849
4850 // 77-108: v0-31, the 16-byte vector registers
4851 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4852
4853 // 109: vrsave
4854 // 110: vscr
4855 // 111: spe_acc
4856 // 112: spefscr
4857 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004858 // 114: tfhar
4859 // 115: tfiar
4860 // 116: texasr
4861 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004862
4863 return false;
4864}
John McCallea8d8bb2010-03-11 00:10:12 +00004865
Bill Schmidt25cb3492012-10-03 19:18:57 +00004866bool
4867PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4868 CodeGen::CodeGenFunction &CGF,
4869 llvm::Value *Address) const {
4870
4871 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4872}
4873
4874bool
4875PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4876 llvm::Value *Address) const {
4877
4878 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4879}
4880
Chris Lattner0cf24192010-06-28 20:05:43 +00004881//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004882// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004883//===----------------------------------------------------------------------===//
4884
4885namespace {
4886
John McCall12f23522016-04-04 18:33:08 +00004887class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004888public:
4889 enum ABIKind {
4890 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004891 DarwinPCS,
4892 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004893 };
4894
4895private:
4896 ABIKind Kind;
4897
4898public:
John McCall12f23522016-04-04 18:33:08 +00004899 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4900 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004901
4902private:
4903 ABIKind getABIKind() const { return Kind; }
4904 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4905
4906 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004907 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004908 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4909 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4910 uint64_t Members) const override;
4911
Tim Northovera2ee4332014-03-29 15:09:45 +00004912 bool isIllegalVectorType(QualType Ty) const;
4913
David Blaikie1cbb9712014-11-14 19:09:44 +00004914 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004915 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004916 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004917
Tim Northoverb047bfa2014-11-27 21:02:49 +00004918 for (auto &it : FI.arguments())
4919 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004920 }
4921
John McCall7f416cc2015-09-08 08:05:57 +00004922 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4923 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004924
John McCall7f416cc2015-09-08 08:05:57 +00004925 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4926 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004927
John McCall7f416cc2015-09-08 08:05:57 +00004928 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4929 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004930 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4931 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4932 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004933 }
John McCall12f23522016-04-04 18:33:08 +00004934
Martin Storsjo502de222017-07-13 17:59:14 +00004935 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4936 QualType Ty) const override;
4937
John McCall56331e22018-01-07 06:28:49 +00004938 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004939 bool asReturnValue) const override {
4940 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4941 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004942 bool isSwiftErrorInRegister() const override {
4943 return true;
4944 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004945
4946 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4947 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004948};
4949
Tim Northover573cbee2014-05-24 12:52:07 +00004950class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004951public:
Tim Northover573cbee2014-05-24 12:52:07 +00004952 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4953 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004954
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004955 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004956 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004957 }
4958
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004959 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4960 return 31;
4961 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004962
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004963 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004964};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004965
4966class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4967public:
4968 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4969 : AArch64TargetCodeGenInfo(CGT, K) {}
4970
4971 void getDependentLibraryOption(llvm::StringRef Lib,
4972 llvm::SmallString<24> &Opt) const override {
4973 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4974 }
4975
4976 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4977 llvm::SmallString<32> &Opt) const override {
4978 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4979 }
4980};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004981}
Tim Northovera2ee4332014-03-29 15:09:45 +00004982
Tim Northoverb047bfa2014-11-27 21:02:49 +00004983ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004984 Ty = useFirstFieldIfTransparentUnion(Ty);
4985
Tim Northovera2ee4332014-03-29 15:09:45 +00004986 // Handle illegal vector types here.
4987 if (isIllegalVectorType(Ty)) {
4988 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004989 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004990 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004991 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4992 return ABIArgInfo::getDirect(ResType);
4993 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004994 if (Size <= 32) {
4995 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004996 return ABIArgInfo::getDirect(ResType);
4997 }
4998 if (Size == 64) {
4999 llvm::Type *ResType =
5000 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005001 return ABIArgInfo::getDirect(ResType);
5002 }
5003 if (Size == 128) {
5004 llvm::Type *ResType =
5005 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005006 return ABIArgInfo::getDirect(ResType);
5007 }
John McCall7f416cc2015-09-08 08:05:57 +00005008 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005009 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005010
5011 if (!isAggregateTypeForABI(Ty)) {
5012 // Treat an enum type as its underlying type.
5013 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5014 Ty = EnumTy->getDecl()->getIntegerType();
5015
Tim Northovera2ee4332014-03-29 15:09:45 +00005016 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005017 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005018 : ABIArgInfo::getDirect());
5019 }
5020
5021 // Structures with either a non-trivial destructor or a non-trivial
5022 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005023 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005024 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5025 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005026 }
5027
5028 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5029 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005030 uint64_t Size = getContext().getTypeSize(Ty);
5031 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5032 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005033 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5034 return ABIArgInfo::getIgnore();
5035
Tim Northover23bcad22017-05-05 22:36:06 +00005036 // GNU C mode. The only argument that gets ignored is an empty one with size
5037 // 0.
5038 if (IsEmpty && Size == 0)
5039 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005040 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5041 }
5042
5043 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005044 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005045 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005046 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005047 return ABIArgInfo::getDirect(
5048 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005049 }
5050
5051 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005052 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005053 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5054 // same size and alignment.
5055 if (getTarget().isRenderScriptTarget()) {
5056 return coerceToIntArray(Ty, getContext(), getVMContext());
5057 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005058 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005059 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005060
Tim Northovera2ee4332014-03-29 15:09:45 +00005061 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5062 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005063 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005064 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5065 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5066 }
5067 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5068 }
5069
John McCall7f416cc2015-09-08 08:05:57 +00005070 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005071}
5072
Tim Northover573cbee2014-05-24 12:52:07 +00005073ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005074 if (RetTy->isVoidType())
5075 return ABIArgInfo::getIgnore();
5076
5077 // Large vector types should be returned via memory.
5078 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005079 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005080
5081 if (!isAggregateTypeForABI(RetTy)) {
5082 // Treat an enum type as its underlying type.
5083 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5084 RetTy = EnumTy->getDecl()->getIntegerType();
5085
Tim Northover4dab6982014-04-18 13:46:08 +00005086 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005087 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005088 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005089 }
5090
Tim Northover23bcad22017-05-05 22:36:06 +00005091 uint64_t Size = getContext().getTypeSize(RetTy);
5092 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005093 return ABIArgInfo::getIgnore();
5094
Craig Topper8a13c412014-05-21 05:09:00 +00005095 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005096 uint64_t Members = 0;
5097 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005098 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5099 return ABIArgInfo::getDirect();
5100
5101 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005102 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005103 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5104 // same size and alignment.
5105 if (getTarget().isRenderScriptTarget()) {
5106 return coerceToIntArray(RetTy, getContext(), getVMContext());
5107 }
Pete Cooper635b5092015-04-17 22:16:24 +00005108 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005109 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005110
5111 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5112 // For aggregates with 16-byte alignment, we use i128.
5113 if (Alignment < 128 && Size == 128) {
5114 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5115 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5116 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5118 }
5119
John McCall7f416cc2015-09-08 08:05:57 +00005120 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005121}
5122
Tim Northover573cbee2014-05-24 12:52:07 +00005123/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5124bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005125 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5126 // Check whether VT is legal.
5127 unsigned NumElements = VT->getNumElements();
5128 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005129 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005130 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005131 return true;
5132 return Size != 64 && (Size != 128 || NumElements == 1);
5133 }
5134 return false;
5135}
5136
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005137bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5138 llvm::Type *eltTy,
5139 unsigned elts) const {
5140 if (!llvm::isPowerOf2_32(elts))
5141 return false;
5142 if (totalSize.getQuantity() != 8 &&
5143 (totalSize.getQuantity() != 16 || elts == 1))
5144 return false;
5145 return true;
5146}
5147
Reid Klecknere9f6a712014-10-31 17:10:41 +00005148bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5149 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5150 // point type or a short-vector type. This is the same as the 32-bit ABI,
5151 // but with the difference that any floating-point type is allowed,
5152 // including __fp16.
5153 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5154 if (BT->isFloatingPoint())
5155 return true;
5156 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5157 unsigned VecSize = getContext().getTypeSize(VT);
5158 if (VecSize == 64 || VecSize == 128)
5159 return true;
5160 }
5161 return false;
5162}
5163
5164bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5165 uint64_t Members) const {
5166 return Members <= 4;
5167}
5168
John McCall7f416cc2015-09-08 08:05:57 +00005169Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005170 QualType Ty,
5171 CodeGenFunction &CGF) const {
5172 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005173 bool IsIndirect = AI.isIndirect();
5174
Tim Northoverb047bfa2014-11-27 21:02:49 +00005175 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5176 if (IsIndirect)
5177 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5178 else if (AI.getCoerceToType())
5179 BaseTy = AI.getCoerceToType();
5180
5181 unsigned NumRegs = 1;
5182 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5183 BaseTy = ArrTy->getElementType();
5184 NumRegs = ArrTy->getNumElements();
5185 }
5186 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5187
Tim Northovera2ee4332014-03-29 15:09:45 +00005188 // The AArch64 va_list type and handling is specified in the Procedure Call
5189 // Standard, section B.4:
5190 //
5191 // struct {
5192 // void *__stack;
5193 // void *__gr_top;
5194 // void *__vr_top;
5195 // int __gr_offs;
5196 // int __vr_offs;
5197 // };
5198
5199 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5200 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5201 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5202 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005203
John McCall7f416cc2015-09-08 08:05:57 +00005204 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5205 CharUnits TyAlign = TyInfo.second;
5206
5207 Address reg_offs_p = Address::invalid();
5208 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005209 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005210 CharUnits reg_top_offset;
5211 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005212 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005213 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005214 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005215 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5216 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005217 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5218 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005219 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005220 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005221 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005222 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005223 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005224 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5225 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005226 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5227 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005228 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005229 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005230 }
5231
5232 //=======================================
5233 // Find out where argument was passed
5234 //=======================================
5235
5236 // If reg_offs >= 0 we're already using the stack for this type of
5237 // argument. We don't want to keep updating reg_offs (in case it overflows,
5238 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5239 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005240 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005241 UsingStack = CGF.Builder.CreateICmpSGE(
5242 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5243
5244 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5245
5246 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005247 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005248 CGF.EmitBlock(MaybeRegBlock);
5249
5250 // Integer arguments may need to correct register alignment (for example a
5251 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5252 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005253 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5254 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005255
5256 reg_offs = CGF.Builder.CreateAdd(
5257 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5258 "align_regoffs");
5259 reg_offs = CGF.Builder.CreateAnd(
5260 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5261 "aligned_regoffs");
5262 }
5263
5264 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005265 // The fact that this is done unconditionally reflects the fact that
5266 // allocating an argument to the stack also uses up all the remaining
5267 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005268 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005269 NewOffset = CGF.Builder.CreateAdd(
5270 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5271 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5272
5273 // Now we're in a position to decide whether this argument really was in
5274 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005275 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005276 InRegs = CGF.Builder.CreateICmpSLE(
5277 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5278
5279 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5280
5281 //=======================================
5282 // Argument was in registers
5283 //=======================================
5284
5285 // Now we emit the code for if the argument was originally passed in
5286 // registers. First start the appropriate block:
5287 CGF.EmitBlock(InRegBlock);
5288
John McCall7f416cc2015-09-08 08:05:57 +00005289 llvm::Value *reg_top = nullptr;
5290 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5291 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005292 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005293 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5294 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5295 Address RegAddr = Address::invalid();
5296 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005297
5298 if (IsIndirect) {
5299 // If it's been passed indirectly (actually a struct), whatever we find from
5300 // stored registers or on the stack will actually be a struct **.
5301 MemTy = llvm::PointerType::getUnqual(MemTy);
5302 }
5303
Craig Topper8a13c412014-05-21 05:09:00 +00005304 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005305 uint64_t NumMembers = 0;
5306 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005307 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005308 // Homogeneous aggregates passed in registers will have their elements split
5309 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5310 // qN+1, ...). We reload and store into a temporary local variable
5311 // contiguously.
5312 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005313 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005314 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5315 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005316 Address Tmp = CGF.CreateTempAlloca(HFATy,
5317 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005318
John McCall7f416cc2015-09-08 08:05:57 +00005319 // On big-endian platforms, the value will be right-aligned in its slot.
5320 int Offset = 0;
5321 if (CGF.CGM.getDataLayout().isBigEndian() &&
5322 BaseTyInfo.first.getQuantity() < 16)
5323 Offset = 16 - BaseTyInfo.first.getQuantity();
5324
Tim Northovera2ee4332014-03-29 15:09:45 +00005325 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005326 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5327 Address LoadAddr =
5328 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5329 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5330
5331 Address StoreAddr =
5332 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005333
5334 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5335 CGF.Builder.CreateStore(Elem, StoreAddr);
5336 }
5337
John McCall7f416cc2015-09-08 08:05:57 +00005338 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005339 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005340 // Otherwise the object is contiguous in memory.
5341
5342 // It might be right-aligned in its slot.
5343 CharUnits SlotSize = BaseAddr.getAlignment();
5344 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005345 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005346 TyInfo.first < SlotSize) {
5347 CharUnits Offset = SlotSize - TyInfo.first;
5348 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005349 }
5350
John McCall7f416cc2015-09-08 08:05:57 +00005351 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005352 }
5353
5354 CGF.EmitBranch(ContBlock);
5355
5356 //=======================================
5357 // Argument was on the stack
5358 //=======================================
5359 CGF.EmitBlock(OnStackBlock);
5360
John McCall7f416cc2015-09-08 08:05:57 +00005361 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5362 CharUnits::Zero(), "stack_p");
5363 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005364
John McCall7f416cc2015-09-08 08:05:57 +00005365 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005366 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005367 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5368 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005369
John McCall7f416cc2015-09-08 08:05:57 +00005370 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005371
John McCall7f416cc2015-09-08 08:05:57 +00005372 OnStackPtr = CGF.Builder.CreateAdd(
5373 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005374 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005375 OnStackPtr = CGF.Builder.CreateAnd(
5376 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005377 "align_stack");
5378
John McCall7f416cc2015-09-08 08:05:57 +00005379 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005380 }
John McCall7f416cc2015-09-08 08:05:57 +00005381 Address OnStackAddr(OnStackPtr,
5382 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005383
John McCall7f416cc2015-09-08 08:05:57 +00005384 // All stack slots are multiples of 8 bytes.
5385 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5386 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005387 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005388 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005389 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005390 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005391
John McCall7f416cc2015-09-08 08:05:57 +00005392 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005393 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005394 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005395
5396 // Write the new value of __stack for the next call to va_arg
5397 CGF.Builder.CreateStore(NewStack, stack_p);
5398
5399 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005400 TyInfo.first < StackSlotSize) {
5401 CharUnits Offset = StackSlotSize - TyInfo.first;
5402 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005403 }
5404
John McCall7f416cc2015-09-08 08:05:57 +00005405 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005406
5407 CGF.EmitBranch(ContBlock);
5408
5409 //=======================================
5410 // Tidy up
5411 //=======================================
5412 CGF.EmitBlock(ContBlock);
5413
John McCall7f416cc2015-09-08 08:05:57 +00005414 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5415 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005416
5417 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005418 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5419 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005420
5421 return ResAddr;
5422}
5423
John McCall7f416cc2015-09-08 08:05:57 +00005424Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5425 CodeGenFunction &CGF) const {
5426 // The backend's lowering doesn't support va_arg for aggregates or
5427 // illegal vector types. Lower VAArg here for these cases and use
5428 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005429 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005430 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005431
John McCall7f416cc2015-09-08 08:05:57 +00005432 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005433
John McCall7f416cc2015-09-08 08:05:57 +00005434 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005435 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005436 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5437 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5438 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005439 }
5440
John McCall7f416cc2015-09-08 08:05:57 +00005441 // The size of the actual thing passed, which might end up just
5442 // being a pointer for indirect types.
5443 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5444
5445 // Arguments bigger than 16 bytes which aren't homogeneous
5446 // aggregates should be passed indirectly.
5447 bool IsIndirect = false;
5448 if (TyInfo.first.getQuantity() > 16) {
5449 const Type *Base = nullptr;
5450 uint64_t Members = 0;
5451 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005452 }
5453
John McCall7f416cc2015-09-08 08:05:57 +00005454 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5455 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005456}
5457
Martin Storsjo502de222017-07-13 17:59:14 +00005458Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5459 QualType Ty) const {
5460 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5461 CGF.getContext().getTypeInfoInChars(Ty),
5462 CharUnits::fromQuantity(8),
5463 /*allowHigherAlign*/ false);
5464}
5465
Tim Northovera2ee4332014-03-29 15:09:45 +00005466//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005467// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005468//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005469
5470namespace {
5471
John McCall12f23522016-04-04 18:33:08 +00005472class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005473public:
5474 enum ABIKind {
5475 APCS = 0,
5476 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005477 AAPCS_VFP = 2,
5478 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005479 };
5480
5481private:
5482 ABIKind Kind;
5483
5484public:
John McCall12f23522016-04-04 18:33:08 +00005485 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5486 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005487 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005488 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005489
John McCall3480ef22011-08-30 01:42:09 +00005490 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005491 switch (getTarget().getTriple().getEnvironment()) {
5492 case llvm::Triple::Android:
5493 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005494 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005495 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005496 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005497 case llvm::Triple::MuslEABI:
5498 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005499 return true;
5500 default:
5501 return false;
5502 }
John McCall3480ef22011-08-30 01:42:09 +00005503 }
5504
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005505 bool isEABIHF() const {
5506 switch (getTarget().getTriple().getEnvironment()) {
5507 case llvm::Triple::EABIHF:
5508 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005509 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005510 return true;
5511 default:
5512 return false;
5513 }
5514 }
5515
Daniel Dunbar020daa92009-09-12 01:00:39 +00005516 ABIKind getABIKind() const { return Kind; }
5517
Tim Northovera484bc02013-10-01 14:34:25 +00005518private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005519 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005520 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005521 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005522
Reid Klecknere9f6a712014-10-31 17:10:41 +00005523 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5524 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5525 uint64_t Members) const override;
5526
Craig Topper4f12f102014-03-12 06:41:41 +00005527 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005528
John McCall7f416cc2015-09-08 08:05:57 +00005529 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5530 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005531
5532 llvm::CallingConv::ID getLLVMDefaultCC() const;
5533 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005534 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005535
John McCall56331e22018-01-07 06:28:49 +00005536 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005537 bool asReturnValue) const override {
5538 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5539 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005540 bool isSwiftErrorInRegister() const override {
5541 return true;
5542 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005543 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5544 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005545};
5546
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005547class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5548public:
Chris Lattner2b037972010-07-29 02:01:43 +00005549 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5550 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005551
John McCall3480ef22011-08-30 01:42:09 +00005552 const ARMABIInfo &getABIInfo() const {
5553 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5554 }
5555
Craig Topper4f12f102014-03-12 06:41:41 +00005556 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005557 return 13;
5558 }
Roman Divackyc1617352011-05-18 19:36:54 +00005559
Craig Topper4f12f102014-03-12 06:41:41 +00005560 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005561 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005562 }
5563
Roman Divackyc1617352011-05-18 19:36:54 +00005564 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005565 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005566 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005567
5568 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005569 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005570 return false;
5571 }
John McCall3480ef22011-08-30 01:42:09 +00005572
Craig Topper4f12f102014-03-12 06:41:41 +00005573 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005574 if (getABIInfo().isEABI()) return 88;
5575 return TargetCodeGenInfo::getSizeOfUnwindException();
5576 }
Tim Northovera484bc02013-10-01 14:34:25 +00005577
Eric Christopher162c91c2015-06-05 22:03:00 +00005578 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005579 CodeGen::CodeGenModule &CGM) const override {
5580 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005581 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005582 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005583 if (!FD)
5584 return;
5585
5586 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5587 if (!Attr)
5588 return;
5589
5590 const char *Kind;
5591 switch (Attr->getInterrupt()) {
5592 case ARMInterruptAttr::Generic: Kind = ""; break;
5593 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5594 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5595 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5596 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5597 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5598 }
5599
5600 llvm::Function *Fn = cast<llvm::Function>(GV);
5601
5602 Fn->addFnAttr("interrupt", Kind);
5603
Tim Northover5627d392015-10-30 16:30:45 +00005604 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5605 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005606 return;
5607
5608 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5609 // however this is not necessarily true on taking any interrupt. Instruct
5610 // the backend to perform a realignment as part of the function prologue.
5611 llvm::AttrBuilder B;
5612 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005613 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005614 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005615};
5616
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005617class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005618public:
5619 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5620 : ARMTargetCodeGenInfo(CGT, K) {}
5621
Eric Christopher162c91c2015-06-05 22:03:00 +00005622 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005623 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005624
5625 void getDependentLibraryOption(llvm::StringRef Lib,
5626 llvm::SmallString<24> &Opt) const override {
5627 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5628 }
5629
5630 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5631 llvm::SmallString<32> &Opt) const override {
5632 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5633 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005634};
5635
Eric Christopher162c91c2015-06-05 22:03:00 +00005636void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005637 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5638 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5639 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005640 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005641 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005642}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005643}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005644
Chris Lattner22326a12010-07-29 02:31:05 +00005645void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005646 if (!::classifyReturnType(getCXXABI(), FI, *this))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005647 FI.getReturnInfo() =
5648 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005649
Tim Northoverbc784d12015-02-24 17:22:40 +00005650 for (auto &I : FI.arguments())
5651 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005652
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005653 // Always honor user-specified calling convention.
5654 if (FI.getCallingConvention() != llvm::CallingConv::C)
5655 return;
5656
John McCall882987f2013-02-28 19:01:20 +00005657 llvm::CallingConv::ID cc = getRuntimeCC();
5658 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005659 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005660}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005661
John McCall882987f2013-02-28 19:01:20 +00005662/// Return the default calling convention that LLVM will use.
5663llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5664 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005665 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005666 return llvm::CallingConv::ARM_AAPCS_VFP;
5667 else if (isEABI())
5668 return llvm::CallingConv::ARM_AAPCS;
5669 else
5670 return llvm::CallingConv::ARM_APCS;
5671}
5672
5673/// Return the calling convention that our ABI would like us to use
5674/// as the C calling convention.
5675llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005676 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005677 case APCS: return llvm::CallingConv::ARM_APCS;
5678 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5679 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005680 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005681 }
John McCall882987f2013-02-28 19:01:20 +00005682 llvm_unreachable("bad ABI kind");
5683}
5684
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005685void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005686 assert(getRuntimeCC() == llvm::CallingConv::C);
5687
5688 // Don't muddy up the IR with a ton of explicit annotations if
5689 // they'd just match what LLVM will infer from the triple.
5690 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5691 if (abiCC != getLLVMDefaultCC())
5692 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005693}
5694
Tim Northoverbc784d12015-02-24 17:22:40 +00005695ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5696 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005697 // 6.1.2.1 The following argument types are VFP CPRCs:
5698 // A single-precision floating-point type (including promoted
5699 // half-precision types); A double-precision floating-point type;
5700 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5701 // with a Base Type of a single- or double-precision floating-point type,
5702 // 64-bit containerized vectors or 128-bit containerized vectors with one
5703 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005704 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005705
Reid Klecknerb1be6832014-11-15 01:41:41 +00005706 Ty = useFirstFieldIfTransparentUnion(Ty);
5707
Manman Renfef9e312012-10-16 19:18:39 +00005708 // Handle illegal vector types here.
5709 if (isIllegalVectorType(Ty)) {
5710 uint64_t Size = getContext().getTypeSize(Ty);
5711 if (Size <= 32) {
5712 llvm::Type *ResType =
5713 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005714 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005715 }
5716 if (Size == 64) {
5717 llvm::Type *ResType = llvm::VectorType::get(
5718 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005719 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005720 }
5721 if (Size == 128) {
5722 llvm::Type *ResType = llvm::VectorType::get(
5723 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005724 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005725 }
John McCall7f416cc2015-09-08 08:05:57 +00005726 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005727 }
5728
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005729 // _Float16 and __fp16 get passed as if it were an int or float, but with
5730 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5731 // half type natively, and does not need to interwork with AAPCS code.
5732 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5733 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005734 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5735 llvm::Type::getFloatTy(getVMContext()) :
5736 llvm::Type::getInt32Ty(getVMContext());
5737 return ABIArgInfo::getDirect(ResType);
5738 }
5739
John McCalla1dee5302010-08-22 10:59:02 +00005740 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005741 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005742 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005743 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005744 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005745
Alex Bradburye41a5e22018-01-12 20:08:16 +00005746 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005747 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005748 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005749
Oliver Stannard405bded2014-02-11 09:25:50 +00005750 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005751 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005752 }
Tim Northover1060eae2013-06-21 22:49:34 +00005753
Daniel Dunbar09d33622009-09-14 21:54:03 +00005754 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005755 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005756 return ABIArgInfo::getIgnore();
5757
Tim Northover5a1558e2014-11-07 22:30:50 +00005758 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005759 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5760 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005761 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005762 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005763 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005764 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005765 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005766 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005767 }
Tim Northover5627d392015-10-30 16:30:45 +00005768 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5769 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5770 // this convention even for a variadic function: the backend will use GPRs
5771 // if needed.
5772 const Type *Base = nullptr;
5773 uint64_t Members = 0;
5774 if (isHomogeneousAggregate(Ty, Base, Members)) {
5775 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5776 llvm::Type *Ty =
5777 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5778 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5779 }
5780 }
5781
5782 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5783 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5784 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5785 // bigger than 128-bits, they get placed in space allocated by the caller,
5786 // and a pointer is passed.
5787 return ABIArgInfo::getIndirect(
5788 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005789 }
5790
Manman Ren6c30e132012-08-13 21:23:55 +00005791 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005792 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5793 // most 8-byte. We realign the indirect argument if type alignment is bigger
5794 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005795 uint64_t ABIAlign = 4;
5796 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5797 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005798 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005799 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005800
Manman Ren8cd99812012-11-06 04:58:01 +00005801 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005802 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005803 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5804 /*ByVal=*/true,
5805 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005806 }
5807
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005808 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5809 // same size and alignment.
5810 if (getTarget().isRenderScriptTarget()) {
5811 return coerceToIntArray(Ty, getContext(), getVMContext());
5812 }
5813
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005814 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005815 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005816 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005817 // FIXME: Try to match the types of the arguments more accurately where
5818 // we can.
5819 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005820 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5821 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005822 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005823 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5824 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005825 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005826
Tim Northover5a1558e2014-11-07 22:30:50 +00005827 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005828}
5829
Chris Lattner458b2aa2010-07-29 02:16:43 +00005830static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005831 llvm::LLVMContext &VMContext) {
5832 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5833 // is called integer-like if its size is less than or equal to one word, and
5834 // the offset of each of its addressable sub-fields is zero.
5835
5836 uint64_t Size = Context.getTypeSize(Ty);
5837
5838 // Check that the type fits in a word.
5839 if (Size > 32)
5840 return false;
5841
5842 // FIXME: Handle vector types!
5843 if (Ty->isVectorType())
5844 return false;
5845
Daniel Dunbard53bac72009-09-14 02:20:34 +00005846 // Float types are never treated as "integer like".
5847 if (Ty->isRealFloatingType())
5848 return false;
5849
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005850 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005851 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005852 return true;
5853
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005854 // Small complex integer types are "integer like".
5855 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5856 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005857
5858 // Single element and zero sized arrays should be allowed, by the definition
5859 // above, but they are not.
5860
5861 // Otherwise, it must be a record type.
5862 const RecordType *RT = Ty->getAs<RecordType>();
5863 if (!RT) return false;
5864
5865 // Ignore records with flexible arrays.
5866 const RecordDecl *RD = RT->getDecl();
5867 if (RD->hasFlexibleArrayMember())
5868 return false;
5869
5870 // Check that all sub-fields are at offset 0, and are themselves "integer
5871 // like".
5872 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5873
5874 bool HadField = false;
5875 unsigned idx = 0;
5876 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5877 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005878 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005879
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005880 // Bit-fields are not addressable, we only need to verify they are "integer
5881 // like". We still have to disallow a subsequent non-bitfield, for example:
5882 // struct { int : 0; int x }
5883 // is non-integer like according to gcc.
5884 if (FD->isBitField()) {
5885 if (!RD->isUnion())
5886 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005887
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005888 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5889 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005890
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005891 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005892 }
5893
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005894 // Check if this field is at offset 0.
5895 if (Layout.getFieldOffset(idx) != 0)
5896 return false;
5897
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005898 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5899 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005900
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005901 // Only allow at most one field in a structure. This doesn't match the
5902 // wording above, but follows gcc in situations with a field following an
5903 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005904 if (!RD->isUnion()) {
5905 if (HadField)
5906 return false;
5907
5908 HadField = true;
5909 }
5910 }
5911
5912 return true;
5913}
5914
Oliver Stannard405bded2014-02-11 09:25:50 +00005915ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5916 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005917 bool IsEffectivelyAAPCS_VFP =
5918 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005919
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005920 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005921 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005922
Daniel Dunbar19964db2010-09-23 01:54:32 +00005923 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005924 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005925 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005926 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005927
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005928 // _Float16 and __fp16 get returned as if it were an int or float, but with
5929 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5930 // half type natively, and does not need to interwork with AAPCS code.
5931 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
5932 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005933 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5934 llvm::Type::getFloatTy(getVMContext()) :
5935 llvm::Type::getInt32Ty(getVMContext());
5936 return ABIArgInfo::getDirect(ResType);
5937 }
5938
John McCalla1dee5302010-08-22 10:59:02 +00005939 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005940 // Treat an enum type as its underlying type.
5941 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5942 RetTy = EnumTy->getDecl()->getIntegerType();
5943
Alex Bradburye41a5e22018-01-12 20:08:16 +00005944 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00005945 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005946 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005947
5948 // Are we following APCS?
5949 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005950 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005951 return ABIArgInfo::getIgnore();
5952
Daniel Dunbareedf1512010-02-01 23:31:19 +00005953 // Complex types are all returned as packed integers.
5954 //
5955 // FIXME: Consider using 2 x vector types if the back end handles them
5956 // correctly.
5957 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005958 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5959 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005960
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005961 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005962 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005963 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005964 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005965 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005966 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005967 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005968 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5969 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005970 }
5971
5972 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005973 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005974 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005975
5976 // Otherwise this is an AAPCS variant.
5977
Chris Lattner458b2aa2010-07-29 02:16:43 +00005978 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005979 return ABIArgInfo::getIgnore();
5980
Bob Wilson1d9269a2011-11-02 04:51:36 +00005981 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005982 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005983 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005984 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005985 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005986 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005987 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005988 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005989 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005990 }
5991
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005992 // Aggregates <= 4 bytes are returned in r0; other aggregates
5993 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005994 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005995 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005996 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5997 // same size and alignment.
5998 if (getTarget().isRenderScriptTarget()) {
5999 return coerceToIntArray(RetTy, getContext(), getVMContext());
6000 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006001 if (getDataLayout().isBigEndian())
6002 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006003 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006004
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006005 // Return in the smallest viable integer type.
6006 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006007 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006008 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006009 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6010 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006011 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6012 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6013 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006014 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006015 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006016 }
6017
John McCall7f416cc2015-09-08 08:05:57 +00006018 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006019}
6020
Manman Renfef9e312012-10-16 19:18:39 +00006021/// isIllegalVector - check whether Ty is an illegal vector type.
6022bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006023 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6024 if (isAndroid()) {
6025 // Android shipped using Clang 3.1, which supported a slightly different
6026 // vector ABI. The primary differences were that 3-element vector types
6027 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6028 // accepts that legacy behavior for Android only.
6029 // Check whether VT is legal.
6030 unsigned NumElements = VT->getNumElements();
6031 // NumElements should be power of 2 or equal to 3.
6032 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6033 return true;
6034 } else {
6035 // Check whether VT is legal.
6036 unsigned NumElements = VT->getNumElements();
6037 uint64_t Size = getContext().getTypeSize(VT);
6038 // NumElements should be power of 2.
6039 if (!llvm::isPowerOf2_32(NumElements))
6040 return true;
6041 // Size should be greater than 32 bits.
6042 return Size <= 32;
6043 }
Manman Renfef9e312012-10-16 19:18:39 +00006044 }
6045 return false;
6046}
6047
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006048bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6049 llvm::Type *eltTy,
6050 unsigned numElts) const {
6051 if (!llvm::isPowerOf2_32(numElts))
6052 return false;
6053 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6054 if (size > 64)
6055 return false;
6056 if (vectorSize.getQuantity() != 8 &&
6057 (vectorSize.getQuantity() != 16 || numElts == 1))
6058 return false;
6059 return true;
6060}
6061
Reid Klecknere9f6a712014-10-31 17:10:41 +00006062bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6063 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6064 // double, or 64-bit or 128-bit vectors.
6065 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6066 if (BT->getKind() == BuiltinType::Float ||
6067 BT->getKind() == BuiltinType::Double ||
6068 BT->getKind() == BuiltinType::LongDouble)
6069 return true;
6070 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6071 unsigned VecSize = getContext().getTypeSize(VT);
6072 if (VecSize == 64 || VecSize == 128)
6073 return true;
6074 }
6075 return false;
6076}
6077
6078bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6079 uint64_t Members) const {
6080 return Members <= 4;
6081}
6082
John McCall7f416cc2015-09-08 08:05:57 +00006083Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6084 QualType Ty) const {
6085 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006086
John McCall7f416cc2015-09-08 08:05:57 +00006087 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006088 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006089 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6090 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6091 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006092 }
6093
John McCall7f416cc2015-09-08 08:05:57 +00006094 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6095 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006096
John McCall7f416cc2015-09-08 08:05:57 +00006097 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6098 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006099 const Type *Base = nullptr;
6100 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006101 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6102 IsIndirect = true;
6103
Tim Northover5627d392015-10-30 16:30:45 +00006104 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6105 // allocated by the caller.
6106 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6107 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6108 !isHomogeneousAggregate(Ty, Base, Members)) {
6109 IsIndirect = true;
6110
John McCall7f416cc2015-09-08 08:05:57 +00006111 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006112 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6113 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006114 // Our callers should be prepared to handle an under-aligned address.
6115 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6116 getABIKind() == ARMABIInfo::AAPCS) {
6117 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6118 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006119 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6120 // ARMv7k allows type alignment up to 16 bytes.
6121 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6122 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006123 } else {
6124 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006125 }
John McCall7f416cc2015-09-08 08:05:57 +00006126 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006127
John McCall7f416cc2015-09-08 08:05:57 +00006128 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6129 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006130}
6131
Chris Lattner0cf24192010-06-28 20:05:43 +00006132//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006133// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006134//===----------------------------------------------------------------------===//
6135
6136namespace {
6137
Justin Holewinski83e96682012-05-24 17:43:12 +00006138class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006139public:
Justin Holewinski36837432013-03-30 14:38:24 +00006140 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006141
6142 ABIArgInfo classifyReturnType(QualType RetTy) const;
6143 ABIArgInfo classifyArgumentType(QualType Ty) const;
6144
Craig Topper4f12f102014-03-12 06:41:41 +00006145 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006146 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6147 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006148};
6149
Justin Holewinski83e96682012-05-24 17:43:12 +00006150class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006151public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006152 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6153 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006154
Eric Christopher162c91c2015-06-05 22:03:00 +00006155 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006156 CodeGen::CodeGenModule &M) const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006157
Justin Holewinski36837432013-03-30 14:38:24 +00006158private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006159 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6160 // resulting MDNode to the nvvm.annotations MDNode.
6161 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006162};
6163
Justin Holewinski83e96682012-05-24 17:43:12 +00006164ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006165 if (RetTy->isVoidType())
6166 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006167
6168 // note: this is different from default ABI
6169 if (!RetTy->isScalarType())
6170 return ABIArgInfo::getDirect();
6171
6172 // Treat an enum type as its underlying type.
6173 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6174 RetTy = EnumTy->getDecl()->getIntegerType();
6175
Alex Bradburye41a5e22018-01-12 20:08:16 +00006176 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6177 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006178}
6179
Justin Holewinski83e96682012-05-24 17:43:12 +00006180ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006181 // Treat an enum type as its underlying type.
6182 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6183 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006184
Eli Bendersky95338a02014-10-29 13:43:21 +00006185 // Return aggregates type as indirect by value
6186 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006187 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006188
Alex Bradburye41a5e22018-01-12 20:08:16 +00006189 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6190 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006191}
6192
Justin Holewinski83e96682012-05-24 17:43:12 +00006193void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006194 if (!getCXXABI().classifyReturnType(FI))
6195 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006196 for (auto &I : FI.arguments())
6197 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006198
6199 // Always honor user-specified calling convention.
6200 if (FI.getCallingConvention() != llvm::CallingConv::C)
6201 return;
6202
John McCall882987f2013-02-28 19:01:20 +00006203 FI.setEffectiveCallingConvention(getRuntimeCC());
6204}
6205
John McCall7f416cc2015-09-08 08:05:57 +00006206Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6207 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006208 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006209}
6210
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006211void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006212 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6213 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006214 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006215 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006216 if (!FD) return;
6217
6218 llvm::Function *F = cast<llvm::Function>(GV);
6219
6220 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006221 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006222 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006223 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006224 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006225 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006226 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6227 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006228 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006229 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006230 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006231 }
Justin Holewinski38031972011-10-05 17:58:44 +00006232
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006233 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006234 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006235 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006236 // __global__ functions cannot be called from the device, we do not
6237 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006238 if (FD->hasAttr<CUDAGlobalAttr>()) {
6239 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6240 addNVVMMetadata(F, "kernel", 1);
6241 }
Artem Belevich7093e402015-04-21 22:55:54 +00006242 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006243 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006244 llvm::APSInt MaxThreads(32);
6245 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6246 if (MaxThreads > 0)
6247 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6248
6249 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6250 // not specified in __launch_bounds__ or if the user specified a 0 value,
6251 // we don't have to add a PTX directive.
6252 if (Attr->getMinBlocks()) {
6253 llvm::APSInt MinBlocks(32);
6254 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6255 if (MinBlocks > 0)
6256 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6257 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006258 }
6259 }
Justin Holewinski38031972011-10-05 17:58:44 +00006260 }
6261}
6262
Eli Benderskye06a2c42014-04-15 16:57:05 +00006263void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6264 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006265 llvm::Module *M = F->getParent();
6266 llvm::LLVMContext &Ctx = M->getContext();
6267
6268 // Get "nvvm.annotations" metadata node
6269 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6270
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006271 llvm::Metadata *MDVals[] = {
6272 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6273 llvm::ConstantAsMetadata::get(
6274 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006275 // Append metadata to nvvm.annotations
6276 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6277}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006278}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006279
6280//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006281// SystemZ ABI Implementation
6282//===----------------------------------------------------------------------===//
6283
6284namespace {
6285
Bryan Chane3f1ed52016-04-28 13:56:43 +00006286class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006287 bool HasVector;
6288
Ulrich Weigand47445072013-05-06 16:26:41 +00006289public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006290 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006291 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006292
6293 bool isPromotableIntegerType(QualType Ty) const;
6294 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006295 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006296 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006297 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006298
6299 ABIArgInfo classifyReturnType(QualType RetTy) const;
6300 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6301
Craig Topper4f12f102014-03-12 06:41:41 +00006302 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006303 if (!getCXXABI().classifyReturnType(FI))
6304 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006305 for (auto &I : FI.arguments())
6306 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006307 }
6308
John McCall7f416cc2015-09-08 08:05:57 +00006309 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6310 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006311
John McCall56331e22018-01-07 06:28:49 +00006312 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006313 bool asReturnValue) const override {
6314 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6315 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006316 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006317 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006318 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006319};
6320
6321class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6322public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006323 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6324 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006325};
6326
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006327}
Ulrich Weigand47445072013-05-06 16:26:41 +00006328
6329bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6330 // Treat an enum type as its underlying type.
6331 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6332 Ty = EnumTy->getDecl()->getIntegerType();
6333
6334 // Promotable integer types are required to be promoted by the ABI.
6335 if (Ty->isPromotableIntegerType())
6336 return true;
6337
6338 // 32-bit values must also be promoted.
6339 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6340 switch (BT->getKind()) {
6341 case BuiltinType::Int:
6342 case BuiltinType::UInt:
6343 return true;
6344 default:
6345 return false;
6346 }
6347 return false;
6348}
6349
6350bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006351 return (Ty->isAnyComplexType() ||
6352 Ty->isVectorType() ||
6353 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006354}
6355
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006356bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6357 return (HasVector &&
6358 Ty->isVectorType() &&
6359 getContext().getTypeSize(Ty) <= 128);
6360}
6361
Ulrich Weigand47445072013-05-06 16:26:41 +00006362bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6363 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6364 switch (BT->getKind()) {
6365 case BuiltinType::Float:
6366 case BuiltinType::Double:
6367 return true;
6368 default:
6369 return false;
6370 }
6371
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006372 return false;
6373}
6374
6375QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006376 if (const RecordType *RT = Ty->getAsStructureType()) {
6377 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006378 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006379
6380 // If this is a C++ record, check the bases first.
6381 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006382 for (const auto &I : CXXRD->bases()) {
6383 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006384
6385 // Empty bases don't affect things either way.
6386 if (isEmptyRecord(getContext(), Base, true))
6387 continue;
6388
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006389 if (!Found.isNull())
6390 return Ty;
6391 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006392 }
6393
6394 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006395 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006396 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006397 // Unlike isSingleElementStruct(), empty structure and array fields
6398 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006399 if (getContext().getLangOpts().CPlusPlus &&
6400 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6401 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006402
6403 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006404 // Nested structures still do though.
6405 if (!Found.isNull())
6406 return Ty;
6407 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006408 }
6409
6410 // Unlike isSingleElementStruct(), trailing padding is allowed.
6411 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006412 if (!Found.isNull())
6413 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006414 }
6415
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006416 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006417}
6418
John McCall7f416cc2015-09-08 08:05:57 +00006419Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6420 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006421 // Assume that va_list type is correct; should be pointer to LLVM type:
6422 // struct {
6423 // i64 __gpr;
6424 // i64 __fpr;
6425 // i8 *__overflow_arg_area;
6426 // i8 *__reg_save_area;
6427 // };
6428
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006429 // Every non-vector argument occupies 8 bytes and is passed by preference
6430 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6431 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006432 Ty = getContext().getCanonicalType(Ty);
6433 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006434 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006435 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006436 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006437 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006438 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006439 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006440 CharUnits UnpaddedSize;
6441 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006442 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006443 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6444 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006445 } else {
6446 if (AI.getCoerceToType())
6447 ArgTy = AI.getCoerceToType();
6448 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006449 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006450 UnpaddedSize = TyInfo.first;
6451 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006452 }
John McCall7f416cc2015-09-08 08:05:57 +00006453 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6454 if (IsVector && UnpaddedSize > PaddedSize)
6455 PaddedSize = CharUnits::fromQuantity(16);
6456 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006457
John McCall7f416cc2015-09-08 08:05:57 +00006458 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006459
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006460 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006461 llvm::Value *PaddedSizeV =
6462 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006463
6464 if (IsVector) {
6465 // Work out the address of a vector argument on the stack.
6466 // Vector arguments are always passed in the high bits of a
6467 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006468 Address OverflowArgAreaPtr =
6469 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006470 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006471 Address OverflowArgArea =
6472 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6473 TyInfo.second);
6474 Address MemAddr =
6475 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006476
6477 // Update overflow_arg_area_ptr pointer
6478 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006479 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6480 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006481 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6482
6483 return MemAddr;
6484 }
6485
John McCall7f416cc2015-09-08 08:05:57 +00006486 assert(PaddedSize.getQuantity() == 8);
6487
6488 unsigned MaxRegs, RegCountField, RegSaveIndex;
6489 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006490 if (InFPRs) {
6491 MaxRegs = 4; // Maximum of 4 FPR arguments
6492 RegCountField = 1; // __fpr
6493 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006494 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006495 } else {
6496 MaxRegs = 5; // Maximum of 5 GPR arguments
6497 RegCountField = 0; // __gpr
6498 RegSaveIndex = 2; // save offset for r2
6499 RegPadding = Padding; // values are passed in the low bits of a GPR
6500 }
6501
John McCall7f416cc2015-09-08 08:05:57 +00006502 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6503 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6504 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006505 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006506 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6507 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006508 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006509
6510 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6511 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6512 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6513 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6514
6515 // Emit code to load the value if it was passed in registers.
6516 CGF.EmitBlock(InRegBlock);
6517
6518 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006519 llvm::Value *ScaledRegCount =
6520 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6521 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006522 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6523 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006524 llvm::Value *RegOffset =
6525 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006526 Address RegSaveAreaPtr =
6527 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6528 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006529 llvm::Value *RegSaveArea =
6530 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006531 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6532 "raw_reg_addr"),
6533 PaddedSize);
6534 Address RegAddr =
6535 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006536
6537 // Update the register count
6538 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6539 llvm::Value *NewRegCount =
6540 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6541 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6542 CGF.EmitBranch(ContBlock);
6543
6544 // Emit code to load the value if it was passed in memory.
6545 CGF.EmitBlock(InMemBlock);
6546
6547 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006548 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6549 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6550 Address OverflowArgArea =
6551 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6552 PaddedSize);
6553 Address RawMemAddr =
6554 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6555 Address MemAddr =
6556 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006557
6558 // Update overflow_arg_area_ptr pointer
6559 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006560 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6561 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006562 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6563 CGF.EmitBranch(ContBlock);
6564
6565 // Return the appropriate result.
6566 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006567 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6568 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006569
6570 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006571 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6572 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006573
6574 return ResAddr;
6575}
6576
Ulrich Weigand47445072013-05-06 16:26:41 +00006577ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6578 if (RetTy->isVoidType())
6579 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006580 if (isVectorArgumentType(RetTy))
6581 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006582 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006583 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006584 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6585 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006586}
6587
6588ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6589 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006590 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006591 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006592
6593 // Integers and enums are extended to full register width.
6594 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006595 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006596
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006597 // Handle vector types and vector-like structure types. Note that
6598 // as opposed to float-like structure types, we do not allow any
6599 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006600 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006601 QualType SingleElementTy = GetSingleElementType(Ty);
6602 if (isVectorArgumentType(SingleElementTy) &&
6603 getContext().getTypeSize(SingleElementTy) == Size)
6604 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6605
6606 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006607 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006608 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006609
6610 // Handle small structures.
6611 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6612 // Structures with flexible arrays have variable length, so really
6613 // fail the size test above.
6614 const RecordDecl *RD = RT->getDecl();
6615 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006616 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006617
6618 // The structure is passed as an unextended integer, a float, or a double.
6619 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006620 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006621 assert(Size == 32 || Size == 64);
6622 if (Size == 32)
6623 PassTy = llvm::Type::getFloatTy(getVMContext());
6624 else
6625 PassTy = llvm::Type::getDoubleTy(getVMContext());
6626 } else
6627 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6628 return ABIArgInfo::getDirect(PassTy);
6629 }
6630
6631 // Non-structure compounds are passed indirectly.
6632 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006633 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006634
Craig Topper8a13c412014-05-21 05:09:00 +00006635 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006636}
6637
6638//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006639// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006640//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006641
6642namespace {
6643
6644class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6645public:
Chris Lattner2b037972010-07-29 02:01:43 +00006646 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6647 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006648 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006649 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006650};
6651
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006652}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006653
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006654void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006655 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6656 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006657 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006658 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006659 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6660 // Handle 'interrupt' attribute:
6661 llvm::Function *F = cast<llvm::Function>(GV);
6662
6663 // Step 1: Set ISR calling convention.
6664 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6665
6666 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006667 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006668
6669 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006670 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006671 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6672 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006673 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006674 }
6675}
6676
Chris Lattner0cf24192010-06-28 20:05:43 +00006677//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006678// MIPS ABI Implementation. This works for both little-endian and
6679// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006680//===----------------------------------------------------------------------===//
6681
John McCall943fae92010-05-27 06:19:26 +00006682namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006683class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006684 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006685 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6686 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006687 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006688 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006689 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006690 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006691public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006692 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006693 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006694 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006695
6696 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006697 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006698 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006699 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6700 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006701 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006702};
6703
John McCall943fae92010-05-27 06:19:26 +00006704class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006705 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006706public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006707 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6708 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006709 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006710
Craig Topper4f12f102014-03-12 06:41:41 +00006711 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006712 return 29;
6713 }
6714
Eric Christopher162c91c2015-06-05 22:03:00 +00006715 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006716 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006717 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006718 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006719 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006720
6721 if (FD->hasAttr<MipsLongCallAttr>())
6722 Fn->addFnAttr("long-call");
6723 else if (FD->hasAttr<MipsShortCallAttr>())
6724 Fn->addFnAttr("short-call");
6725
6726 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006727 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006728 return;
6729
Reed Kotler3d5966f2013-03-13 20:40:30 +00006730 if (FD->hasAttr<Mips16Attr>()) {
6731 Fn->addFnAttr("mips16");
6732 }
6733 else if (FD->hasAttr<NoMips16Attr>()) {
6734 Fn->addFnAttr("nomips16");
6735 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006736
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006737 if (FD->hasAttr<MicroMipsAttr>())
6738 Fn->addFnAttr("micromips");
6739 else if (FD->hasAttr<NoMicroMipsAttr>())
6740 Fn->addFnAttr("nomicromips");
6741
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006742 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6743 if (!Attr)
6744 return;
6745
6746 const char *Kind;
6747 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006748 case MipsInterruptAttr::eic: Kind = "eic"; break;
6749 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6750 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6751 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6752 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6753 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6754 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6755 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6756 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6757 }
6758
6759 Fn->addFnAttr("interrupt", Kind);
6760
Reed Kotler373feca2013-01-16 17:10:28 +00006761 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006762
John McCall943fae92010-05-27 06:19:26 +00006763 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006764 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006765
Craig Topper4f12f102014-03-12 06:41:41 +00006766 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006767 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006768 }
John McCall943fae92010-05-27 06:19:26 +00006769};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006770}
John McCall943fae92010-05-27 06:19:26 +00006771
Eric Christopher7565e0d2015-05-29 23:09:49 +00006772void MipsABIInfo::CoerceToIntArgs(
6773 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006774 llvm::IntegerType *IntTy =
6775 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006776
6777 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6778 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6779 ArgList.push_back(IntTy);
6780
6781 // If necessary, add one more integer type to ArgList.
6782 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6783
6784 if (R)
6785 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006786}
6787
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006788// In N32/64, an aligned double precision floating point field is passed in
6789// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006790llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006791 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6792
6793 if (IsO32) {
6794 CoerceToIntArgs(TySize, ArgList);
6795 return llvm::StructType::get(getVMContext(), ArgList);
6796 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006797
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006798 if (Ty->isComplexType())
6799 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006800
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006801 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006802
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006803 // Unions/vectors are passed in integer registers.
6804 if (!RT || !RT->isStructureOrClassType()) {
6805 CoerceToIntArgs(TySize, ArgList);
6806 return llvm::StructType::get(getVMContext(), ArgList);
6807 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006808
6809 const RecordDecl *RD = RT->getDecl();
6810 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006811 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006812
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006813 uint64_t LastOffset = 0;
6814 unsigned idx = 0;
6815 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6816
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006817 // Iterate over fields in the struct/class and check if there are any aligned
6818 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006819 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6820 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006821 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006822 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6823
6824 if (!BT || BT->getKind() != BuiltinType::Double)
6825 continue;
6826
6827 uint64_t Offset = Layout.getFieldOffset(idx);
6828 if (Offset % 64) // Ignore doubles that are not aligned.
6829 continue;
6830
6831 // Add ((Offset - LastOffset) / 64) args of type i64.
6832 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6833 ArgList.push_back(I64);
6834
6835 // Add double type.
6836 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6837 LastOffset = Offset + 64;
6838 }
6839
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006840 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6841 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006842
6843 return llvm::StructType::get(getVMContext(), ArgList);
6844}
6845
Akira Hatanakaddd66342013-10-29 18:41:15 +00006846llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6847 uint64_t Offset) const {
6848 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006849 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006850
Akira Hatanakaddd66342013-10-29 18:41:15 +00006851 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006852}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006853
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006854ABIArgInfo
6855MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006856 Ty = useFirstFieldIfTransparentUnion(Ty);
6857
Akira Hatanaka1632af62012-01-09 19:31:25 +00006858 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006859 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006860 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006861
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006862 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6863 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006864 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6865 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006866
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006867 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006868 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006869 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006870 return ABIArgInfo::getIgnore();
6871
Mark Lacey3825e832013-10-06 01:33:34 +00006872 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006873 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006874 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006875 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006876
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006877 // If we have reached here, aggregates are passed directly by coercing to
6878 // another structure type. Padding is inserted if the offset of the
6879 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006880 ABIArgInfo ArgInfo =
6881 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6882 getPaddingType(OrigOffset, CurrOffset));
6883 ArgInfo.setInReg(true);
6884 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006885 }
6886
6887 // Treat an enum type as its underlying type.
6888 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6889 Ty = EnumTy->getDecl()->getIntegerType();
6890
Daniel Sanders5b445b32014-10-24 14:42:42 +00006891 // All integral types are promoted to the GPR width.
6892 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00006893 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006894
Akira Hatanakaddd66342013-10-29 18:41:15 +00006895 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006896 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006897}
6898
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006899llvm::Type*
6900MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006901 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006902 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006903
Akira Hatanakab6f74432012-02-09 18:49:26 +00006904 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006905 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006906 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6907 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006908
Akira Hatanakab6f74432012-02-09 18:49:26 +00006909 // N32/64 returns struct/classes in floating point registers if the
6910 // following conditions are met:
6911 // 1. The size of the struct/class is no larger than 128-bit.
6912 // 2. The struct/class has one or two fields all of which are floating
6913 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006914 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006915 //
6916 // Any other composite results are returned in integer registers.
6917 //
6918 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6919 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6920 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006921 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006922
Akira Hatanakab6f74432012-02-09 18:49:26 +00006923 if (!BT || !BT->isFloatingPoint())
6924 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006925
David Blaikie2d7c57e2012-04-30 02:36:29 +00006926 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006927 }
6928
6929 if (b == e)
6930 return llvm::StructType::get(getVMContext(), RTList,
6931 RD->hasAttr<PackedAttr>());
6932
6933 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006934 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006935 }
6936
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006937 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006938 return llvm::StructType::get(getVMContext(), RTList);
6939}
6940
Akira Hatanakab579fe52011-06-02 00:09:17 +00006941ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006942 uint64_t Size = getContext().getTypeSize(RetTy);
6943
Daniel Sandersed39f582014-09-04 13:28:14 +00006944 if (RetTy->isVoidType())
6945 return ABIArgInfo::getIgnore();
6946
6947 // O32 doesn't treat zero-sized structs differently from other structs.
6948 // However, N32/N64 ignores zero sized return values.
6949 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006950 return ABIArgInfo::getIgnore();
6951
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006952 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006953 if (Size <= 128) {
6954 if (RetTy->isAnyComplexType())
6955 return ABIArgInfo::getDirect();
6956
Daniel Sanderse5018b62014-09-04 15:05:39 +00006957 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006958 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006959 if (!IsO32 ||
6960 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6961 ABIArgInfo ArgInfo =
6962 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6963 ArgInfo.setInReg(true);
6964 return ArgInfo;
6965 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006966 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006967
John McCall7f416cc2015-09-08 08:05:57 +00006968 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006969 }
6970
6971 // Treat an enum type as its underlying type.
6972 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6973 RetTy = EnumTy->getDecl()->getIntegerType();
6974
Alex Bradburye41a5e22018-01-12 20:08:16 +00006975 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6976 : ABIArgInfo::getDirect());
Akira Hatanakab579fe52011-06-02 00:09:17 +00006977}
6978
6979void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006980 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006981 if (!getCXXABI().classifyReturnType(FI))
6982 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006983
Eric Christopher7565e0d2015-05-29 23:09:49 +00006984 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006985 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006986
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006987 for (auto &I : FI.arguments())
6988 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006989}
6990
John McCall7f416cc2015-09-08 08:05:57 +00006991Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6992 QualType OrigTy) const {
6993 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006994
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006995 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6996 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006997 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006998 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006999 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007000 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007001 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007002 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007003 DidPromote = true;
7004 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7005 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007006 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007007
John McCall7f416cc2015-09-08 08:05:57 +00007008 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007009
John McCall7f416cc2015-09-08 08:05:57 +00007010 // The alignment of things in the argument area is never larger than
7011 // StackAlignInBytes.
7012 TyInfo.second =
7013 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7014
7015 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7016 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7017
7018 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7019 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7020
7021
7022 // If there was a promotion, "unpromote" into a temporary.
7023 // TODO: can we just use a pointer into a subset of the original slot?
7024 if (DidPromote) {
7025 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7026 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7027
7028 // Truncate down to the right width.
7029 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7030 : CGF.IntPtrTy);
7031 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7032 if (OrigTy->isPointerType())
7033 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7034
7035 CGF.Builder.CreateStore(V, Temp);
7036 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007037 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007038
John McCall7f416cc2015-09-08 08:05:57 +00007039 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007040}
7041
Alex Bradburye41a5e22018-01-12 20:08:16 +00007042ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007043 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007044
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007045 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7046 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007047 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007048
Alex Bradburye41a5e22018-01-12 20:08:16 +00007049 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007050}
7051
John McCall943fae92010-05-27 06:19:26 +00007052bool
7053MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7054 llvm::Value *Address) const {
7055 // This information comes from gcc's implementation, which seems to
7056 // as canonical as it gets.
7057
John McCall943fae92010-05-27 06:19:26 +00007058 // Everything on MIPS is 4 bytes. Double-precision FP registers
7059 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007060 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007061
7062 // 0-31 are the general purpose registers, $0 - $31.
7063 // 32-63 are the floating-point registers, $f0 - $f31.
7064 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7065 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007066 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007067
7068 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7069 // They are one bit wide and ignored here.
7070
7071 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7072 // (coprocessor 1 is the FP unit)
7073 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7074 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7075 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007076 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007077 return false;
7078}
7079
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007080//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007081// AVR ABI Implementation.
7082//===----------------------------------------------------------------------===//
7083
7084namespace {
7085class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7086public:
7087 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7088 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7089
7090 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007091 CodeGen::CodeGenModule &CGM) const override {
7092 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007093 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007094 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7095 if (!FD) return;
7096 auto *Fn = cast<llvm::Function>(GV);
7097
7098 if (FD->getAttr<AVRInterruptAttr>())
7099 Fn->addFnAttr("interrupt");
7100
7101 if (FD->getAttr<AVRSignalAttr>())
7102 Fn->addFnAttr("signal");
7103 }
7104};
7105}
7106
7107//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007108// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007109// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007110// handling.
7111//===----------------------------------------------------------------------===//
7112
7113namespace {
7114
7115class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7116public:
7117 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7118 : DefaultTargetCodeGenInfo(CGT) {}
7119
Eric Christopher162c91c2015-06-05 22:03:00 +00007120 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007121 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007122};
7123
Eric Christopher162c91c2015-06-05 22:03:00 +00007124void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007125 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7126 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007127 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007128 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007129 if (!FD) return;
7130
7131 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007132
David Blaikiebbafb8a2012-03-11 07:00:24 +00007133 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007134 if (FD->hasAttr<OpenCLKernelAttr>()) {
7135 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007136 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007137 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7138 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007139 // Convert the reqd_work_group_size() attributes to metadata.
7140 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007141 llvm::NamedMDNode *OpenCLMetadata =
7142 M.getModule().getOrInsertNamedMetadata(
7143 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007144
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007145 SmallVector<llvm::Metadata *, 5> Operands;
7146 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007147
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007148 Operands.push_back(
7149 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7150 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7151 Operands.push_back(
7152 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7153 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7154 Operands.push_back(
7155 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7156 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007157
Eric Christopher7565e0d2015-05-29 23:09:49 +00007158 // Add a boolean constant operand for "required" (true) or "hint"
7159 // (false) for implementing the work_group_size_hint attr later.
7160 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007161 Operands.push_back(
7162 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007163 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7164 }
7165 }
7166 }
7167}
7168
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007169}
John McCall943fae92010-05-27 06:19:26 +00007170
Tony Linthicum76329bf2011-12-12 21:14:55 +00007171//===----------------------------------------------------------------------===//
7172// Hexagon ABI Implementation
7173//===----------------------------------------------------------------------===//
7174
7175namespace {
7176
7177class HexagonABIInfo : public ABIInfo {
7178
7179
7180public:
7181 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7182
7183private:
7184
7185 ABIArgInfo classifyReturnType(QualType RetTy) const;
7186 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7187
Craig Topper4f12f102014-03-12 06:41:41 +00007188 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007189
John McCall7f416cc2015-09-08 08:05:57 +00007190 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7191 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007192};
7193
7194class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7195public:
7196 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7197 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7198
Craig Topper4f12f102014-03-12 06:41:41 +00007199 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007200 return 29;
7201 }
7202};
7203
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007204}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007205
7206void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007207 if (!getCXXABI().classifyReturnType(FI))
7208 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007209 for (auto &I : FI.arguments())
7210 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007211}
7212
7213ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7214 if (!isAggregateTypeForABI(Ty)) {
7215 // Treat an enum type as its underlying type.
7216 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7217 Ty = EnumTy->getDecl()->getIntegerType();
7218
Alex Bradburye41a5e22018-01-12 20:08:16 +00007219 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7220 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007221 }
7222
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007223 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7224 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7225
Tony Linthicum76329bf2011-12-12 21:14:55 +00007226 // Ignore empty records.
7227 if (isEmptyRecord(getContext(), Ty, true))
7228 return ABIArgInfo::getIgnore();
7229
Tony Linthicum76329bf2011-12-12 21:14:55 +00007230 uint64_t Size = getContext().getTypeSize(Ty);
7231 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007232 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007233 // Pass in the smallest viable integer type.
7234 else if (Size > 32)
7235 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7236 else if (Size > 16)
7237 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7238 else if (Size > 8)
7239 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7240 else
7241 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7242}
7243
7244ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7245 if (RetTy->isVoidType())
7246 return ABIArgInfo::getIgnore();
7247
7248 // Large vector types should be returned via memory.
7249 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007250 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007251
7252 if (!isAggregateTypeForABI(RetTy)) {
7253 // Treat an enum type as its underlying type.
7254 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7255 RetTy = EnumTy->getDecl()->getIntegerType();
7256
Alex Bradburye41a5e22018-01-12 20:08:16 +00007257 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7258 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007259 }
7260
Tony Linthicum76329bf2011-12-12 21:14:55 +00007261 if (isEmptyRecord(getContext(), RetTy, true))
7262 return ABIArgInfo::getIgnore();
7263
7264 // Aggregates <= 8 bytes are returned in r0; other aggregates
7265 // are returned indirectly.
7266 uint64_t Size = getContext().getTypeSize(RetTy);
7267 if (Size <= 64) {
7268 // Return in the smallest viable integer type.
7269 if (Size <= 8)
7270 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7271 if (Size <= 16)
7272 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7273 if (Size <= 32)
7274 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7275 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7276 }
7277
John McCall7f416cc2015-09-08 08:05:57 +00007278 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007279}
7280
John McCall7f416cc2015-09-08 08:05:57 +00007281Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7282 QualType Ty) const {
7283 // FIXME: Someone needs to audit that this handle alignment correctly.
7284 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7285 getContext().getTypeInfoInChars(Ty),
7286 CharUnits::fromQuantity(4),
7287 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007288}
7289
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007290//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007291// Lanai ABI Implementation
7292//===----------------------------------------------------------------------===//
7293
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007294namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007295class LanaiABIInfo : public DefaultABIInfo {
7296public:
7297 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7298
7299 bool shouldUseInReg(QualType Ty, CCState &State) const;
7300
7301 void computeInfo(CGFunctionInfo &FI) const override {
7302 CCState State(FI.getCallingConvention());
7303 // Lanai uses 4 registers to pass arguments unless the function has the
7304 // regparm attribute set.
7305 if (FI.getHasRegParm()) {
7306 State.FreeRegs = FI.getRegParm();
7307 } else {
7308 State.FreeRegs = 4;
7309 }
7310
7311 if (!getCXXABI().classifyReturnType(FI))
7312 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7313 for (auto &I : FI.arguments())
7314 I.info = classifyArgumentType(I.type, State);
7315 }
7316
Jacques Pienaare74d9132016-04-26 00:09:29 +00007317 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007318 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7319};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007320} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007321
7322bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7323 unsigned Size = getContext().getTypeSize(Ty);
7324 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7325
7326 if (SizeInRegs == 0)
7327 return false;
7328
7329 if (SizeInRegs > State.FreeRegs) {
7330 State.FreeRegs = 0;
7331 return false;
7332 }
7333
7334 State.FreeRegs -= SizeInRegs;
7335
7336 return true;
7337}
7338
Jacques Pienaare74d9132016-04-26 00:09:29 +00007339ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7340 CCState &State) const {
7341 if (!ByVal) {
7342 if (State.FreeRegs) {
7343 --State.FreeRegs; // Non-byval indirects just use one pointer.
7344 return getNaturalAlignIndirectInReg(Ty);
7345 }
7346 return getNaturalAlignIndirect(Ty, false);
7347 }
7348
7349 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007350 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007351 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7352 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7353 /*Realign=*/TypeAlign >
7354 MinABIStackAlignInBytes);
7355}
7356
Jacques Pienaard964cc22016-03-28 21:02:54 +00007357ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7358 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007359 // Check with the C++ ABI first.
7360 const RecordType *RT = Ty->getAs<RecordType>();
7361 if (RT) {
7362 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7363 if (RAA == CGCXXABI::RAA_Indirect) {
7364 return getIndirectResult(Ty, /*ByVal=*/false, State);
7365 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7366 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7367 }
7368 }
7369
7370 if (isAggregateTypeForABI(Ty)) {
7371 // Structures with flexible arrays are always indirect.
7372 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7373 return getIndirectResult(Ty, /*ByVal=*/true, State);
7374
7375 // Ignore empty structs/unions.
7376 if (isEmptyRecord(getContext(), Ty, true))
7377 return ABIArgInfo::getIgnore();
7378
7379 llvm::LLVMContext &LLVMContext = getVMContext();
7380 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7381 if (SizeInRegs <= State.FreeRegs) {
7382 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7383 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7384 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7385 State.FreeRegs -= SizeInRegs;
7386 return ABIArgInfo::getDirectInReg(Result);
7387 } else {
7388 State.FreeRegs = 0;
7389 }
7390 return getIndirectResult(Ty, true, State);
7391 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007392
7393 // Treat an enum type as its underlying type.
7394 if (const auto *EnumTy = Ty->getAs<EnumType>())
7395 Ty = EnumTy->getDecl()->getIntegerType();
7396
Jacques Pienaare74d9132016-04-26 00:09:29 +00007397 bool InReg = shouldUseInReg(Ty, State);
7398 if (Ty->isPromotableIntegerType()) {
7399 if (InReg)
7400 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007401 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007402 }
7403 if (InReg)
7404 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007405 return ABIArgInfo::getDirect();
7406}
7407
7408namespace {
7409class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7410public:
7411 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7412 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7413};
7414}
7415
7416//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007417// AMDGPU ABI Implementation
7418//===----------------------------------------------------------------------===//
7419
7420namespace {
7421
Matt Arsenault88d7da02016-08-22 19:25:59 +00007422class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007423private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007424 static const unsigned MaxNumRegsForArgsRet = 16;
7425
Matt Arsenault3fe73952017-08-09 21:44:58 +00007426 unsigned numRegsForType(QualType Ty) const;
7427
7428 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7429 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7430 uint64_t Members) const override;
7431
7432public:
7433 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7434 DefaultABIInfo(CGT) {}
7435
7436 ABIArgInfo classifyReturnType(QualType RetTy) const;
7437 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7438 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007439
7440 void computeInfo(CGFunctionInfo &FI) const override;
7441};
7442
Matt Arsenault3fe73952017-08-09 21:44:58 +00007443bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7444 return true;
7445}
7446
7447bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7448 const Type *Base, uint64_t Members) const {
7449 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7450
7451 // Homogeneous Aggregates may occupy at most 16 registers.
7452 return Members * NumRegs <= MaxNumRegsForArgsRet;
7453}
7454
Matt Arsenault3fe73952017-08-09 21:44:58 +00007455/// Estimate number of registers the type will use when passed in registers.
7456unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7457 unsigned NumRegs = 0;
7458
7459 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7460 // Compute from the number of elements. The reported size is based on the
7461 // in-memory size, which includes the padding 4th element for 3-vectors.
7462 QualType EltTy = VT->getElementType();
7463 unsigned EltSize = getContext().getTypeSize(EltTy);
7464
7465 // 16-bit element vectors should be passed as packed.
7466 if (EltSize == 16)
7467 return (VT->getNumElements() + 1) / 2;
7468
7469 unsigned EltNumRegs = (EltSize + 31) / 32;
7470 return EltNumRegs * VT->getNumElements();
7471 }
7472
7473 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7474 const RecordDecl *RD = RT->getDecl();
7475 assert(!RD->hasFlexibleArrayMember());
7476
7477 for (const FieldDecl *Field : RD->fields()) {
7478 QualType FieldTy = Field->getType();
7479 NumRegs += numRegsForType(FieldTy);
7480 }
7481
7482 return NumRegs;
7483 }
7484
7485 return (getContext().getTypeSize(Ty) + 31) / 32;
7486}
7487
Matt Arsenault88d7da02016-08-22 19:25:59 +00007488void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007489 llvm::CallingConv::ID CC = FI.getCallingConvention();
7490
Matt Arsenault88d7da02016-08-22 19:25:59 +00007491 if (!getCXXABI().classifyReturnType(FI))
7492 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7493
Matt Arsenault3fe73952017-08-09 21:44:58 +00007494 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7495 for (auto &Arg : FI.arguments()) {
7496 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7497 Arg.info = classifyKernelArgumentType(Arg.type);
7498 } else {
7499 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7500 }
7501 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007502}
7503
Matt Arsenault3fe73952017-08-09 21:44:58 +00007504ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7505 if (isAggregateTypeForABI(RetTy)) {
7506 // Records with non-trivial destructors/copy-constructors should not be
7507 // returned by value.
7508 if (!getRecordArgABI(RetTy, getCXXABI())) {
7509 // Ignore empty structs/unions.
7510 if (isEmptyRecord(getContext(), RetTy, true))
7511 return ABIArgInfo::getIgnore();
7512
7513 // Lower single-element structs to just return a regular value.
7514 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7515 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7516
7517 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7518 const RecordDecl *RD = RT->getDecl();
7519 if (RD->hasFlexibleArrayMember())
7520 return DefaultABIInfo::classifyReturnType(RetTy);
7521 }
7522
7523 // Pack aggregates <= 4 bytes into single VGPR or pair.
7524 uint64_t Size = getContext().getTypeSize(RetTy);
7525 if (Size <= 16)
7526 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7527
7528 if (Size <= 32)
7529 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7530
7531 if (Size <= 64) {
7532 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7533 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7534 }
7535
7536 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7537 return ABIArgInfo::getDirect();
7538 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007539 }
7540
Matt Arsenault3fe73952017-08-09 21:44:58 +00007541 // Otherwise just do the default thing.
7542 return DefaultABIInfo::classifyReturnType(RetTy);
7543}
7544
7545/// For kernels all parameters are really passed in a special buffer. It doesn't
7546/// make sense to pass anything byval, so everything must be direct.
7547ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7548 Ty = useFirstFieldIfTransparentUnion(Ty);
7549
7550 // TODO: Can we omit empty structs?
7551
Matt Arsenault88d7da02016-08-22 19:25:59 +00007552 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007553 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7554 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007555
7556 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7557 // individual elements, which confuses the Clover OpenCL backend; therefore we
7558 // have to set it to false here. Other args of getDirect() are just defaults.
7559 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7560}
7561
Matt Arsenault3fe73952017-08-09 21:44:58 +00007562ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7563 unsigned &NumRegsLeft) const {
7564 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7565
7566 Ty = useFirstFieldIfTransparentUnion(Ty);
7567
7568 if (isAggregateTypeForABI(Ty)) {
7569 // Records with non-trivial destructors/copy-constructors should not be
7570 // passed by value.
7571 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7572 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7573
7574 // Ignore empty structs/unions.
7575 if (isEmptyRecord(getContext(), Ty, true))
7576 return ABIArgInfo::getIgnore();
7577
7578 // Lower single-element structs to just pass a regular value. TODO: We
7579 // could do reasonable-size multiple-element structs too, using getExpand(),
7580 // though watch out for things like bitfields.
7581 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7582 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7583
7584 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7585 const RecordDecl *RD = RT->getDecl();
7586 if (RD->hasFlexibleArrayMember())
7587 return DefaultABIInfo::classifyArgumentType(Ty);
7588 }
7589
7590 // Pack aggregates <= 8 bytes into single VGPR or pair.
7591 uint64_t Size = getContext().getTypeSize(Ty);
7592 if (Size <= 64) {
7593 unsigned NumRegs = (Size + 31) / 32;
7594 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7595
7596 if (Size <= 16)
7597 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7598
7599 if (Size <= 32)
7600 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7601
7602 // XXX: Should this be i64 instead, and should the limit increase?
7603 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7604 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7605 }
7606
7607 if (NumRegsLeft > 0) {
7608 unsigned NumRegs = numRegsForType(Ty);
7609 if (NumRegsLeft >= NumRegs) {
7610 NumRegsLeft -= NumRegs;
7611 return ABIArgInfo::getDirect();
7612 }
7613 }
7614 }
7615
7616 // Otherwise just do the default thing.
7617 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7618 if (!ArgInfo.isIndirect()) {
7619 unsigned NumRegs = numRegsForType(Ty);
7620 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7621 }
7622
7623 return ArgInfo;
7624}
7625
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007626class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7627public:
7628 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007629 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007630 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007631 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007632 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007633
Yaxun Liu402804b2016-12-15 08:09:08 +00007634 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7635 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007636
Alexander Richardson6d989432017-10-15 18:48:14 +00007637 LangAS getASTAllocaAddressSpace() const override {
7638 return getLangASFromTargetAS(
7639 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007640 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007641 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7642 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007643 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7644 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007645 llvm::Function *
7646 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7647 llvm::Function *BlockInvokeFunc,
7648 llvm::Value *BlockLiteral) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007649};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007650}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007651
Eric Christopher162c91c2015-06-05 22:03:00 +00007652void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007653 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7654 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007655 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007656 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007657 if (!FD)
7658 return;
7659
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007660 llvm::Function *F = cast<llvm::Function>(GV);
7661
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007662 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7663 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007664
7665 if (M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>() &&
7666 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Tony Tye68e11a62018-03-23 18:51:45 +00007667 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007668
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007669 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7670 if (ReqdWGS || FlatWGS) {
7671 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7672 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7673 if (ReqdWGS && Min == 0 && Max == 0)
7674 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007675
7676 if (Min != 0) {
7677 assert(Min <= Max && "Min must be less than or equal Max");
7678
7679 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7680 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7681 } else
7682 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007683 }
7684
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007685 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7686 unsigned Min = Attr->getMin();
7687 unsigned Max = Attr->getMax();
7688
7689 if (Min != 0) {
7690 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7691
7692 std::string AttrVal = llvm::utostr(Min);
7693 if (Max != 0)
7694 AttrVal = AttrVal + "," + llvm::utostr(Max);
7695 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7696 } else
7697 assert(Max == 0 && "Max must be zero");
7698 }
7699
7700 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007701 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007702
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007703 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007704 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7705 }
7706
7707 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7708 uint32_t NumVGPR = Attr->getNumVGPR();
7709
7710 if (NumVGPR != 0)
7711 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007712 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007713}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007714
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007715unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7716 return llvm::CallingConv::AMDGPU_KERNEL;
7717}
7718
Yaxun Liu402804b2016-12-15 08:09:08 +00007719// Currently LLVM assumes null pointers always have value 0,
7720// which results in incorrectly transformed IR. Therefore, instead of
7721// emitting null pointers in private and local address spaces, a null
7722// pointer in generic address space is emitted which is casted to a
7723// pointer in local or private address space.
7724llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7725 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7726 QualType QT) const {
7727 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7728 return llvm::ConstantPointerNull::get(PT);
7729
7730 auto &Ctx = CGM.getContext();
7731 auto NPT = llvm::PointerType::get(PT->getElementType(),
7732 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7733 return llvm::ConstantExpr::getAddrSpaceCast(
7734 llvm::ConstantPointerNull::get(NPT), PT);
7735}
7736
Alexander Richardson6d989432017-10-15 18:48:14 +00007737LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007738AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7739 const VarDecl *D) const {
7740 assert(!CGM.getLangOpts().OpenCL &&
7741 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7742 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007743 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7744 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007745 if (!D)
7746 return DefaultGlobalAS;
7747
Alexander Richardson6d989432017-10-15 18:48:14 +00007748 LangAS AddrSpace = D->getType().getAddressSpace();
7749 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007750 if (AddrSpace != LangAS::Default)
7751 return AddrSpace;
7752
7753 if (CGM.isTypeConstant(D->getType(), false)) {
7754 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7755 return ConstAS.getValue();
7756 }
7757 return DefaultGlobalAS;
7758}
7759
Yaxun Liu39195062017-08-04 18:16:31 +00007760llvm::SyncScope::ID
7761AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7762 llvm::LLVMContext &C) const {
7763 StringRef Name;
7764 switch (S) {
7765 case SyncScope::OpenCLWorkGroup:
7766 Name = "workgroup";
7767 break;
7768 case SyncScope::OpenCLDevice:
7769 Name = "agent";
7770 break;
7771 case SyncScope::OpenCLAllSVMDevices:
7772 Name = "";
7773 break;
7774 case SyncScope::OpenCLSubGroup:
7775 Name = "subgroup";
7776 }
7777 return C.getOrInsertSyncScopeID(Name);
7778}
7779
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007780//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007781// SPARC v8 ABI Implementation.
7782// Based on the SPARC Compliance Definition version 2.4.1.
7783//
7784// Ensures that complex values are passed in registers.
7785//
7786namespace {
7787class SparcV8ABIInfo : public DefaultABIInfo {
7788public:
7789 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7790
7791private:
7792 ABIArgInfo classifyReturnType(QualType RetTy) const;
7793 void computeInfo(CGFunctionInfo &FI) const override;
7794};
7795} // end anonymous namespace
7796
7797
7798ABIArgInfo
7799SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7800 if (Ty->isAnyComplexType()) {
7801 return ABIArgInfo::getDirect();
7802 }
7803 else {
7804 return DefaultABIInfo::classifyReturnType(Ty);
7805 }
7806}
7807
7808void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7809
7810 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7811 for (auto &Arg : FI.arguments())
7812 Arg.info = classifyArgumentType(Arg.type);
7813}
7814
7815namespace {
7816class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7817public:
7818 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7819 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7820};
7821} // end anonymous namespace
7822
7823//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007824// SPARC v9 ABI Implementation.
7825// Based on the SPARC Compliance Definition version 2.4.1.
7826//
7827// Function arguments a mapped to a nominal "parameter array" and promoted to
7828// registers depending on their type. Each argument occupies 8 or 16 bytes in
7829// the array, structs larger than 16 bytes are passed indirectly.
7830//
7831// One case requires special care:
7832//
7833// struct mixed {
7834// int i;
7835// float f;
7836// };
7837//
7838// When a struct mixed is passed by value, it only occupies 8 bytes in the
7839// parameter array, but the int is passed in an integer register, and the float
7840// is passed in a floating point register. This is represented as two arguments
7841// with the LLVM IR inreg attribute:
7842//
7843// declare void f(i32 inreg %i, float inreg %f)
7844//
7845// The code generator will only allocate 4 bytes from the parameter array for
7846// the inreg arguments. All other arguments are allocated a multiple of 8
7847// bytes.
7848//
7849namespace {
7850class SparcV9ABIInfo : public ABIInfo {
7851public:
7852 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7853
7854private:
7855 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007856 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007857 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7858 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007859
7860 // Coercion type builder for structs passed in registers. The coercion type
7861 // serves two purposes:
7862 //
7863 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7864 // in registers.
7865 // 2. Expose aligned floating point elements as first-level elements, so the
7866 // code generator knows to pass them in floating point registers.
7867 //
7868 // We also compute the InReg flag which indicates that the struct contains
7869 // aligned 32-bit floats.
7870 //
7871 struct CoerceBuilder {
7872 llvm::LLVMContext &Context;
7873 const llvm::DataLayout &DL;
7874 SmallVector<llvm::Type*, 8> Elems;
7875 uint64_t Size;
7876 bool InReg;
7877
7878 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7879 : Context(c), DL(dl), Size(0), InReg(false) {}
7880
7881 // Pad Elems with integers until Size is ToSize.
7882 void pad(uint64_t ToSize) {
7883 assert(ToSize >= Size && "Cannot remove elements");
7884 if (ToSize == Size)
7885 return;
7886
7887 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007888 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007889 if (Aligned > Size && Aligned <= ToSize) {
7890 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7891 Size = Aligned;
7892 }
7893
7894 // Add whole 64-bit words.
7895 while (Size + 64 <= ToSize) {
7896 Elems.push_back(llvm::Type::getInt64Ty(Context));
7897 Size += 64;
7898 }
7899
7900 // Final in-word padding.
7901 if (Size < ToSize) {
7902 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7903 Size = ToSize;
7904 }
7905 }
7906
7907 // Add a floating point element at Offset.
7908 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7909 // Unaligned floats are treated as integers.
7910 if (Offset % Bits)
7911 return;
7912 // The InReg flag is only required if there are any floats < 64 bits.
7913 if (Bits < 64)
7914 InReg = true;
7915 pad(Offset);
7916 Elems.push_back(Ty);
7917 Size = Offset + Bits;
7918 }
7919
7920 // Add a struct type to the coercion type, starting at Offset (in bits).
7921 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7922 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7923 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7924 llvm::Type *ElemTy = StrTy->getElementType(i);
7925 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7926 switch (ElemTy->getTypeID()) {
7927 case llvm::Type::StructTyID:
7928 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7929 break;
7930 case llvm::Type::FloatTyID:
7931 addFloat(ElemOffset, ElemTy, 32);
7932 break;
7933 case llvm::Type::DoubleTyID:
7934 addFloat(ElemOffset, ElemTy, 64);
7935 break;
7936 case llvm::Type::FP128TyID:
7937 addFloat(ElemOffset, ElemTy, 128);
7938 break;
7939 case llvm::Type::PointerTyID:
7940 if (ElemOffset % 64 == 0) {
7941 pad(ElemOffset);
7942 Elems.push_back(ElemTy);
7943 Size += 64;
7944 }
7945 break;
7946 default:
7947 break;
7948 }
7949 }
7950 }
7951
7952 // Check if Ty is a usable substitute for the coercion type.
7953 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007954 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007955 }
7956
7957 // Get the coercion type as a literal struct type.
7958 llvm::Type *getType() const {
7959 if (Elems.size() == 1)
7960 return Elems.front();
7961 else
7962 return llvm::StructType::get(Context, Elems);
7963 }
7964 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007965};
7966} // end anonymous namespace
7967
7968ABIArgInfo
7969SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7970 if (Ty->isVoidType())
7971 return ABIArgInfo::getIgnore();
7972
7973 uint64_t Size = getContext().getTypeSize(Ty);
7974
7975 // Anything too big to fit in registers is passed with an explicit indirect
7976 // pointer / sret pointer.
7977 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007978 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007979
7980 // Treat an enum type as its underlying type.
7981 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7982 Ty = EnumTy->getDecl()->getIntegerType();
7983
7984 // Integer types smaller than a register are extended.
7985 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007986 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007987
7988 // Other non-aggregates go in registers.
7989 if (!isAggregateTypeForABI(Ty))
7990 return ABIArgInfo::getDirect();
7991
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007992 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7993 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7994 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007995 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007996
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007997 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007998 // Build a coercion type from the LLVM struct type.
7999 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8000 if (!StrTy)
8001 return ABIArgInfo::getDirect();
8002
8003 CoerceBuilder CB(getVMContext(), getDataLayout());
8004 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008005 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008006
8007 // Try to use the original type for coercion.
8008 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8009
8010 if (CB.InReg)
8011 return ABIArgInfo::getDirectInReg(CoerceTy);
8012 else
8013 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008014}
8015
John McCall7f416cc2015-09-08 08:05:57 +00008016Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8017 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008018 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8019 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8020 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8021 AI.setCoerceToType(ArgTy);
8022
John McCall7f416cc2015-09-08 08:05:57 +00008023 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008024
John McCall7f416cc2015-09-08 08:05:57 +00008025 CGBuilderTy &Builder = CGF.Builder;
8026 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8027 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8028
8029 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8030
8031 Address ArgAddr = Address::invalid();
8032 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008033 switch (AI.getKind()) {
8034 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008035 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008036 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008037 llvm_unreachable("Unsupported ABI kind for va_arg");
8038
John McCall7f416cc2015-09-08 08:05:57 +00008039 case ABIArgInfo::Extend: {
8040 Stride = SlotSize;
8041 CharUnits Offset = SlotSize - TypeInfo.first;
8042 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008043 break;
John McCall7f416cc2015-09-08 08:05:57 +00008044 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008045
John McCall7f416cc2015-09-08 08:05:57 +00008046 case ABIArgInfo::Direct: {
8047 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008048 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008049 ArgAddr = Addr;
8050 break;
John McCall7f416cc2015-09-08 08:05:57 +00008051 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008052
8053 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008054 Stride = SlotSize;
8055 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8056 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8057 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008058 break;
8059
8060 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008061 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008062 }
8063
8064 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008065 llvm::Value *NextPtr =
8066 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8067 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008068
John McCall7f416cc2015-09-08 08:05:57 +00008069 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008070}
8071
8072void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8073 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008074 for (auto &I : FI.arguments())
8075 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008076}
8077
8078namespace {
8079class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8080public:
8081 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8082 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008083
Craig Topper4f12f102014-03-12 06:41:41 +00008084 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008085 return 14;
8086 }
8087
8088 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008089 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008090};
8091} // end anonymous namespace
8092
Roman Divackyf02c9942014-02-24 18:46:27 +00008093bool
8094SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8095 llvm::Value *Address) const {
8096 // This is calculated from the LLVM and GCC tables and verified
8097 // against gcc output. AFAIK all ABIs use the same encoding.
8098
8099 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8100
8101 llvm::IntegerType *i8 = CGF.Int8Ty;
8102 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8103 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8104
8105 // 0-31: the 8-byte general-purpose registers
8106 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8107
8108 // 32-63: f0-31, the 4-byte floating-point registers
8109 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8110
8111 // Y = 64
8112 // PSR = 65
8113 // WIM = 66
8114 // TBR = 67
8115 // PC = 68
8116 // NPC = 69
8117 // FSR = 70
8118 // CSR = 71
8119 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008120
Roman Divackyf02c9942014-02-24 18:46:27 +00008121 // 72-87: d0-15, the 8-byte floating-point registers
8122 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8123
8124 return false;
8125}
8126
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008127
Robert Lytton0e076492013-08-13 09:43:10 +00008128//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008129// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008130//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008131
Robert Lytton0e076492013-08-13 09:43:10 +00008132namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008133
8134/// A SmallStringEnc instance is used to build up the TypeString by passing
8135/// it by reference between functions that append to it.
8136typedef llvm::SmallString<128> SmallStringEnc;
8137
8138/// TypeStringCache caches the meta encodings of Types.
8139///
8140/// The reason for caching TypeStrings is two fold:
8141/// 1. To cache a type's encoding for later uses;
8142/// 2. As a means to break recursive member type inclusion.
8143///
8144/// A cache Entry can have a Status of:
8145/// NonRecursive: The type encoding is not recursive;
8146/// Recursive: The type encoding is recursive;
8147/// Incomplete: An incomplete TypeString;
8148/// IncompleteUsed: An incomplete TypeString that has been used in a
8149/// Recursive type encoding.
8150///
8151/// A NonRecursive entry will have all of its sub-members expanded as fully
8152/// as possible. Whilst it may contain types which are recursive, the type
8153/// itself is not recursive and thus its encoding may be safely used whenever
8154/// the type is encountered.
8155///
8156/// A Recursive entry will have all of its sub-members expanded as fully as
8157/// possible. The type itself is recursive and it may contain other types which
8158/// are recursive. The Recursive encoding must not be used during the expansion
8159/// of a recursive type's recursive branch. For simplicity the code uses
8160/// IncompleteCount to reject all usage of Recursive encodings for member types.
8161///
8162/// An Incomplete entry is always a RecordType and only encodes its
8163/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8164/// are placed into the cache during type expansion as a means to identify and
8165/// handle recursive inclusion of types as sub-members. If there is recursion
8166/// the entry becomes IncompleteUsed.
8167///
8168/// During the expansion of a RecordType's members:
8169///
8170/// If the cache contains a NonRecursive encoding for the member type, the
8171/// cached encoding is used;
8172///
8173/// If the cache contains a Recursive encoding for the member type, the
8174/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8175///
8176/// If the member is a RecordType, an Incomplete encoding is placed into the
8177/// cache to break potential recursive inclusion of itself as a sub-member;
8178///
8179/// Once a member RecordType has been expanded, its temporary incomplete
8180/// entry is removed from the cache. If a Recursive encoding was swapped out
8181/// it is swapped back in;
8182///
8183/// If an incomplete entry is used to expand a sub-member, the incomplete
8184/// entry is marked as IncompleteUsed. The cache keeps count of how many
8185/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8186///
8187/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8188/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8189/// Else the member is part of a recursive type and thus the recursion has
8190/// been exited too soon for the encoding to be correct for the member.
8191///
8192class TypeStringCache {
8193 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8194 struct Entry {
8195 std::string Str; // The encoded TypeString for the type.
8196 enum Status State; // Information about the encoding in 'Str'.
8197 std::string Swapped; // A temporary place holder for a Recursive encoding
8198 // during the expansion of RecordType's members.
8199 };
8200 std::map<const IdentifierInfo *, struct Entry> Map;
8201 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8202 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8203public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008204 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008205 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8206 bool removeIncomplete(const IdentifierInfo *ID);
8207 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8208 bool IsRecursive);
8209 StringRef lookupStr(const IdentifierInfo *ID);
8210};
8211
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008212/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008213/// FieldEncoding is a helper for this ordering process.
8214class FieldEncoding {
8215 bool HasName;
8216 std::string Enc;
8217public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008218 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008219 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008220 bool operator<(const FieldEncoding &rhs) const {
8221 if (HasName != rhs.HasName) return HasName;
8222 return Enc < rhs.Enc;
8223 }
8224};
8225
Robert Lytton7d1db152013-08-19 09:46:39 +00008226class XCoreABIInfo : public DefaultABIInfo {
8227public:
8228 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008229 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8230 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008231};
8232
Robert Lyttond21e2d72014-03-03 13:45:29 +00008233class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008234 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008235public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008236 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008237 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008238 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8239 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008240};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008241
Robert Lytton2d196952013-10-11 10:29:34 +00008242} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008243
James Y Knight29b5f082016-02-24 02:59:33 +00008244// TODO: this implementation is likely now redundant with the default
8245// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008246Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8247 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008248 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008249
Robert Lytton2d196952013-10-11 10:29:34 +00008250 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008251 CharUnits SlotSize = CharUnits::fromQuantity(4);
8252 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008253
Robert Lytton2d196952013-10-11 10:29:34 +00008254 // Handle the argument.
8255 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008256 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008257 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8258 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8259 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008260 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008261
8262 Address Val = Address::invalid();
8263 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008264 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008265 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008266 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008267 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008268 llvm_unreachable("Unsupported ABI kind for va_arg");
8269 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008270 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8271 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008272 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008273 case ABIArgInfo::Extend:
8274 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008275 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8276 ArgSize = CharUnits::fromQuantity(
8277 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008278 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008279 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008280 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008281 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8282 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8283 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008284 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008285 }
Robert Lytton2d196952013-10-11 10:29:34 +00008286
8287 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008288 if (!ArgSize.isZero()) {
8289 llvm::Value *APN =
8290 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8291 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008292 }
John McCall7f416cc2015-09-08 08:05:57 +00008293
Robert Lytton2d196952013-10-11 10:29:34 +00008294 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008295}
Robert Lytton0e076492013-08-13 09:43:10 +00008296
Robert Lytton844aeeb2014-05-02 09:33:20 +00008297/// During the expansion of a RecordType, an incomplete TypeString is placed
8298/// into the cache as a means to identify and break recursion.
8299/// If there is a Recursive encoding in the cache, it is swapped out and will
8300/// be reinserted by removeIncomplete().
8301/// All other types of encoding should have been used rather than arriving here.
8302void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8303 std::string StubEnc) {
8304 if (!ID)
8305 return;
8306 Entry &E = Map[ID];
8307 assert( (E.Str.empty() || E.State == Recursive) &&
8308 "Incorrectly use of addIncomplete");
8309 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8310 E.Swapped.swap(E.Str); // swap out the Recursive
8311 E.Str.swap(StubEnc);
8312 E.State = Incomplete;
8313 ++IncompleteCount;
8314}
8315
8316/// Once the RecordType has been expanded, the temporary incomplete TypeString
8317/// must be removed from the cache.
8318/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8319/// Returns true if the RecordType was defined recursively.
8320bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8321 if (!ID)
8322 return false;
8323 auto I = Map.find(ID);
8324 assert(I != Map.end() && "Entry not present");
8325 Entry &E = I->second;
8326 assert( (E.State == Incomplete ||
8327 E.State == IncompleteUsed) &&
8328 "Entry must be an incomplete type");
8329 bool IsRecursive = false;
8330 if (E.State == IncompleteUsed) {
8331 // We made use of our Incomplete encoding, thus we are recursive.
8332 IsRecursive = true;
8333 --IncompleteUsedCount;
8334 }
8335 if (E.Swapped.empty())
8336 Map.erase(I);
8337 else {
8338 // Swap the Recursive back.
8339 E.Swapped.swap(E.Str);
8340 E.Swapped.clear();
8341 E.State = Recursive;
8342 }
8343 --IncompleteCount;
8344 return IsRecursive;
8345}
8346
8347/// Add the encoded TypeString to the cache only if it is NonRecursive or
8348/// Recursive (viz: all sub-members were expanded as fully as possible).
8349void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8350 bool IsRecursive) {
8351 if (!ID || IncompleteUsedCount)
8352 return; // No key or it is is an incomplete sub-type so don't add.
8353 Entry &E = Map[ID];
8354 if (IsRecursive && !E.Str.empty()) {
8355 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8356 "This is not the same Recursive entry");
8357 // The parent container was not recursive after all, so we could have used
8358 // this Recursive sub-member entry after all, but we assumed the worse when
8359 // we started viz: IncompleteCount!=0.
8360 return;
8361 }
8362 assert(E.Str.empty() && "Entry already present");
8363 E.Str = Str.str();
8364 E.State = IsRecursive? Recursive : NonRecursive;
8365}
8366
8367/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8368/// are recursively expanding a type (IncompleteCount != 0) and the cached
8369/// encoding is Recursive, return an empty StringRef.
8370StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8371 if (!ID)
8372 return StringRef(); // We have no key.
8373 auto I = Map.find(ID);
8374 if (I == Map.end())
8375 return StringRef(); // We have no encoding.
8376 Entry &E = I->second;
8377 if (E.State == Recursive && IncompleteCount)
8378 return StringRef(); // We don't use Recursive encodings for member types.
8379
8380 if (E.State == Incomplete) {
8381 // The incomplete type is being used to break out of recursion.
8382 E.State = IncompleteUsed;
8383 ++IncompleteUsedCount;
8384 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008385 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008386}
8387
8388/// The XCore ABI includes a type information section that communicates symbol
8389/// type information to the linker. The linker uses this information to verify
8390/// safety/correctness of things such as array bound and pointers et al.
8391/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8392/// This type information (TypeString) is emitted into meta data for all global
8393/// symbols: definitions, declarations, functions & variables.
8394///
8395/// The TypeString carries type, qualifier, name, size & value details.
8396/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008397/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008398/// The output is tested by test/CodeGen/xcore-stringtype.c.
8399///
8400static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8401 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8402
8403/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8404void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8405 CodeGen::CodeGenModule &CGM) const {
8406 SmallStringEnc Enc;
8407 if (getTypeString(Enc, D, CGM, TSC)) {
8408 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008409 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8410 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008411 llvm::NamedMDNode *MD =
8412 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8413 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8414 }
8415}
8416
Xiuli Pan972bea82016-03-24 03:57:17 +00008417//===----------------------------------------------------------------------===//
8418// SPIR ABI Implementation
8419//===----------------------------------------------------------------------===//
8420
8421namespace {
8422class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8423public:
8424 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8425 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008426 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008427};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008428
Xiuli Pan972bea82016-03-24 03:57:17 +00008429} // End anonymous namespace.
8430
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008431namespace clang {
8432namespace CodeGen {
8433void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8434 DefaultABIInfo SPIRABI(CGM.getTypes());
8435 SPIRABI.computeInfo(FI);
8436}
8437}
8438}
8439
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008440unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8441 return llvm::CallingConv::SPIR_KERNEL;
8442}
8443
Robert Lytton844aeeb2014-05-02 09:33:20 +00008444static bool appendType(SmallStringEnc &Enc, QualType QType,
8445 const CodeGen::CodeGenModule &CGM,
8446 TypeStringCache &TSC);
8447
8448/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008449/// Builds a SmallVector containing the encoded field types in declaration
8450/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008451static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8452 const RecordDecl *RD,
8453 const CodeGen::CodeGenModule &CGM,
8454 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008455 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008456 SmallStringEnc Enc;
8457 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008458 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008459 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008460 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008461 Enc += "b(";
8462 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008463 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008464 Enc += ':';
8465 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008466 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008467 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008468 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008469 Enc += ')';
8470 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008471 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008472 }
8473 return true;
8474}
8475
8476/// Appends structure and union types to Enc and adds encoding to cache.
8477/// Recursively calls appendType (via extractFieldType) for each field.
8478/// Union types have their fields ordered according to the ABI.
8479static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8480 const CodeGen::CodeGenModule &CGM,
8481 TypeStringCache &TSC, const IdentifierInfo *ID) {
8482 // Append the cached TypeString if we have one.
8483 StringRef TypeString = TSC.lookupStr(ID);
8484 if (!TypeString.empty()) {
8485 Enc += TypeString;
8486 return true;
8487 }
8488
8489 // Start to emit an incomplete TypeString.
8490 size_t Start = Enc.size();
8491 Enc += (RT->isUnionType()? 'u' : 's');
8492 Enc += '(';
8493 if (ID)
8494 Enc += ID->getName();
8495 Enc += "){";
8496
8497 // We collect all encoded fields and order as necessary.
8498 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008499 const RecordDecl *RD = RT->getDecl()->getDefinition();
8500 if (RD && !RD->field_empty()) {
8501 // An incomplete TypeString stub is placed in the cache for this RecordType
8502 // so that recursive calls to this RecordType will use it whilst building a
8503 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008504 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008505 std::string StubEnc(Enc.substr(Start).str());
8506 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8507 TSC.addIncomplete(ID, std::move(StubEnc));
8508 if (!extractFieldType(FE, RD, CGM, TSC)) {
8509 (void) TSC.removeIncomplete(ID);
8510 return false;
8511 }
8512 IsRecursive = TSC.removeIncomplete(ID);
8513 // The ABI requires unions to be sorted but not structures.
8514 // See FieldEncoding::operator< for sort algorithm.
8515 if (RT->isUnionType())
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00008516 llvm::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008517 // We can now complete the TypeString.
8518 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008519 for (unsigned I = 0; I != E; ++I) {
8520 if (I)
8521 Enc += ',';
8522 Enc += FE[I].str();
8523 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008524 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008525 Enc += '}';
8526 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8527 return true;
8528}
8529
8530/// Appends enum types to Enc and adds the encoding to the cache.
8531static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8532 TypeStringCache &TSC,
8533 const IdentifierInfo *ID) {
8534 // Append the cached TypeString if we have one.
8535 StringRef TypeString = TSC.lookupStr(ID);
8536 if (!TypeString.empty()) {
8537 Enc += TypeString;
8538 return true;
8539 }
8540
8541 size_t Start = Enc.size();
8542 Enc += "e(";
8543 if (ID)
8544 Enc += ID->getName();
8545 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008546
8547 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008548 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008549 SmallVector<FieldEncoding, 16> FE;
8550 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8551 ++I) {
8552 SmallStringEnc EnumEnc;
8553 EnumEnc += "m(";
8554 EnumEnc += I->getName();
8555 EnumEnc += "){";
8556 I->getInitVal().toString(EnumEnc);
8557 EnumEnc += '}';
8558 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8559 }
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00008560 llvm::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008561 unsigned E = FE.size();
8562 for (unsigned I = 0; I != E; ++I) {
8563 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008564 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008565 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008566 }
8567 }
8568 Enc += '}';
8569 TSC.addIfComplete(ID, Enc.substr(Start), false);
8570 return true;
8571}
8572
8573/// Appends type's qualifier to Enc.
8574/// This is done prior to appending the type's encoding.
8575static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8576 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008577 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008578 int Lookup = 0;
8579 if (QT.isConstQualified())
8580 Lookup += 1<<0;
8581 if (QT.isRestrictQualified())
8582 Lookup += 1<<1;
8583 if (QT.isVolatileQualified())
8584 Lookup += 1<<2;
8585 Enc += Table[Lookup];
8586}
8587
8588/// Appends built-in types to Enc.
8589static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8590 const char *EncType;
8591 switch (BT->getKind()) {
8592 case BuiltinType::Void:
8593 EncType = "0";
8594 break;
8595 case BuiltinType::Bool:
8596 EncType = "b";
8597 break;
8598 case BuiltinType::Char_U:
8599 EncType = "uc";
8600 break;
8601 case BuiltinType::UChar:
8602 EncType = "uc";
8603 break;
8604 case BuiltinType::SChar:
8605 EncType = "sc";
8606 break;
8607 case BuiltinType::UShort:
8608 EncType = "us";
8609 break;
8610 case BuiltinType::Short:
8611 EncType = "ss";
8612 break;
8613 case BuiltinType::UInt:
8614 EncType = "ui";
8615 break;
8616 case BuiltinType::Int:
8617 EncType = "si";
8618 break;
8619 case BuiltinType::ULong:
8620 EncType = "ul";
8621 break;
8622 case BuiltinType::Long:
8623 EncType = "sl";
8624 break;
8625 case BuiltinType::ULongLong:
8626 EncType = "ull";
8627 break;
8628 case BuiltinType::LongLong:
8629 EncType = "sll";
8630 break;
8631 case BuiltinType::Float:
8632 EncType = "ft";
8633 break;
8634 case BuiltinType::Double:
8635 EncType = "d";
8636 break;
8637 case BuiltinType::LongDouble:
8638 EncType = "ld";
8639 break;
8640 default:
8641 return false;
8642 }
8643 Enc += EncType;
8644 return true;
8645}
8646
8647/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8648static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8649 const CodeGen::CodeGenModule &CGM,
8650 TypeStringCache &TSC) {
8651 Enc += "p(";
8652 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8653 return false;
8654 Enc += ')';
8655 return true;
8656}
8657
8658/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008659static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8660 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008661 const CodeGen::CodeGenModule &CGM,
8662 TypeStringCache &TSC, StringRef NoSizeEnc) {
8663 if (AT->getSizeModifier() != ArrayType::Normal)
8664 return false;
8665 Enc += "a(";
8666 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8667 CAT->getSize().toStringUnsigned(Enc);
8668 else
8669 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8670 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008671 // The Qualifiers should be attached to the type rather than the array.
8672 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008673 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8674 return false;
8675 Enc += ')';
8676 return true;
8677}
8678
8679/// Appends a function encoding to Enc, calling appendType for the return type
8680/// and the arguments.
8681static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8682 const CodeGen::CodeGenModule &CGM,
8683 TypeStringCache &TSC) {
8684 Enc += "f{";
8685 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8686 return false;
8687 Enc += "}(";
8688 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8689 // N.B. we are only interested in the adjusted param types.
8690 auto I = FPT->param_type_begin();
8691 auto E = FPT->param_type_end();
8692 if (I != E) {
8693 do {
8694 if (!appendType(Enc, *I, CGM, TSC))
8695 return false;
8696 ++I;
8697 if (I != E)
8698 Enc += ',';
8699 } while (I != E);
8700 if (FPT->isVariadic())
8701 Enc += ",va";
8702 } else {
8703 if (FPT->isVariadic())
8704 Enc += "va";
8705 else
8706 Enc += '0';
8707 }
8708 }
8709 Enc += ')';
8710 return true;
8711}
8712
8713/// Handles the type's qualifier before dispatching a call to handle specific
8714/// type encodings.
8715static bool appendType(SmallStringEnc &Enc, QualType QType,
8716 const CodeGen::CodeGenModule &CGM,
8717 TypeStringCache &TSC) {
8718
8719 QualType QT = QType.getCanonicalType();
8720
Robert Lytton6adb20f2014-06-05 09:06:21 +00008721 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8722 // The Qualifiers should be attached to the type rather than the array.
8723 // Thus we don't call appendQualifier() here.
8724 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8725
Robert Lytton844aeeb2014-05-02 09:33:20 +00008726 appendQualifier(Enc, QT);
8727
8728 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8729 return appendBuiltinType(Enc, BT);
8730
Robert Lytton844aeeb2014-05-02 09:33:20 +00008731 if (const PointerType *PT = QT->getAs<PointerType>())
8732 return appendPointerType(Enc, PT, CGM, TSC);
8733
8734 if (const EnumType *ET = QT->getAs<EnumType>())
8735 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8736
8737 if (const RecordType *RT = QT->getAsStructureType())
8738 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8739
8740 if (const RecordType *RT = QT->getAsUnionType())
8741 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8742
8743 if (const FunctionType *FT = QT->getAs<FunctionType>())
8744 return appendFunctionType(Enc, FT, CGM, TSC);
8745
8746 return false;
8747}
8748
8749static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8750 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8751 if (!D)
8752 return false;
8753
8754 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8755 if (FD->getLanguageLinkage() != CLanguageLinkage)
8756 return false;
8757 return appendType(Enc, FD->getType(), CGM, TSC);
8758 }
8759
8760 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8761 if (VD->getLanguageLinkage() != CLanguageLinkage)
8762 return false;
8763 QualType QT = VD->getType().getCanonicalType();
8764 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8765 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008766 // The Qualifiers should be attached to the type rather than the array.
8767 // Thus we don't call appendQualifier() here.
8768 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008769 }
8770 return appendType(Enc, QT, CGM, TSC);
8771 }
8772 return false;
8773}
8774
Alex Bradbury8cbdd482018-01-15 17:54:52 +00008775//===----------------------------------------------------------------------===//
8776// RISCV ABI Implementation
8777//===----------------------------------------------------------------------===//
8778
8779namespace {
8780class RISCVABIInfo : public DefaultABIInfo {
8781private:
8782 unsigned XLen; // Size of the integer ('x') registers in bits.
8783 static const int NumArgGPRs = 8;
8784
8785public:
8786 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8787 : DefaultABIInfo(CGT), XLen(XLen) {}
8788
8789 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
8790 // non-virtual, but computeInfo is virtual, so we overload it.
8791 void computeInfo(CGFunctionInfo &FI) const override;
8792
8793 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
8794 int &ArgGPRsLeft) const;
8795 ABIArgInfo classifyReturnType(QualType RetTy) const;
8796
8797 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8798 QualType Ty) const override;
8799
8800 ABIArgInfo extendType(QualType Ty) const;
8801};
8802} // end anonymous namespace
8803
8804void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
8805 QualType RetTy = FI.getReturnType();
8806 if (!getCXXABI().classifyReturnType(FI))
8807 FI.getReturnInfo() = classifyReturnType(RetTy);
8808
8809 // IsRetIndirect is true if classifyArgumentType indicated the value should
8810 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
8811 // is passed direct in LLVM IR, relying on the backend lowering code to
8812 // rewrite the argument list and pass indirectly on RV32.
8813 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
8814 getContext().getTypeSize(RetTy) > (2 * XLen);
8815
8816 // We must track the number of GPRs used in order to conform to the RISC-V
8817 // ABI, as integer scalars passed in registers should have signext/zeroext
8818 // when promoted, but are anyext if passed on the stack. As GPR usage is
8819 // different for variadic arguments, we must also track whether we are
8820 // examining a vararg or not.
8821 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
8822 int NumFixedArgs = FI.getNumRequiredArgs();
8823
8824 int ArgNum = 0;
8825 for (auto &ArgInfo : FI.arguments()) {
8826 bool IsFixed = ArgNum < NumFixedArgs;
8827 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
8828 ArgNum++;
8829 }
8830}
8831
8832ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
8833 int &ArgGPRsLeft) const {
8834 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
8835 Ty = useFirstFieldIfTransparentUnion(Ty);
8836
8837 // Structures with either a non-trivial destructor or a non-trivial
8838 // copy constructor are always passed indirectly.
8839 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8840 if (ArgGPRsLeft)
8841 ArgGPRsLeft -= 1;
8842 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
8843 CGCXXABI::RAA_DirectInMemory);
8844 }
8845
8846 // Ignore empty structs/unions.
8847 if (isEmptyRecord(getContext(), Ty, true))
8848 return ABIArgInfo::getIgnore();
8849
8850 uint64_t Size = getContext().getTypeSize(Ty);
8851 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
8852 bool MustUseStack = false;
8853 // Determine the number of GPRs needed to pass the current argument
8854 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
8855 // register pairs, so may consume 3 registers.
8856 int NeededArgGPRs = 1;
8857 if (!IsFixed && NeededAlign == 2 * XLen)
8858 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
8859 else if (Size > XLen && Size <= 2 * XLen)
8860 NeededArgGPRs = 2;
8861
8862 if (NeededArgGPRs > ArgGPRsLeft) {
8863 MustUseStack = true;
8864 NeededArgGPRs = ArgGPRsLeft;
8865 }
8866
8867 ArgGPRsLeft -= NeededArgGPRs;
8868
8869 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
8870 // Treat an enum type as its underlying type.
8871 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8872 Ty = EnumTy->getDecl()->getIntegerType();
8873
8874 // All integral types are promoted to XLen width, unless passed on the
8875 // stack.
8876 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
8877 return extendType(Ty);
8878 }
8879
8880 return ABIArgInfo::getDirect();
8881 }
8882
8883 // Aggregates which are <= 2*XLen will be passed in registers if possible,
8884 // so coerce to integers.
8885 if (Size <= 2 * XLen) {
8886 unsigned Alignment = getContext().getTypeAlign(Ty);
8887
8888 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
8889 // required, and a 2-element XLen array if only XLen alignment is required.
8890 if (Size <= XLen) {
8891 return ABIArgInfo::getDirect(
8892 llvm::IntegerType::get(getVMContext(), XLen));
8893 } else if (Alignment == 2 * XLen) {
8894 return ABIArgInfo::getDirect(
8895 llvm::IntegerType::get(getVMContext(), 2 * XLen));
8896 } else {
8897 return ABIArgInfo::getDirect(llvm::ArrayType::get(
8898 llvm::IntegerType::get(getVMContext(), XLen), 2));
8899 }
8900 }
8901 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8902}
8903
8904ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
8905 if (RetTy->isVoidType())
8906 return ABIArgInfo::getIgnore();
8907
8908 int ArgGPRsLeft = 2;
8909
8910 // The rules for return and argument types are the same, so defer to
8911 // classifyArgumentType.
8912 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
8913}
8914
8915Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8916 QualType Ty) const {
8917 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
8918
8919 // Empty records are ignored for parameter passing purposes.
8920 if (isEmptyRecord(getContext(), Ty, true)) {
8921 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
8922 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
8923 return Addr;
8924 }
8925
8926 std::pair<CharUnits, CharUnits> SizeAndAlign =
8927 getContext().getTypeInfoInChars(Ty);
8928
8929 // Arguments bigger than 2*Xlen bytes are passed indirectly.
8930 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
8931
8932 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
8933 SlotSize, /*AllowHigherAlign=*/true);
8934}
8935
8936ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
8937 int TySize = getContext().getTypeSize(Ty);
8938 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
8939 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8940 return ABIArgInfo::getSignExtend(Ty);
8941 return ABIArgInfo::getExtend(Ty);
8942}
8943
8944namespace {
8945class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
8946public:
8947 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8948 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
8949};
8950} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00008951
Robert Lytton0e076492013-08-13 09:43:10 +00008952//===----------------------------------------------------------------------===//
8953// Driver code
8954//===----------------------------------------------------------------------===//
8955
Rafael Espindola9f834732014-09-19 01:54:22 +00008956bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008957 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008958}
8959
Chris Lattner2b037972010-07-29 02:01:43 +00008960const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008961 if (TheTargetCodeGenInfo)
8962 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008963
Reid Kleckner9305fd12016-04-13 23:37:17 +00008964 // Helper to set the unique_ptr while still keeping the return value.
8965 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8966 this->TheTargetCodeGenInfo.reset(P);
8967 return *P;
8968 };
8969
John McCallc8e01702013-04-16 22:48:15 +00008970 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008971 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008972 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008973 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008974
Derek Schuff09338a22012-09-06 17:37:28 +00008975 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008976 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008977 case llvm::Triple::mips:
8978 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008979 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008980 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8981 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008982
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008983 case llvm::Triple::mips64:
8984 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008985 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008986
Dylan McKaye8232d72017-02-08 05:09:26 +00008987 case llvm::Triple::avr:
8988 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8989
Tim Northover25e8a672014-05-24 12:51:25 +00008990 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008991 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008992 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008993 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008994 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008995 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008996 return SetCGInfo(
8997 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008998
Reid Kleckner9305fd12016-04-13 23:37:17 +00008999 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009000 }
9001
Dan Gohmanc2853072015-09-03 22:51:53 +00009002 case llvm::Triple::wasm32:
9003 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009004 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009005
Daniel Dunbard59655c2009-09-12 00:59:49 +00009006 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009007 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009008 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009009 case llvm::Triple::thumbeb: {
9010 if (Triple.getOS() == llvm::Triple::Win32) {
9011 return SetCGInfo(
9012 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009013 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009014
Reid Kleckner9305fd12016-04-13 23:37:17 +00009015 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9016 StringRef ABIStr = getTarget().getABI();
9017 if (ABIStr == "apcs-gnu")
9018 Kind = ARMABIInfo::APCS;
9019 else if (ABIStr == "aapcs16")
9020 Kind = ARMABIInfo::AAPCS16_VFP;
9021 else if (CodeGenOpts.FloatABI == "hard" ||
9022 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009023 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009024 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009025 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009026 Kind = ARMABIInfo::AAPCS_VFP;
9027
9028 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9029 }
9030
John McCallea8d8bb2010-03-11 00:10:12 +00009031 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009032 return SetCGInfo(
9033 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009034 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009035 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009036 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009037 if (getTarget().getABI() == "elfv2")
9038 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009039 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009040 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009041
Hal Finkel415c2a32016-10-02 02:10:45 +00009042 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9043 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009044 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009045 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009046 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009047 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009048 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009049 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009050 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009051 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009052 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009053
Hal Finkel415c2a32016-10-02 02:10:45 +00009054 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9055 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009056 }
John McCallea8d8bb2010-03-11 00:10:12 +00009057
Peter Collingbournec947aae2012-05-20 23:28:41 +00009058 case llvm::Triple::nvptx:
9059 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009060 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009061
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009062 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009063 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009064
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009065 case llvm::Triple::riscv32:
9066 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9067 case llvm::Triple::riscv64:
9068 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9069
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009070 case llvm::Triple::systemz: {
9071 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009072 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009073 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009074
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009075 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009076 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009077 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009078
Eli Friedman33465822011-07-08 23:31:17 +00009079 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009080 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009081 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009082 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009083 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009084
John McCall1fe2a8c2013-06-18 02:46:29 +00009085 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009086 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9087 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9088 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009089 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009090 return SetCGInfo(new X86_32TargetCodeGenInfo(
9091 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9092 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9093 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009094 }
Eli Friedman33465822011-07-08 23:31:17 +00009095 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009096
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009097 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009098 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009099 X86AVXABILevel AVXLevel =
9100 (ABI == "avx512"
9101 ? X86AVXABILevel::AVX512
9102 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009103
Chris Lattner04dc9572010-08-31 16:44:54 +00009104 switch (Triple.getOS()) {
9105 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009106 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00009107 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009108 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009109 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009110 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009111 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009112 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009113 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009114 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009115 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009116 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009117 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009118 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009119 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009120 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009121 case llvm::Triple::sparc:
9122 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009123 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009124 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009125 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009126 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009127 case llvm::Triple::spir:
9128 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009129 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009130 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009131}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009132
9133/// Create an OpenCL kernel for an enqueued block.
9134///
9135/// The kernel has the same function type as the block invoke function. Its
9136/// name is the name of the block invoke function postfixed with "_kernel".
9137/// It simply calls the block invoke function then returns.
9138llvm::Function *
9139TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9140 llvm::Function *Invoke,
9141 llvm::Value *BlockLiteral) const {
9142 auto *InvokeFT = Invoke->getFunctionType();
9143 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9144 for (auto &P : InvokeFT->params())
9145 ArgTys.push_back(P);
9146 auto &C = CGF.getLLVMContext();
9147 std::string Name = Invoke->getName().str() + "_kernel";
9148 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9149 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9150 &CGF.CGM.getModule());
9151 auto IP = CGF.Builder.saveIP();
9152 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9153 auto &Builder = CGF.Builder;
9154 Builder.SetInsertPoint(BB);
9155 llvm::SmallVector<llvm::Value *, 2> Args;
9156 for (auto &A : F->args())
9157 Args.push_back(&A);
9158 Builder.CreateCall(Invoke, Args);
9159 Builder.CreateRetVoid();
9160 Builder.restoreIP(IP);
9161 return F;
9162}
9163
9164/// Create an OpenCL kernel for an enqueued block.
9165///
9166/// The type of the first argument (the block literal) is the struct type
9167/// of the block literal instead of a pointer type. The first argument
9168/// (block literal) is passed directly by value to the kernel. The kernel
9169/// allocates the same type of struct on stack and stores the block literal
9170/// to it and passes its pointer to the block invoke function. The kernel
9171/// has "enqueued-block" function attribute and kernel argument metadata.
9172llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9173 CodeGenFunction &CGF, llvm::Function *Invoke,
9174 llvm::Value *BlockLiteral) const {
9175 auto &Builder = CGF.Builder;
9176 auto &C = CGF.getLLVMContext();
9177
9178 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9179 auto *InvokeFT = Invoke->getFunctionType();
9180 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9181 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9182 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9183 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9184 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9185 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9186 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9187
9188 ArgTys.push_back(BlockTy);
9189 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9190 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9191 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9192 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9193 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9194 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9195 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9196 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009197 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9198 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9199 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9200 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9201 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9202 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009203 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009204 }
9205 std::string Name = Invoke->getName().str() + "_kernel";
9206 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9207 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9208 &CGF.CGM.getModule());
9209 F->addFnAttr("enqueued-block");
9210 auto IP = CGF.Builder.saveIP();
9211 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9212 Builder.SetInsertPoint(BB);
9213 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9214 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9215 BlockPtr->setAlignment(BlockAlign);
9216 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9217 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9218 llvm::SmallVector<llvm::Value *, 2> Args;
9219 Args.push_back(Cast);
9220 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9221 Args.push_back(I);
9222 Builder.CreateCall(Invoke, Args);
9223 Builder.CreateRetVoid();
9224 Builder.restoreIP(IP);
9225
9226 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9227 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9228 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9229 F->setMetadata("kernel_arg_base_type",
9230 llvm::MDNode::get(C, ArgBaseTypeNames));
9231 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9232 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9233 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9234
9235 return F;
9236}