blob: fe87f544ed6b1a1a1916f56e135da1fbf6262e02 [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 {
Fangrui Song6907ce22018-07-30 19:24:48 +0000308 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000309 }
310
311 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000312 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000313 llvm::Value *NextPtr =
314 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
315 "argp.next");
316 CGF.Builder.CreateStore(NextPtr, VAListAddr);
317
318 // If the argument is smaller than a slot, and this is a big-endian
319 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000320 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
321 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000322 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
323 }
324
325 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
326 return Addr;
327}
328
329/// Emit va_arg for a platform using the common void* representation,
330/// where arguments are simply emitted in an array of slots on the stack.
331///
332/// \param IsIndirect - Values of this type are passed indirectly.
333/// \param ValueInfo - The size and alignment of this type, generally
334/// computed with getContext().getTypeInfoInChars(ValueTy).
335/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
336/// Each argument will be allocated to a multiple of this number of
337/// slots, and all the slots will be aligned to this value.
338/// \param AllowHigherAlign - The slot alignment is not a cap;
339/// an argument type with an alignment greater than the slot size
340/// will be emitted on a higher-alignment address, potentially
341/// leaving one or more empty slots behind as padding.
342static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
343 QualType ValueTy, bool IsIndirect,
344 std::pair<CharUnits, CharUnits> ValueInfo,
345 CharUnits SlotSizeAndAlign,
346 bool AllowHigherAlign) {
347 // The size and alignment of the value that was passed directly.
348 CharUnits DirectSize, DirectAlign;
349 if (IsIndirect) {
350 DirectSize = CGF.getPointerSize();
351 DirectAlign = CGF.getPointerAlign();
352 } else {
353 DirectSize = ValueInfo.first;
354 DirectAlign = ValueInfo.second;
355 }
356
357 // Cast the address we've calculated to the right type.
358 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
359 if (IsIndirect)
360 DirectTy = DirectTy->getPointerTo(0);
361
362 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
363 DirectSize, DirectAlign,
364 SlotSizeAndAlign,
365 AllowHigherAlign);
366
367 if (IsIndirect) {
368 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
369 }
370
371 return Addr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000372
John McCall7f416cc2015-09-08 08:05:57 +0000373}
374
375static Address emitMergePHI(CodeGenFunction &CGF,
376 Address Addr1, llvm::BasicBlock *Block1,
377 Address Addr2, llvm::BasicBlock *Block2,
378 const llvm::Twine &Name = "") {
379 assert(Addr1.getType() == Addr2.getType());
380 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
381 PHI->addIncoming(Addr1.getPointer(), Block1);
382 PHI->addIncoming(Addr2.getPointer(), Block2);
383 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
384 return Address(PHI, Align);
385}
386
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000387TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
388
John McCall3480ef22011-08-30 01:42:09 +0000389// If someone can figure out a general rule for this, that would be great.
390// It's probably just doomed to be platform-dependent, though.
391unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
392 // Verified for:
393 // x86-64 FreeBSD, Linux, Darwin
394 // x86-32 FreeBSD, Linux, Darwin
395 // PowerPC Linux, Darwin
396 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000397 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000398 return 32;
399}
400
John McCalla729c622012-02-17 03:33:10 +0000401bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
402 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000403 // The following conventions are known to require this to be false:
404 // x86_stdcall
405 // MIPS
406 // For everything else, we just prefer false unless we opt out.
407 return false;
408}
409
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000410void
411TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
412 llvm::SmallString<24> &Opt) const {
413 // This assumes the user is passing a library name like "rt" instead of a
414 // filename like "librt.a/so", and that they don't care whether it's static or
415 // dynamic.
416 Opt = "-l";
417 Opt += Lib;
418}
419
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000420unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000421 // OpenCL kernels are called via an explicit runtime API with arguments
422 // set with clSetKernelArg(), not as normal sub-functions.
423 // Return SPIR_KERNEL by default as the kernel calling convention to
424 // ensure the fingerprint is fixed such way that each OpenCL argument
425 // gets one matching argument in the produced kernel function argument
426 // list to enable feasible implementation of clSetKernelArg() with
427 // aggregates etc. In case we would use the default C calling conv here,
428 // clSetKernelArg() might break depending on the target-specific
429 // conventions; different targets might split structs passed as values
430 // to multiple function arguments etc.
431 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000432}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000433
Yaxun Liu402804b2016-12-15 08:09:08 +0000434llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
435 llvm::PointerType *T, QualType QT) const {
436 return llvm::ConstantPointerNull::get(T);
437}
438
Alexander Richardson6d989432017-10-15 18:48:14 +0000439LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
440 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000441 assert(!CGM.getLangOpts().OpenCL &&
442 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
443 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000444 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000445}
446
Yaxun Liu402804b2016-12-15 08:09:08 +0000447llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000448 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
449 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000450 // Since target may map different address spaces in AST to the same address
451 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000452 if (auto *C = dyn_cast<llvm::Constant>(Src))
453 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000454 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000455}
456
Yaxun Liucbf647c2017-07-08 13:24:52 +0000457llvm::Constant *
458TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000459 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 llvm::Type *DestTy) const {
461 // Since target may map different address spaces in AST to the same address
462 // space, an address space conversion may end up as a bitcast.
463 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
464}
465
Yaxun Liu39195062017-08-04 18:16:31 +0000466llvm::SyncScope::ID
467TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
468 return C.getOrInsertSyncScopeID(""); /* default sync scope */
469}
470
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000472
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000473/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000474/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
476 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000477 if (FD->isUnnamedBitfield())
478 return true;
479
480 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000481
Eli Friedman0b3f2012011-11-18 03:47:20 +0000482 // Constant arrays of empty records count as empty, strip them off.
483 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000484 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000485 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
486 if (AT->getSize() == 0)
487 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000488 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000489 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000490
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000491 const RecordType *RT = FT->getAs<RecordType>();
492 if (!RT)
493 return false;
494
495 // C++ record fields are never empty, at least in the Itanium ABI.
496 //
497 // FIXME: We should use a predicate for whether this behavior is true in the
498 // current ABI.
499 if (isa<CXXRecordDecl>(RT->getDecl()))
500 return false;
501
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000502 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000503}
504
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000505/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506/// fields. Note that a structure with a flexible array member is not
507/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000508static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000509 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000511 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000512 const RecordDecl *RD = RT->getDecl();
513 if (RD->hasFlexibleArrayMember())
514 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000515
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000516 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000517 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000518 for (const auto &I : CXXRD->bases())
519 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000520 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000521
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000522 for (const auto *I : RD->fields())
523 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000524 return false;
525 return true;
526}
527
528/// isSingleElementStruct - Determine if a structure is a "single
529/// element struct", i.e. it has exactly one non-empty field or
530/// exactly one field which is itself a single element
531/// struct. Structures with flexible array members are never
532/// considered single element structs.
533///
534/// \return The field declaration for the single non-empty field, if
535/// it exists.
536static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000537 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000538 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000539 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000540
541 const RecordDecl *RD = RT->getDecl();
542 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544
Craig Topper8a13c412014-05-21 05:09:00 +0000545 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000546
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000547 // If this is a C++ record, check the bases first.
548 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000549 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000550 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000551 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000552 continue;
553
554 // If we already found an element then this isn't a single-element struct.
555 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000556 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000557
558 // If this is non-empty and not a single element struct, the composite
559 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000560 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000561 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000562 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000563 }
564 }
565
566 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000567 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568 QualType FT = FD->getType();
569
570 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000571 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572 continue;
573
574 // If we already found an element then this isn't a single-element
575 // struct.
576 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000577 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578
579 // Treat single element arrays as the element.
580 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
581 if (AT->getSize().getZExtValue() != 1)
582 break;
583 FT = AT->getElementType();
584 }
585
John McCalla1dee5302010-08-22 10:59:02 +0000586 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587 Found = FT.getTypePtr();
588 } else {
589 Found = isSingleElementStruct(FT, Context);
590 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000591 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000592 }
593 }
594
Eli Friedmanee945342011-11-18 01:25:50 +0000595 // We don't consider a struct a single-element struct if it has
596 // padding beyond the element type.
597 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000598 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000599
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000600 return Found;
601}
602
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000603namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000604Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
605 const ABIArgInfo &AI) {
606 // This default implementation defers to the llvm backend's va_arg
607 // instruction. It can handle only passing arguments directly
608 // (typically only handled in the backend for primitive types), or
609 // aggregates passed indirectly by pointer (NOTE: if the "byval"
610 // flag has ABI impact in the callee, this implementation cannot
611 // work.)
612
613 // Only a few cases are covered here at the moment -- those needed
614 // by the default abi.
615 llvm::Value *Val;
616
617 if (AI.isIndirect()) {
618 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000619 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000620 assert(
621 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000622 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000623
624 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
625 CharUnits TyAlignForABI = TyInfo.second;
626
627 llvm::Type *BaseTy =
628 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
629 llvm::Value *Addr =
630 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
631 return Address(Addr, TyAlignForABI);
632 } else {
633 assert((AI.isDirect() || AI.isExtend()) &&
634 "Unexpected ArgInfo Kind in generic VAArg emitter!");
635
636 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000637 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000638 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000639 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000640 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000641 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000642 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000643 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000644
645 Address Temp = CGF.CreateMemTemp(Ty, "varet");
646 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
647 CGF.Builder.CreateStore(Val, Temp);
648 return Temp;
649 }
650}
651
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000652/// DefaultABIInfo - The default implementation for ABI specific
653/// details. This implementation provides information which results in
654/// self-consistent and sensible LLVM IR generation, but does not
655/// conform to any particular ABI.
656class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000657public:
658 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000659
Chris Lattner458b2aa2010-07-29 02:16:43 +0000660 ABIArgInfo classifyReturnType(QualType RetTy) const;
661 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000662
Craig Topper4f12f102014-03-12 06:41:41 +0000663 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000664 if (!getCXXABI().classifyReturnType(FI))
665 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000666 for (auto &I : FI.arguments())
667 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000668 }
669
John McCall7f416cc2015-09-08 08:05:57 +0000670 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000671 QualType Ty) const override {
672 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
673 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000674};
675
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000676class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
677public:
Chris Lattner2b037972010-07-29 02:01:43 +0000678 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
679 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000680};
681
Chris Lattner458b2aa2010-07-29 02:16:43 +0000682ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000683 Ty = useFirstFieldIfTransparentUnion(Ty);
684
685 if (isAggregateTypeForABI(Ty)) {
686 // Records with non-trivial destructors/copy-constructors should not be
687 // passed by value.
688 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000689 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000690
John McCall7f416cc2015-09-08 08:05:57 +0000691 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000692 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000693
Chris Lattner9723d6c2010-03-11 18:19:55 +0000694 // Treat an enum type as its underlying type.
695 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
696 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000697
Alex Bradburye41a5e22018-01-12 20:08:16 +0000698 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
699 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000700}
701
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000702ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
703 if (RetTy->isVoidType())
704 return ABIArgInfo::getIgnore();
705
706 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000707 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000708
709 // Treat an enum type as its underlying type.
710 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
711 RetTy = EnumTy->getDecl()->getIntegerType();
712
Alex Bradburye41a5e22018-01-12 20:08:16 +0000713 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
714 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000715}
716
Derek Schuff09338a22012-09-06 17:37:28 +0000717//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000718// WebAssembly ABI Implementation
719//
720// This is a very simple ABI that relies a lot on DefaultABIInfo.
721//===----------------------------------------------------------------------===//
722
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)) {}
Sam Clegg6fd7d682018-06-25 18:47:32 +0000750
751 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
752 CodeGen::CodeGenModule &CGM) const override {
753 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
754 llvm::Function *Fn = cast<llvm::Function>(GV);
755 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
756 Fn->addFnAttr("no-prototype");
757 }
758 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000759};
760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000761/// Classify argument of given type \p Ty.
Dan Gohmanc2853072015-09-03 22:51:53 +0000762ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
763 Ty = useFirstFieldIfTransparentUnion(Ty);
764
765 if (isAggregateTypeForABI(Ty)) {
766 // Records with non-trivial destructors/copy-constructors should not be
767 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000768 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000769 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000770 // Ignore empty structs/unions.
771 if (isEmptyRecord(getContext(), Ty, true))
772 return ABIArgInfo::getIgnore();
773 // Lower single-element structs to just pass a regular value. TODO: We
774 // could do reasonable-size multiple-element structs too, using getExpand(),
775 // though watch out for things like bitfields.
776 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
777 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000778 }
779
780 // Otherwise just do the default thing.
781 return DefaultABIInfo::classifyArgumentType(Ty);
782}
783
784ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
785 if (isAggregateTypeForABI(RetTy)) {
786 // Records with non-trivial destructors/copy-constructors should not be
787 // returned by value.
788 if (!getRecordArgABI(RetTy, getCXXABI())) {
789 // Ignore empty structs/unions.
790 if (isEmptyRecord(getContext(), RetTy, true))
791 return ABIArgInfo::getIgnore();
792 // Lower single-element structs to just return a regular value. TODO: We
793 // could do reasonable-size multiple-element structs too, using
794 // ABIArgInfo::getDirect().
795 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
796 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
797 }
798 }
799
800 // Otherwise just do the default thing.
801 return DefaultABIInfo::classifyReturnType(RetTy);
802}
803
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000804Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
805 QualType Ty) const {
806 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
807 getContext().getTypeInfoInChars(Ty),
808 CharUnits::fromQuantity(4),
809 /*AllowHigherAlign=*/ true);
810}
811
Dan Gohmanc2853072015-09-03 22:51:53 +0000812//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000813// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000814//
815// This is a simplified version of the x86_32 ABI. Arguments and return values
816// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000817//===----------------------------------------------------------------------===//
818
819class PNaClABIInfo : public ABIInfo {
820 public:
821 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
822
823 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000824 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000825
Craig Topper4f12f102014-03-12 06:41:41 +0000826 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000827 Address EmitVAArg(CodeGenFunction &CGF,
828 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000829};
830
831class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
832 public:
833 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
834 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
835};
836
837void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000838 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000839 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
840
Reid Kleckner40ca9132014-05-13 22:05:45 +0000841 for (auto &I : FI.arguments())
842 I.info = classifyArgumentType(I.type);
843}
Derek Schuff09338a22012-09-06 17:37:28 +0000844
John McCall7f416cc2015-09-08 08:05:57 +0000845Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
846 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000847 // The PNaCL ABI is a bit odd, in that varargs don't use normal
848 // function classification. Structs get passed directly for varargs
849 // functions, through a rewriting transform in
850 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
851 // this target to actually support a va_arg instructions with an
852 // aggregate type, unlike other targets.
853 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000854}
855
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000856/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000857ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000858 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000859 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000860 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
861 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000862 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
863 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000864 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000865 } else if (Ty->isFloatingType()) {
866 // Floating-point types don't go inreg.
867 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000868 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000869
Alex Bradburye41a5e22018-01-12 20:08:16 +0000870 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
871 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000872}
873
874ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
875 if (RetTy->isVoidType())
876 return ABIArgInfo::getIgnore();
877
Eli Benderskye20dad62013-04-04 22:49:35 +0000878 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000879 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000880 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000881
882 // Treat an enum type as its underlying type.
883 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
884 RetTy = EnumTy->getDecl()->getIntegerType();
885
Alex Bradburye41a5e22018-01-12 20:08:16 +0000886 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
887 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000888}
889
Chad Rosier651c1832013-03-25 21:00:27 +0000890/// IsX86_MMXType - Return true if this is an MMX type.
891bool IsX86_MMXType(llvm::Type *IRType) {
892 // 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 +0000893 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
894 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
895 IRType->getScalarSizeInBits() != 64;
896}
897
Jay Foad7c57be32011-07-11 09:56:20 +0000898static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000899 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000900 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000901 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
902 .Cases("y", "&y", "^Ym", true)
903 .Default(false);
904 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000905 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
906 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000907 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000908 }
909
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000910 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000911 }
912
913 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000914 return Ty;
915}
916
Reid Kleckner80944df2014-10-31 22:00:51 +0000917/// Returns true if this type can be passed in SSE registers with the
918/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
919static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
920 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000921 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
922 if (BT->getKind() == BuiltinType::LongDouble) {
923 if (&Context.getTargetInfo().getLongDoubleFormat() ==
924 &llvm::APFloat::x87DoubleExtended())
925 return false;
926 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000927 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000928 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000929 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
930 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
931 // registers specially.
932 unsigned VecSize = Context.getTypeSize(VT);
933 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
934 return true;
935 }
936 return false;
937}
938
939/// Returns true if this aggregate is small enough to be passed in SSE registers
940/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
941static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
942 return NumMembers <= 4;
943}
944
Erich Keane521ed962017-01-05 00:20:51 +0000945/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
946static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
947 auto AI = ABIArgInfo::getDirect(T);
948 AI.setInReg(true);
949 AI.setCanBeFlattened(false);
950 return AI;
951}
952
Chris Lattner0cf24192010-06-28 20:05:43 +0000953//===----------------------------------------------------------------------===//
954// X86-32 ABI Implementation
955//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000956
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000957/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000958struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000959 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000960
961 unsigned CC;
962 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000963 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000964};
965
Erich Keane521ed962017-01-05 00:20:51 +0000966enum {
967 // Vectorcall only allows the first 6 parameters to be passed in registers.
968 VectorcallMaxParamNumAsReg = 6
969};
970
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000971/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000972class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000973 enum Class {
974 Integer,
975 Float
976 };
977
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000978 static const unsigned MinABIStackAlignInBytes = 4;
979
David Chisnallde3a0692009-08-17 23:08:21 +0000980 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000981 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000982 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000983 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000984 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000985 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000986
987 static bool isRegisterSize(unsigned Size) {
988 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
989 }
990
Reid Kleckner80944df2014-10-31 22:00:51 +0000991 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
992 // FIXME: Assumes vectorcall is in use.
993 return isX86VectorTypeForVectorCall(getContext(), Ty);
994 }
995
996 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
997 uint64_t NumMembers) const override {
998 // FIXME: Assumes vectorcall is in use.
999 return isX86VectorCallAggregateSmallEnough(NumMembers);
1000 }
1001
Reid Kleckner40ca9132014-05-13 22:05:45 +00001002 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001003
Daniel Dunbar557893d2010-04-21 19:10:51 +00001004 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1005 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001006 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1007
John McCall7f416cc2015-09-08 08:05:57 +00001008 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001009
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001010 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001011 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001012
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001013 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001014 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001015 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001016
Fangrui Song6907ce22018-07-30 19:24:48 +00001017 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001018 /// true if any registers were allocated.
1019 bool updateFreeRegs(QualType Ty, CCState &State) const;
1020
1021 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1022 bool &NeedsPadding) const;
1023 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001024
Reid Kleckner04046052016-05-02 17:41:07 +00001025 bool canExpandIndirectArgument(QualType Ty) const;
1026
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001027 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001028 /// inalloca.
1029 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1030
1031 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001032 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001033 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001034 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1035 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001036
Rafael Espindola75419dc2012-07-23 23:30:29 +00001037public:
1038
Craig Topper4f12f102014-03-12 06:41:41 +00001039 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001040 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1041 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001042
Michael Kupersteindc745202015-10-19 07:52:25 +00001043 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1044 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001045 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001046 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001047 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001048 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001049 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001050 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001051 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001052
John McCall56331e22018-01-07 06:28:49 +00001053 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001054 bool asReturnValue) const override {
1055 // LLVM's x86-32 lowering currently only assigns up to three
1056 // integer registers and three fp registers. Oddly, it'll use up to
1057 // four vector registers for vectors, but those can overlap with the
1058 // scalar registers.
1059 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001060 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001061
1062 bool isSwiftErrorInRegister() const override {
1063 // x86-32 lowering does not support passing swifterror in a register.
1064 return false;
1065 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001066};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001068class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1069public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001070 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1071 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001072 unsigned NumRegisterParameters, bool SoftFloatABI)
1073 : TargetCodeGenInfo(new X86_32ABIInfo(
1074 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1075 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001076
John McCall1fe2a8c2013-06-18 02:46:29 +00001077 static bool isStructReturnInRegABI(
1078 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1079
Eric Christopher162c91c2015-06-05 22:03:00 +00001080 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001081 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001082
Craig Topper4f12f102014-03-12 06:41:41 +00001083 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001084 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001085 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001086 return 4;
1087 }
1088
1089 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001090 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001091
Jay Foad7c57be32011-07-11 09:56:20 +00001092 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001093 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001094 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001095 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1096 }
1097
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001098 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1099 std::string &Constraints,
1100 std::vector<llvm::Type *> &ResultRegTypes,
1101 std::vector<llvm::Type *> &ResultTruncRegTypes,
1102 std::vector<LValue> &ResultRegDests,
1103 std::string &AsmString,
1104 unsigned NumOutputs) const override;
1105
Craig Topper4f12f102014-03-12 06:41:41 +00001106 llvm::Constant *
1107 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001108 unsigned Sig = (0xeb << 0) | // jmp rel8
1109 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001110 ('v' << 16) |
1111 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001112 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1113 }
John McCall01391782016-02-05 21:37:38 +00001114
1115 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1116 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001117 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001118 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001119};
1120
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001121}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001122
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001123/// Rewrite input constraint references after adding some output constraints.
1124/// In the case where there is one output and one input and we add one output,
1125/// we need to replace all operand references greater than or equal to 1:
1126/// mov $0, $1
1127/// mov eax, $1
1128/// The result will be:
1129/// mov $0, $2
1130/// mov eax, $2
1131static void rewriteInputConstraintReferences(unsigned FirstIn,
1132 unsigned NumNewOuts,
1133 std::string &AsmString) {
1134 std::string Buf;
1135 llvm::raw_string_ostream OS(Buf);
1136 size_t Pos = 0;
1137 while (Pos < AsmString.size()) {
1138 size_t DollarStart = AsmString.find('$', Pos);
1139 if (DollarStart == std::string::npos)
1140 DollarStart = AsmString.size();
1141 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1142 if (DollarEnd == std::string::npos)
1143 DollarEnd = AsmString.size();
1144 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1145 Pos = DollarEnd;
1146 size_t NumDollars = DollarEnd - DollarStart;
1147 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1148 // We have an operand reference.
1149 size_t DigitStart = Pos;
1150 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1151 if (DigitEnd == std::string::npos)
1152 DigitEnd = AsmString.size();
1153 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1154 unsigned OperandIndex;
1155 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1156 if (OperandIndex >= FirstIn)
1157 OperandIndex += NumNewOuts;
1158 OS << OperandIndex;
1159 } else {
1160 OS << OperandStr;
1161 }
1162 Pos = DigitEnd;
1163 }
1164 }
1165 AsmString = std::move(OS.str());
1166}
1167
1168/// Add output constraints for EAX:EDX because they are return registers.
1169void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1170 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1171 std::vector<llvm::Type *> &ResultRegTypes,
1172 std::vector<llvm::Type *> &ResultTruncRegTypes,
1173 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1174 unsigned NumOutputs) const {
1175 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1176
1177 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1178 // larger.
1179 if (!Constraints.empty())
1180 Constraints += ',';
1181 if (RetWidth <= 32) {
1182 Constraints += "={eax}";
1183 ResultRegTypes.push_back(CGF.Int32Ty);
1184 } else {
1185 // Use the 'A' constraint for EAX:EDX.
1186 Constraints += "=A";
1187 ResultRegTypes.push_back(CGF.Int64Ty);
1188 }
1189
1190 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1191 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1192 ResultTruncRegTypes.push_back(CoerceTy);
1193
1194 // Coerce the integer by bitcasting the return slot pointer.
1195 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1196 CoerceTy->getPointerTo()));
1197 ResultRegDests.push_back(ReturnSlot);
1198
1199 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1200}
1201
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001202/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001203/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001204bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1205 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206 uint64_t Size = Context.getTypeSize(Ty);
1207
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001208 // For i386, type must be register sized.
1209 // For the MCU ABI, it only needs to be <= 8-byte
1210 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1211 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001212
1213 if (Ty->isVectorType()) {
1214 // 64- and 128- bit vectors inside structures are not returned in
1215 // registers.
1216 if (Size == 64 || Size == 128)
1217 return false;
1218
1219 return true;
1220 }
1221
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001222 // If this is a builtin, pointer, enum, complex type, member pointer, or
1223 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001224 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001225 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001226 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227 return true;
1228
1229 // Arrays are treated like records.
1230 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001231 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001232
1233 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001234 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001235 if (!RT) return false;
1236
Anders Carlsson40446e82010-01-27 03:25:19 +00001237 // FIXME: Traverse bases here too.
1238
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001239 // Structure types are passed in register if all fields would be
1240 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001241 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001243 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001244 continue;
1245
1246 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001247 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001248 return false;
1249 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001250 return true;
1251}
1252
Reid Kleckner04046052016-05-02 17:41:07 +00001253static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1254 // Treat complex types as the element type.
1255 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1256 Ty = CTy->getElementType();
1257
1258 // Check for a type which we know has a simple scalar argument-passing
1259 // convention without any padding. (We're specifically looking for 32
1260 // and 64-bit integer and integer-equivalents, float, and double.)
1261 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1262 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1263 return false;
1264
1265 uint64_t Size = Context.getTypeSize(Ty);
1266 return Size == 32 || Size == 64;
1267}
1268
Reid Kleckner791bbf62017-01-13 17:18:19 +00001269static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1270 uint64_t &Size) {
1271 for (const auto *FD : RD->fields()) {
1272 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1273 // argument is smaller than 32-bits, expanding the struct will create
1274 // alignment padding.
1275 if (!is32Or64BitBasicType(FD->getType(), Context))
1276 return false;
1277
1278 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1279 // how to expand them yet, and the predicate for telling if a bitfield still
1280 // counts as "basic" is more complicated than what we were doing previously.
1281 if (FD->isBitField())
1282 return false;
1283
1284 Size += Context.getTypeSize(FD->getType());
1285 }
1286 return true;
1287}
1288
1289static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1290 uint64_t &Size) {
1291 // Don't do this if there are any non-empty bases.
1292 for (const CXXBaseSpecifier &Base : RD->bases()) {
1293 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1294 Size))
1295 return false;
1296 }
1297 if (!addFieldSizes(Context, RD, Size))
1298 return false;
1299 return true;
1300}
1301
Reid Kleckner04046052016-05-02 17:41:07 +00001302/// Test whether an argument type which is to be passed indirectly (on the
1303/// stack) would have the equivalent layout if it was expanded into separate
1304/// arguments. If so, we prefer to do the latter to avoid inhibiting
1305/// optimizations.
1306bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1307 // We can only expand structure types.
1308 const RecordType *RT = Ty->getAs<RecordType>();
1309 if (!RT)
1310 return false;
1311 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001312 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001313 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001314 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001315 // On non-Windows, we have to conservatively match our old bitcode
1316 // prototypes in order to be ABI-compatible at the bitcode level.
1317 if (!CXXRD->isCLike())
1318 return false;
1319 } else {
1320 // Don't do this for dynamic classes.
1321 if (CXXRD->isDynamicClass())
1322 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001323 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001324 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001325 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001326 } else {
1327 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001328 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001329 }
1330
1331 // We can do this if there was no alignment padding.
1332 return Size == getContext().getTypeSize(Ty);
1333}
1334
John McCall7f416cc2015-09-08 08:05:57 +00001335ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001336 // If the return value is indirect, then the hidden argument is consuming one
1337 // integer register.
1338 if (State.FreeRegs) {
1339 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001340 if (!IsMCUABI)
1341 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001342 }
John McCall7f416cc2015-09-08 08:05:57 +00001343 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001344}
1345
Eric Christopher7565e0d2015-05-29 23:09:49 +00001346ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1347 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001348 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001349 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001350
Reid Kleckner80944df2014-10-31 22:00:51 +00001351 const Type *Base = nullptr;
1352 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001353 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1354 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001355 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1356 // The LLVM struct type for such an aggregate should lower properly.
1357 return ABIArgInfo::getDirect();
1358 }
1359
Chris Lattner458b2aa2010-07-29 02:16:43 +00001360 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001361 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001362 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001363 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001364
1365 // 128-bit vectors are a special case; they are returned in
1366 // registers and we need to make sure to pick a type the LLVM
1367 // backend will like.
1368 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001369 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001370 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001371
1372 // Always return in register if it fits in a general purpose
1373 // register, or if it is 64 bits and has a single element.
1374 if ((Size == 8 || Size == 16 || Size == 32) ||
1375 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001376 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001377 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001378
John McCall7f416cc2015-09-08 08:05:57 +00001379 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001380 }
1381
1382 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001383 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001384
John McCalla1dee5302010-08-22 10:59:02 +00001385 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001386 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001387 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001388 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001389 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001390 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001391
David Chisnallde3a0692009-08-17 23:08:21 +00001392 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001393 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001394 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001395
Denis Zobnin380b2242016-02-11 11:26:03 +00001396 // Ignore empty structs/unions.
1397 if (isEmptyRecord(getContext(), RetTy, true))
1398 return ABIArgInfo::getIgnore();
1399
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400 // Small structures which are register sized are generally returned
1401 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001402 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001403 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001404
1405 // As a special-case, if the struct is a "single-element" struct, and
1406 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001407 // floating-point register. (MSVC does not apply this special case.)
1408 // We apply a similar transformation for pointer types to improve the
1409 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001410 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001411 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001412 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001413 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1414
1415 // FIXME: We should be able to narrow this integer in cases with dead
1416 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001417 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001418 }
1419
John McCall7f416cc2015-09-08 08:05:57 +00001420 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001421 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001422
Chris Lattner458b2aa2010-07-29 02:16:43 +00001423 // Treat an enum type as its underlying type.
1424 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1425 RetTy = EnumTy->getDecl()->getIntegerType();
1426
Alex Bradburye41a5e22018-01-12 20:08:16 +00001427 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1428 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001429}
1430
Eli Friedman7919bea2012-06-05 19:40:46 +00001431static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1432 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1433}
1434
Daniel Dunbared23de32010-09-16 20:42:00 +00001435static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1436 const RecordType *RT = Ty->getAs<RecordType>();
1437 if (!RT)
1438 return 0;
1439 const RecordDecl *RD = RT->getDecl();
1440
1441 // If this is a C++ record, check the bases first.
1442 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001443 for (const auto &I : CXXRD->bases())
1444 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001445 return false;
1446
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001447 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001448 QualType FT = i->getType();
1449
Eli Friedman7919bea2012-06-05 19:40:46 +00001450 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001451 return true;
1452
1453 if (isRecordWithSSEVectorType(Context, FT))
1454 return true;
1455 }
1456
1457 return false;
1458}
1459
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001460unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1461 unsigned Align) const {
1462 // Otherwise, if the alignment is less than or equal to the minimum ABI
1463 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001464 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001465 return 0; // Use default alignment.
1466
1467 // On non-Darwin, the stack type alignment is always 4.
1468 if (!IsDarwinVectorABI) {
1469 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001470 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001471 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001472
Daniel Dunbared23de32010-09-16 20:42:00 +00001473 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001474 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1475 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001476 return 16;
1477
1478 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001479}
1480
Rafael Espindola703c47f2012-10-19 05:04:37 +00001481ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001482 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001483 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001484 if (State.FreeRegs) {
1485 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001486 if (!IsMCUABI)
1487 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001488 }
John McCall7f416cc2015-09-08 08:05:57 +00001489 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001490 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001491
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001492 // Compute the byval alignment.
1493 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1494 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1495 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001496 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001497
1498 // If the stack alignment is less than the type alignment, realign the
1499 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001500 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001501 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1502 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001503}
1504
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001505X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1506 const Type *T = isSingleElementStruct(Ty, getContext());
1507 if (!T)
1508 T = Ty.getTypePtr();
1509
1510 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1511 BuiltinType::Kind K = BT->getKind();
1512 if (K == BuiltinType::Float || K == BuiltinType::Double)
1513 return Float;
1514 }
1515 return Integer;
1516}
1517
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001518bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001519 if (!IsSoftFloatABI) {
1520 Class C = classify(Ty);
1521 if (C == Float)
1522 return false;
1523 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001524
Rafael Espindola077dd592012-10-24 01:58:58 +00001525 unsigned Size = getContext().getTypeSize(Ty);
1526 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001527
1528 if (SizeInRegs == 0)
1529 return false;
1530
Michael Kuperstein68901882015-10-25 08:18:20 +00001531 if (!IsMCUABI) {
1532 if (SizeInRegs > State.FreeRegs) {
1533 State.FreeRegs = 0;
1534 return false;
1535 }
1536 } else {
1537 // The MCU psABI allows passing parameters in-reg even if there are
1538 // earlier parameters that are passed on the stack. Also,
1539 // it does not allow passing >8-byte structs in-register,
1540 // even if there are 3 free registers available.
1541 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1542 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001543 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001544
Reid Kleckner661f35b2014-01-18 01:12:41 +00001545 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001546 return true;
1547}
1548
Fangrui Song6907ce22018-07-30 19:24:48 +00001549bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001550 bool &InReg,
1551 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001552 // On Windows, aggregates other than HFAs are never passed in registers, and
1553 // they do not consume register slots. Homogenous floating-point aggregates
1554 // (HFAs) have already been dealt with at this point.
1555 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1556 return false;
1557
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001558 NeedsPadding = false;
1559 InReg = !IsMCUABI;
1560
1561 if (!updateFreeRegs(Ty, State))
1562 return false;
1563
1564 if (IsMCUABI)
1565 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001566
Reid Kleckner80944df2014-10-31 22:00:51 +00001567 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001568 State.CC == llvm::CallingConv::X86_VectorCall ||
1569 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001570 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001571 NeedsPadding = true;
1572
Rafael Espindola077dd592012-10-24 01:58:58 +00001573 return false;
1574 }
1575
Rafael Espindola703c47f2012-10-19 05:04:37 +00001576 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001577}
1578
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001579bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1580 if (!updateFreeRegs(Ty, State))
1581 return false;
1582
1583 if (IsMCUABI)
1584 return false;
1585
1586 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001587 State.CC == llvm::CallingConv::X86_VectorCall ||
1588 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001589 if (getContext().getTypeSize(Ty) > 32)
1590 return false;
1591
Fangrui Song6907ce22018-07-30 19:24:48 +00001592 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001593 Ty->isReferenceType());
1594 }
1595
1596 return true;
1597}
1598
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001599ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1600 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001601 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001602
Reid Klecknerb1be6832014-11-15 01:41:41 +00001603 Ty = useFirstFieldIfTransparentUnion(Ty);
1604
Reid Kleckner80944df2014-10-31 22:00:51 +00001605 // Check with the C++ ABI first.
1606 const RecordType *RT = Ty->getAs<RecordType>();
1607 if (RT) {
1608 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1609 if (RAA == CGCXXABI::RAA_Indirect) {
1610 return getIndirectResult(Ty, false, State);
1611 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1612 // The field index doesn't matter, we'll fix it up later.
1613 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1614 }
1615 }
1616
Erich Keane4bd39302017-06-21 16:37:22 +00001617 // Regcall uses the concept of a homogenous vector aggregate, similar
1618 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001619 const Type *Base = nullptr;
1620 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001621 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001622 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001623
Erich Keane4bd39302017-06-21 16:37:22 +00001624 if (State.FreeSSERegs >= NumElts) {
1625 State.FreeSSERegs -= NumElts;
1626 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001627 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001628 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001629 }
Erich Keane4bd39302017-06-21 16:37:22 +00001630 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001631 }
1632
1633 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001634 // Structures with flexible arrays are always indirect.
1635 // FIXME: This should not be byval!
1636 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1637 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001638
Reid Kleckner04046052016-05-02 17:41:07 +00001639 // Ignore empty structs/unions on non-Windows.
1640 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641 return ABIArgInfo::getIgnore();
1642
Rafael Espindolafad28de2012-10-24 01:59:00 +00001643 llvm::LLVMContext &LLVMContext = getVMContext();
1644 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001645 bool NeedsPadding = false;
1646 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001647 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001648 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001649 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001650 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001651 if (InReg)
1652 return ABIArgInfo::getDirectInReg(Result);
1653 else
1654 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001655 }
Craig Topper8a13c412014-05-21 05:09:00 +00001656 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001657
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001658 // Expand small (<= 128-bit) record types when we know that the stack layout
1659 // of those arguments will match the struct. This is important because the
1660 // LLVM backend isn't smart enough to remove byval, which inhibits many
1661 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001662 // Don't do this for the MCU if there are still free integer registers
1663 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001664 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1665 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001666 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001667 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001668 State.CC == llvm::CallingConv::X86_VectorCall ||
1669 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001670 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671
Reid Kleckner661f35b2014-01-18 01:12:41 +00001672 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001673 }
1674
Chris Lattnerd774ae92010-08-26 20:05:13 +00001675 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001676 // On Darwin, some vectors are passed in memory, we handle this by passing
1677 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001678 if (IsDarwinVectorABI) {
1679 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001680 if ((Size == 8 || Size == 16 || Size == 32) ||
1681 (Size == 64 && VT->getNumElements() == 1))
1682 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1683 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001684 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001685
Chad Rosier651c1832013-03-25 21:00:27 +00001686 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1687 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001688
Chris Lattnerd774ae92010-08-26 20:05:13 +00001689 return ABIArgInfo::getDirect();
1690 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001691
1692
Chris Lattner458b2aa2010-07-29 02:16:43 +00001693 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1694 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001695
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001696 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001697
1698 if (Ty->isPromotableIntegerType()) {
1699 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001700 return ABIArgInfo::getExtendInReg(Ty);
1701 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001702 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001703
Rafael Espindola703c47f2012-10-19 05:04:37 +00001704 if (InReg)
1705 return ABIArgInfo::getDirectInReg();
1706 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001707}
1708
Erich Keane521ed962017-01-05 00:20:51 +00001709void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1710 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001711 // Vectorcall x86 works subtly different than in x64, so the format is
1712 // a bit different than the x64 version. First, all vector types (not HVAs)
1713 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1714 // This differs from the x64 implementation, where the first 6 by INDEX get
1715 // registers.
1716 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1717 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1718 // first take up the remaining YMM/XMM registers. If insufficient registers
1719 // remain but an integer register (ECX/EDX) is available, it will be passed
1720 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001721 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001722 // First pass do all the vector types.
1723 const Type *Base = nullptr;
1724 uint64_t NumElts = 0;
1725 const QualType& Ty = I.type;
1726 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1727 isHomogeneousAggregate(Ty, Base, NumElts)) {
1728 if (State.FreeSSERegs >= NumElts) {
1729 State.FreeSSERegs -= NumElts;
1730 I.info = ABIArgInfo::getDirect();
1731 } else {
1732 I.info = classifyArgumentType(Ty, State);
1733 }
1734 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1735 }
Erich Keane521ed962017-01-05 00:20:51 +00001736 }
Erich Keane4bd39302017-06-21 16:37:22 +00001737
Erich Keane521ed962017-01-05 00:20:51 +00001738 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001739 // Second pass, do the rest!
1740 const Type *Base = nullptr;
1741 uint64_t NumElts = 0;
1742 const QualType& Ty = I.type;
1743 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1744
1745 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1746 // Assign true HVAs (non vector/native FP types).
1747 if (State.FreeSSERegs >= NumElts) {
1748 State.FreeSSERegs -= NumElts;
1749 I.info = getDirectX86Hva();
1750 } else {
1751 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1752 }
1753 } else if (!IsHva) {
1754 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1755 I.info = classifyArgumentType(Ty, State);
1756 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1757 }
Erich Keane521ed962017-01-05 00:20:51 +00001758 }
1759}
1760
Rafael Espindolaa6472962012-07-24 00:01:07 +00001761void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001762 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001763 if (IsMCUABI)
1764 State.FreeRegs = 3;
1765 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001766 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001767 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1768 State.FreeRegs = 2;
1769 State.FreeSSERegs = 6;
1770 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001771 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001772 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1773 State.FreeRegs = 5;
1774 State.FreeSSERegs = 8;
1775 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001776 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001777
Akira Hatanakad791e922018-03-19 17:38:40 +00001778 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001779 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001780 } else if (FI.getReturnInfo().isIndirect()) {
1781 // The C++ ABI is not aware of register usage, so we have to check if the
1782 // return value was sret and put it in a register ourselves if appropriate.
1783 if (State.FreeRegs) {
1784 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001785 if (!IsMCUABI)
1786 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001787 }
1788 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001789
Peter Collingbournef7706832014-12-12 23:41:25 +00001790 // The chain argument effectively gives us another free register.
1791 if (FI.isChainCall())
1792 ++State.FreeRegs;
1793
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001795 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1796 computeVectorCallArgs(FI, State, UsedInAlloca);
1797 } else {
1798 // If not vectorcall, revert to normal behavior.
1799 for (auto &I : FI.arguments()) {
1800 I.info = classifyArgumentType(I.type, State);
1801 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1802 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001803 }
1804
1805 // If we needed to use inalloca for any argument, do a second pass and rewrite
1806 // all the memory arguments to use inalloca.
1807 if (UsedInAlloca)
1808 rewriteWithInAlloca(FI);
1809}
1810
1811void
1812X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001813 CharUnits &StackOffset, ABIArgInfo &Info,
1814 QualType Type) const {
1815 // Arguments are always 4-byte-aligned.
1816 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1817
1818 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001819 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1820 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001821 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001822
John McCall7f416cc2015-09-08 08:05:57 +00001823 // Insert padding bytes to respect alignment.
1824 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001825 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001826 if (StackOffset != FieldEnd) {
1827 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001828 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001829 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001830 FrameFields.push_back(Ty);
1831 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001832}
1833
Reid Kleckner852361d2014-07-26 00:12:26 +00001834static bool isArgInAlloca(const ABIArgInfo &Info) {
1835 // Leave ignored and inreg arguments alone.
1836 switch (Info.getKind()) {
1837 case ABIArgInfo::InAlloca:
1838 return true;
1839 case ABIArgInfo::Indirect:
1840 assert(Info.getIndirectByVal());
1841 return true;
1842 case ABIArgInfo::Ignore:
1843 return false;
1844 case ABIArgInfo::Direct:
1845 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001846 if (Info.getInReg())
1847 return false;
1848 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001849 case ABIArgInfo::Expand:
1850 case ABIArgInfo::CoerceAndExpand:
1851 // These are aggregate types which are never passed in registers when
1852 // inalloca is involved.
1853 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001854 }
1855 llvm_unreachable("invalid enum");
1856}
1857
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001858void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1859 assert(IsWin32StructABI && "inalloca only supported on win32");
1860
1861 // Build a packed struct type for all of the arguments in memory.
1862 SmallVector<llvm::Type *, 6> FrameFields;
1863
John McCall7f416cc2015-09-08 08:05:57 +00001864 // The stack alignment is always 4.
1865 CharUnits StackAlign = CharUnits::fromQuantity(4);
1866
1867 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001868 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1869
1870 // Put 'this' into the struct before 'sret', if necessary.
1871 bool IsThisCall =
1872 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1873 ABIArgInfo &Ret = FI.getReturnInfo();
1874 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1875 isArgInAlloca(I->info)) {
1876 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1877 ++I;
1878 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001879
1880 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001881 if (Ret.isIndirect() && !Ret.getInReg()) {
1882 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1883 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001884 // On Windows, the hidden sret parameter is always returned in eax.
1885 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001886 }
1887
1888 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001889 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001890 ++I;
1891
1892 // Put arguments passed in memory into the struct.
1893 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001894 if (isArgInAlloca(I->info))
1895 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001896 }
1897
1898 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001899 /*isPacked=*/true),
1900 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001901}
1902
John McCall7f416cc2015-09-08 08:05:57 +00001903Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1904 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001905
John McCall7f416cc2015-09-08 08:05:57 +00001906 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001907
John McCall7f416cc2015-09-08 08:05:57 +00001908 // x86-32 changes the alignment of certain arguments on the stack.
1909 //
1910 // Just messing with TypeInfo like this works because we never pass
1911 // anything indirectly.
1912 TypeInfo.second = CharUnits::fromQuantity(
1913 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001914
John McCall7f416cc2015-09-08 08:05:57 +00001915 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1916 TypeInfo, CharUnits::fromQuantity(4),
1917 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001918}
1919
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001920bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1921 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1922 assert(Triple.getArch() == llvm::Triple::x86);
1923
1924 switch (Opts.getStructReturnConvention()) {
1925 case CodeGenOptions::SRCK_Default:
1926 break;
1927 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1928 return false;
1929 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1930 return true;
1931 }
1932
Michael Kupersteind749f232015-10-27 07:46:22 +00001933 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001934 return true;
1935
1936 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001937 case llvm::Triple::DragonFly:
1938 case llvm::Triple::FreeBSD:
1939 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001940 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001941 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001942 default:
1943 return false;
1944 }
1945}
1946
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001947void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001948 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1949 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001950 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001951 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001952 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001953 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001954 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001955 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001956 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1957 llvm::Function *Fn = cast<llvm::Function>(GV);
1958 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1959 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001960 }
1961}
1962
John McCallbeec5a02010-03-06 00:35:14 +00001963bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1964 CodeGen::CodeGenFunction &CGF,
1965 llvm::Value *Address) const {
1966 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001967
Chris Lattnerece04092012-02-07 00:39:47 +00001968 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001969
John McCallbeec5a02010-03-06 00:35:14 +00001970 // 0-7 are the eight integer registers; the order is different
1971 // on Darwin (for EH), but the range is the same.
1972 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001973 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001974
John McCallc8e01702013-04-16 22:48:15 +00001975 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001976 // 12-16 are st(0..4). Not sure why we stop at 4.
1977 // These have size 16, which is sizeof(long double) on
1978 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001979 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001980 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001981
John McCallbeec5a02010-03-06 00:35:14 +00001982 } else {
1983 // 9 is %eflags, which doesn't get a size on Darwin for some
1984 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001985 Builder.CreateAlignedStore(
1986 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1987 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001988
1989 // 11-16 are st(0..5). Not sure why we stop at 5.
1990 // These have size 12, which is sizeof(long double) on
1991 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001992 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001993 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1994 }
John McCallbeec5a02010-03-06 00:35:14 +00001995
1996 return false;
1997}
1998
Chris Lattner0cf24192010-06-28 20:05:43 +00001999//===----------------------------------------------------------------------===//
2000// X86-64 ABI Implementation
2001//===----------------------------------------------------------------------===//
2002
2003
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002004namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002005/// The AVX ABI level for X86 targets.
2006enum class X86AVXABILevel {
2007 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002008 AVX,
2009 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002010};
2011
2012/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2013static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2014 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002015 case X86AVXABILevel::AVX512:
2016 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002017 case X86AVXABILevel::AVX:
2018 return 256;
2019 case X86AVXABILevel::None:
2020 return 128;
2021 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002022 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002023}
2024
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002025/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002026class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002027 enum Class {
2028 Integer = 0,
2029 SSE,
2030 SSEUp,
2031 X87,
2032 X87Up,
2033 ComplexX87,
2034 NoClass,
2035 Memory
2036 };
2037
2038 /// merge - Implement the X86_64 ABI merging algorithm.
2039 ///
2040 /// Merge an accumulating classification \arg Accum with a field
2041 /// classification \arg Field.
2042 ///
2043 /// \param Accum - The accumulating classification. This should
2044 /// always be either NoClass or the result of a previous merge
2045 /// call. In addition, this should never be Memory (the caller
2046 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002047 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002048
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002049 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2050 ///
2051 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2052 /// final MEMORY or SSE classes when necessary.
2053 ///
2054 /// \param AggregateSize - The size of the current aggregate in
2055 /// the classification process.
2056 ///
2057 /// \param Lo - The classification for the parts of the type
2058 /// residing in the low word of the containing object.
2059 ///
2060 /// \param Hi - The classification for the parts of the type
2061 /// residing in the higher words of the containing object.
2062 ///
2063 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2064
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002065 /// classify - Determine the x86_64 register classes in which the
2066 /// given type T should be passed.
2067 ///
2068 /// \param Lo - The classification for the parts of the type
2069 /// residing in the low word of the containing object.
2070 ///
2071 /// \param Hi - The classification for the parts of the type
2072 /// residing in the high word of the containing object.
2073 ///
2074 /// \param OffsetBase - The bit offset of this type in the
2075 /// containing object. Some parameters are classified different
2076 /// depending on whether they straddle an eightbyte boundary.
2077 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002078 /// \param isNamedArg - Whether the argument in question is a "named"
2079 /// argument, as used in AMD64-ABI 3.5.7.
2080 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002081 /// If a word is unused its result will be NoClass; if a type should
2082 /// be passed in Memory then at least the classification of \arg Lo
2083 /// will be Memory.
2084 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002085 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002086 ///
2087 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2088 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002089 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2090 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002091
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002092 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002093 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2094 unsigned IROffset, QualType SourceTy,
2095 unsigned SourceOffset) const;
2096 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2097 unsigned IROffset, QualType SourceTy,
2098 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002099
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002100 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002101 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002102 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002103
2104 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002105 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002106 ///
2107 /// \param freeIntRegs - The number of free integer registers remaining
2108 /// available.
2109 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002110
Chris Lattner458b2aa2010-07-29 02:16:43 +00002111 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112
Erich Keane757d3172016-11-02 18:29:35 +00002113 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2114 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002115 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002116
Erich Keane757d3172016-11-02 18:29:35 +00002117 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2118 unsigned &NeededSSE) const;
2119
2120 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2121 unsigned &NeededSSE) const;
2122
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002123 bool IsIllegalVectorType(QualType Ty) const;
2124
John McCalle0fda732011-04-21 01:20:55 +00002125 /// The 0.98 ABI revision clarified a lot of ambiguities,
2126 /// unfortunately in ways that were not always consistent with
2127 /// certain previous compilers. In particular, platforms which
2128 /// required strict binary compatibility with older versions of GCC
2129 /// may need to exempt themselves.
2130 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002131 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002132 }
2133
Richard Smithf667ad52017-08-26 01:04:35 +00002134 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2135 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002136 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002137 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002138 if (getContext().getLangOpts().getClangABICompat() <=
2139 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002140 return false;
2141
David Majnemere2ae2282016-03-04 05:26:16 +00002142 const llvm::Triple &Triple = getTarget().getTriple();
2143 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2144 return false;
2145 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2146 return false;
2147 return true;
2148 }
2149
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002150 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002151 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2152 // 64-bit hardware.
2153 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002154
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002155public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002156 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002157 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002158 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002159 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002160
John McCalla729c622012-02-17 03:33:10 +00002161 bool isPassedUsingAVXType(QualType type) const {
2162 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002163 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002164 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2165 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002166 if (info.isDirect()) {
2167 llvm::Type *ty = info.getCoerceToType();
2168 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2169 return (vectorTy->getBitWidth() > 128);
2170 }
2171 return false;
2172 }
2173
Craig Topper4f12f102014-03-12 06:41:41 +00002174 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002175
John McCall7f416cc2015-09-08 08:05:57 +00002176 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2177 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002178 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2179 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002180
2181 bool has64BitPointers() const {
2182 return Has64BitPointers;
2183 }
John McCall12f23522016-04-04 18:33:08 +00002184
John McCall56331e22018-01-07 06:28:49 +00002185 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002186 bool asReturnValue) const override {
2187 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002188 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002189 bool isSwiftErrorInRegister() const override {
2190 return true;
2191 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002192};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002193
Chris Lattner04dc9572010-08-31 16:44:54 +00002194/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002195class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002196public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002197 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002198 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002199 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002200
Craig Topper4f12f102014-03-12 06:41:41 +00002201 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002202
John McCall7f416cc2015-09-08 08:05:57 +00002203 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2204 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002205
2206 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2207 // FIXME: Assumes vectorcall is in use.
2208 return isX86VectorTypeForVectorCall(getContext(), Ty);
2209 }
2210
2211 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2212 uint64_t NumMembers) const override {
2213 // FIXME: Assumes vectorcall is in use.
2214 return isX86VectorCallAggregateSmallEnough(NumMembers);
2215 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002216
John McCall56331e22018-01-07 06:28:49 +00002217 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002218 bool asReturnValue) const override {
2219 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2220 }
2221
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002222 bool isSwiftErrorInRegister() const override {
2223 return true;
2224 }
2225
Reid Kleckner11a17192015-10-28 22:29:52 +00002226private:
Erich Keane521ed962017-01-05 00:20:51 +00002227 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2228 bool IsVectorCall, bool IsRegCall) const;
2229 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2230 const ABIArgInfo &current) const;
2231 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2232 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002233
Erich Keane521ed962017-01-05 00:20:51 +00002234 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002235};
2236
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002237class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2238public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002239 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002240 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002241
John McCalla729c622012-02-17 03:33:10 +00002242 const X86_64ABIInfo &getABIInfo() const {
2243 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2244 }
2245
Craig Topper4f12f102014-03-12 06:41:41 +00002246 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002247 return 7;
2248 }
2249
2250 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002251 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002252 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002253
John McCall943fae92010-05-27 06:19:26 +00002254 // 0-15 are the 16 integer registers.
2255 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002256 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002257 return false;
2258 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002259
Jay Foad7c57be32011-07-11 09:56:20 +00002260 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002261 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002262 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002263 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2264 }
2265
John McCalla729c622012-02-17 03:33:10 +00002266 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002267 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002268 // The default CC on x86-64 sets %al to the number of SSA
2269 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002270 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002271 // that when AVX types are involved: the ABI explicitly states it is
2272 // undefined, and it doesn't work in practice because of how the ABI
2273 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002274 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002275 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002276 for (CallArgList::const_iterator
2277 it = args.begin(), ie = args.end(); it != ie; ++it) {
2278 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2279 HasAVXType = true;
2280 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002281 }
2282 }
John McCalla729c622012-02-17 03:33:10 +00002283
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002284 if (!HasAVXType)
2285 return true;
2286 }
John McCallcbc038a2011-09-21 08:08:30 +00002287
John McCalla729c622012-02-17 03:33:10 +00002288 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002289 }
2290
Craig Topper4f12f102014-03-12 06:41:41 +00002291 llvm::Constant *
2292 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002293 unsigned Sig = (0xeb << 0) | // jmp rel8
2294 (0x06 << 8) | // .+0x08
2295 ('v' << 16) |
2296 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002297 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2298 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002299
2300 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002301 CodeGen::CodeGenModule &CGM) const override {
2302 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002303 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002304 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002305 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002306 llvm::Function *Fn = cast<llvm::Function>(GV);
2307 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002308 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002309 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2310 llvm::Function *Fn = cast<llvm::Function>(GV);
2311 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2312 }
2313 }
2314 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002315};
2316
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002317class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2318public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002319 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2320 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002321
2322 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002323 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002324 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002325 // If the argument contains a space, enclose it in quotes.
2326 if (Lib.find(" ") != StringRef::npos)
2327 Opt += "\"" + Lib.str() + "\"";
2328 else
2329 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002330 }
2331};
2332
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002333static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002334 // If the argument does not end in .lib, automatically add the suffix.
2335 // If the argument contains a space, enclose it in quotes.
2336 // This matches the behavior of MSVC.
2337 bool Quote = (Lib.find(" ") != StringRef::npos);
2338 std::string ArgStr = Quote ? "\"" : "";
2339 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002340 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002341 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002342 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002343 return ArgStr;
2344}
2345
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002346class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2347public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002348 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002349 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2350 unsigned NumRegisterParameters)
2351 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002352 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002353
Eric Christopher162c91c2015-06-05 22:03:00 +00002354 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002355 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002356
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002357 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002358 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002359 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002360 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002361 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002362
2363 void getDetectMismatchOption(llvm::StringRef Name,
2364 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002365 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002366 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002367 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002368};
2369
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002370static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2371 CodeGen::CodeGenModule &CGM) {
2372 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002373
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002374 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002375 Fn->addFnAttr("stack-probe-size",
2376 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002377 if (CGM.getCodeGenOpts().NoStackArgProbe)
2378 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002379 }
2380}
2381
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002382void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002383 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2384 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2385 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002386 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002387 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002388}
2389
Chris Lattner04dc9572010-08-31 16:44:54 +00002390class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2391public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002392 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2393 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002394 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002395
Eric Christopher162c91c2015-06-05 22:03:00 +00002396 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002397 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002398
Craig Topper4f12f102014-03-12 06:41:41 +00002399 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002400 return 7;
2401 }
2402
2403 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002404 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002405 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002406
Chris Lattner04dc9572010-08-31 16:44:54 +00002407 // 0-15 are the 16 integer registers.
2408 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002409 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002410 return false;
2411 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002412
2413 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002414 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002415 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002416 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002417 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002418
2419 void getDetectMismatchOption(llvm::StringRef Name,
2420 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002421 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002422 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002423 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002424};
2425
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002426void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002427 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2428 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2429 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002430 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002431 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002432 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002433 llvm::Function *Fn = cast<llvm::Function>(GV);
2434 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002435 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002436 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2437 llvm::Function *Fn = cast<llvm::Function>(GV);
2438 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2439 }
2440 }
2441
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002442 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002443}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002444}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002445
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002446void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2447 Class &Hi) const {
2448 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2449 //
2450 // (a) If one of the classes is Memory, the whole argument is passed in
2451 // memory.
2452 //
2453 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2454 // memory.
2455 //
2456 // (c) If the size of the aggregate exceeds two eightbytes and the first
2457 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2458 // argument is passed in memory. NOTE: This is necessary to keep the
2459 // ABI working for processors that don't support the __m256 type.
2460 //
2461 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2462 //
2463 // Some of these are enforced by the merging logic. Others can arise
2464 // only with unions; for example:
2465 // union { _Complex double; unsigned; }
2466 //
2467 // Note that clauses (b) and (c) were added in 0.98.
2468 //
2469 if (Hi == Memory)
2470 Lo = Memory;
2471 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2472 Lo = Memory;
2473 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2474 Lo = Memory;
2475 if (Hi == SSEUp && Lo != SSE)
2476 Hi = SSE;
2477}
2478
Chris Lattnerd776fb12010-06-28 21:43:59 +00002479X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002480 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2481 // classified recursively so that always two fields are
2482 // considered. The resulting class is calculated according to
2483 // the classes of the fields in the eightbyte:
2484 //
2485 // (a) If both classes are equal, this is the resulting class.
2486 //
2487 // (b) If one of the classes is NO_CLASS, the resulting class is
2488 // the other class.
2489 //
2490 // (c) If one of the classes is MEMORY, the result is the MEMORY
2491 // class.
2492 //
2493 // (d) If one of the classes is INTEGER, the result is the
2494 // INTEGER.
2495 //
2496 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2497 // MEMORY is used as class.
2498 //
2499 // (f) Otherwise class SSE is used.
2500
2501 // Accum should never be memory (we should have returned) or
2502 // ComplexX87 (because this cannot be passed in a structure).
2503 assert((Accum != Memory && Accum != ComplexX87) &&
2504 "Invalid accumulated classification during merge.");
2505 if (Accum == Field || Field == NoClass)
2506 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002507 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002509 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002511 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002512 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002513 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2514 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002515 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002516 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002517}
2518
Chris Lattner5c740f12010-06-30 19:14:05 +00002519void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002520 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002521 // FIXME: This code can be simplified by introducing a simple value class for
2522 // Class pairs with appropriate constructor methods for the various
2523 // situations.
2524
2525 // FIXME: Some of the split computations are wrong; unaligned vectors
2526 // shouldn't be passed in registers for example, so there is no chance they
2527 // can straddle an eightbyte. Verify & simplify.
2528
2529 Lo = Hi = NoClass;
2530
2531 Class &Current = OffsetBase < 64 ? Lo : Hi;
2532 Current = Memory;
2533
John McCall9dd450b2009-09-21 23:43:11 +00002534 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 BuiltinType::Kind k = BT->getKind();
2536
2537 if (k == BuiltinType::Void) {
2538 Current = NoClass;
2539 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2540 Lo = Integer;
2541 Hi = Integer;
2542 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2543 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002544 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002545 Current = SSE;
2546 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002547 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002548 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002549 Lo = SSE;
2550 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002551 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002552 Lo = X87;
2553 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002554 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002555 Current = SSE;
2556 } else
2557 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 }
2559 // FIXME: _Decimal32 and _Decimal64 are SSE.
2560 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002561 return;
2562 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002563
Chris Lattnerd776fb12010-06-28 21:43:59 +00002564 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002565 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002566 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
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 (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002571 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002572 return;
2573 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002574
Chris Lattnerd776fb12010-06-28 21:43:59 +00002575 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002576 if (Ty->isMemberFunctionPointerType()) {
2577 if (Has64BitPointers) {
2578 // If Has64BitPointers, this is an {i64, i64}, so classify both
2579 // Lo and Hi now.
2580 Lo = Hi = Integer;
2581 } else {
2582 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2583 // straddles an eightbyte boundary, Hi should be classified as well.
2584 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2585 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2586 if (EB_FuncPtr != EB_ThisAdj) {
2587 Lo = Hi = Integer;
2588 } else {
2589 Current = Integer;
2590 }
2591 }
2592 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002593 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002594 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002595 return;
2596 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002597
Chris Lattnerd776fb12010-06-28 21:43:59 +00002598 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002599 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002600 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2601 // gcc passes the following as integer:
2602 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2603 // 2 bytes - <2 x char>, <1 x short>
2604 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605 Current = Integer;
2606
2607 // If this type crosses an eightbyte boundary, it should be
2608 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002609 uint64_t EB_Lo = (OffsetBase) / 64;
2610 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2611 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 Hi = Lo;
2613 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002614 QualType ElementType = VT->getElementType();
2615
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002617 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 return;
2619
David Majnemere2ae2282016-03-04 05:26:16 +00002620 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2621 // pass them as integer. For platforms where clang is the de facto
2622 // platform compiler, we must continue to use integer.
2623 if (!classifyIntegerMMXAsSSE() &&
2624 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2625 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2626 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2627 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 Current = Integer;
2629 else
2630 Current = SSE;
2631
2632 // If this type crosses an eightbyte boundary, it should be
2633 // split.
2634 if (OffsetBase && OffsetBase != 64)
2635 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002636 } else if (Size == 128 ||
2637 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002638 // Arguments of 256-bits are split into four eightbyte chunks. The
2639 // least significant one belongs to class SSE and all the others to class
2640 // SSEUP. The original Lo and Hi design considers that types can't be
2641 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2642 // This design isn't correct for 256-bits, but since there're no cases
2643 // where the upper parts would need to be inspected, avoid adding
2644 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002645 //
2646 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2647 // registers if they are "named", i.e. not part of the "..." of a
2648 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002649 //
2650 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2651 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002652 Lo = SSE;
2653 Hi = SSEUp;
2654 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002655 return;
2656 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002657
Chris Lattnerd776fb12010-06-28 21:43:59 +00002658 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002659 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660
Chris Lattner2b037972010-07-29 02:01:43 +00002661 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002662 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663 if (Size <= 64)
2664 Current = Integer;
2665 else if (Size <= 128)
2666 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002667 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002668 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002669 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002670 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002671 } else if (ET == getContext().LongDoubleTy) {
2672 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002673 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002674 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002675 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002676 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002677 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002678 Lo = Hi = SSE;
2679 else
2680 llvm_unreachable("unexpected long double representation!");
2681 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682
2683 // If this complex type crosses an eightbyte boundary then it
2684 // should be split.
2685 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002686 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002687 if (Hi == NoClass && EB_Real != EB_Imag)
2688 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002689
Chris Lattnerd776fb12010-06-28 21:43:59 +00002690 return;
2691 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002692
Chris Lattner2b037972010-07-29 02:01:43 +00002693 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002694 // Arrays are treated like structures.
2695
Chris Lattner2b037972010-07-29 02:01:43 +00002696 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697
2698 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002699 // than eight eightbytes, ..., it has class MEMORY.
2700 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701 return;
2702
2703 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2704 // fields, it has class MEMORY.
2705 //
2706 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002707 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 return;
2709
2710 // Otherwise implement simplified merge. We could be smarter about
2711 // this, but it isn't worth it and would be harder to verify.
2712 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002713 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002715
2716 // The only case a 256-bit wide vector could be used is when the array
2717 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2718 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002719 //
2720 if (Size > 128 &&
2721 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002722 return;
2723
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002724 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2725 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002726 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 Lo = merge(Lo, FieldLo);
2728 Hi = merge(Hi, FieldHi);
2729 if (Lo == Memory || Hi == Memory)
2730 break;
2731 }
2732
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002733 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002734 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002735 return;
2736 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002737
Chris Lattnerd776fb12010-06-28 21:43:59 +00002738 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002739 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002740
2741 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002742 // than eight eightbytes, ..., it has class MEMORY.
2743 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 return;
2745
Anders Carlsson20759ad2009-09-16 15:53:40 +00002746 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2747 // copy constructor or a non-trivial destructor, it is passed by invisible
2748 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002749 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002750 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002751
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002752 const RecordDecl *RD = RT->getDecl();
2753
2754 // Assume variable sized types are passed in memory.
2755 if (RD->hasFlexibleArrayMember())
2756 return;
2757
Chris Lattner2b037972010-07-29 02:01:43 +00002758 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002759
2760 // Reset Lo class, this will be recomputed.
2761 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002762
2763 // If this is a C++ record, classify the bases first.
2764 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002765 for (const auto &I : CXXRD->bases()) {
2766 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002767 "Unexpected base class!");
2768 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002769 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002770
2771 // Classify this field.
2772 //
2773 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2774 // single eightbyte, each is classified separately. Each eightbyte gets
2775 // initialized to class NO_CLASS.
2776 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002777 uint64_t Offset =
2778 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002779 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002780 Lo = merge(Lo, FieldLo);
2781 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002782 if (Lo == Memory || Hi == Memory) {
2783 postMerge(Size, Lo, Hi);
2784 return;
2785 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002786 }
2787 }
2788
2789 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002790 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002791 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002792 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002793 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2794 bool BitField = i->isBitField();
2795
David Majnemerb439dfe2016-08-15 07:20:40 +00002796 // Ignore padding bit-fields.
2797 if (BitField && i->isUnnamedBitfield())
2798 continue;
2799
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002800 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2801 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002802 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002803 // The only case a 256-bit wide vector could be used is when the struct
2804 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2805 // to work for sizes wider than 128, early check and fallback to memory.
2806 //
David Majnemerb229cb02016-08-15 06:39:18 +00002807 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2808 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002809 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002810 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002811 return;
2812 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002813 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002814 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002816 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002817 return;
2818 }
2819
2820 // Classify this field.
2821 //
2822 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2823 // exceeds a single eightbyte, each is classified
2824 // separately. Each eightbyte gets initialized to class
2825 // NO_CLASS.
2826 Class FieldLo, FieldHi;
2827
2828 // Bit-fields require special handling, they do not force the
2829 // structure to be passed in memory even if unaligned, and
2830 // therefore they can straddle an eightbyte.
2831 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002832 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002833 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002834 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835
2836 uint64_t EB_Lo = Offset / 64;
2837 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002838
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002839 if (EB_Lo) {
2840 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2841 FieldLo = NoClass;
2842 FieldHi = Integer;
2843 } else {
2844 FieldLo = Integer;
2845 FieldHi = EB_Hi ? Integer : NoClass;
2846 }
2847 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002848 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002849 Lo = merge(Lo, FieldLo);
2850 Hi = merge(Hi, FieldHi);
2851 if (Lo == Memory || Hi == Memory)
2852 break;
2853 }
2854
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002855 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002856 }
2857}
2858
Chris Lattner22a931e2010-06-29 06:01:59 +00002859ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002860 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2861 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002862 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002863 // Treat an enum type as its underlying type.
2864 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2865 Ty = EnumTy->getDecl()->getIntegerType();
2866
Alex Bradburye41a5e22018-01-12 20:08:16 +00002867 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2868 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002869 }
2870
John McCall7f416cc2015-09-08 08:05:57 +00002871 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002872}
2873
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002874bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2875 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2876 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002877 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002878 if (Size <= 64 || Size > LargestVector)
2879 return true;
2880 }
2881
2882 return false;
2883}
2884
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002885ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2886 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002887 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2888 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002889 //
2890 // This assumption is optimistic, as there could be free registers available
2891 // when we need to pass this argument in memory, and LLVM could try to pass
2892 // the argument in the free register. This does not seem to happen currently,
2893 // but this code would be much safer if we could mark the argument with
2894 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002895 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002896 // Treat an enum type as its underlying type.
2897 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2898 Ty = EnumTy->getDecl()->getIntegerType();
2899
Alex Bradburye41a5e22018-01-12 20:08:16 +00002900 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2901 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002902 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002903
Mark Lacey3825e832013-10-06 01:33:34 +00002904 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002905 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002906
Chris Lattner44c2b902011-05-22 23:21:23 +00002907 // Compute the byval alignment. We specify the alignment of the byval in all
2908 // cases so that the mid-level optimizer knows the alignment of the byval.
2909 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002910
2911 // Attempt to avoid passing indirect results using byval when possible. This
2912 // is important for good codegen.
2913 //
2914 // We do this by coercing the value into a scalar type which the backend can
2915 // handle naturally (i.e., without using byval).
2916 //
2917 // For simplicity, we currently only do this when we have exhausted all of the
2918 // free integer registers. Doing this when there are free integer registers
2919 // would require more care, as we would have to ensure that the coerced value
2920 // did not claim the unused register. That would require either reording the
2921 // arguments to the function (so that any subsequent inreg values came first),
2922 // or only doing this optimization when there were no following arguments that
2923 // might be inreg.
2924 //
2925 // We currently expect it to be rare (particularly in well written code) for
2926 // arguments to be passed on the stack when there are still free integer
2927 // registers available (this would typically imply large structs being passed
2928 // by value), so this seems like a fair tradeoff for now.
2929 //
2930 // We can revisit this if the backend grows support for 'onstack' parameter
2931 // attributes. See PR12193.
2932 if (freeIntRegs == 0) {
2933 uint64_t Size = getContext().getTypeSize(Ty);
2934
2935 // If this type fits in an eightbyte, coerce it into the matching integral
2936 // type, which will end up on the stack (with alignment 8).
2937 if (Align == 8 && Size <= 64)
2938 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2939 Size));
2940 }
2941
John McCall7f416cc2015-09-08 08:05:57 +00002942 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002943}
2944
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002945/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2946/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002947llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002948 // Wrapper structs/arrays that only contain vectors are passed just like
2949 // vectors; strip them off if present.
2950 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2951 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002952
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002953 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002954 if (isa<llvm::VectorType>(IRType) ||
2955 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002956 return IRType;
2957
2958 // We couldn't find the preferred IR vector type for 'Ty'.
2959 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002960 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002961
2962 // Return a LLVM IR vector type based on the size of 'Ty'.
2963 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2964 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002965}
2966
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002967/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2968/// is known to either be off the end of the specified type or being in
2969/// alignment padding. The user type specified is known to be at most 128 bits
2970/// in size, and have passed through X86_64ABIInfo::classify with a successful
2971/// classification that put one of the two halves in the INTEGER class.
2972///
2973/// It is conservatively correct to return false.
2974static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2975 unsigned EndBit, ASTContext &Context) {
2976 // If the bytes being queried are off the end of the type, there is no user
2977 // data hiding here. This handles analysis of builtins, vectors and other
2978 // types that don't contain interesting padding.
2979 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2980 if (TySize <= StartBit)
2981 return true;
2982
Chris Lattner98076a22010-07-29 07:43:55 +00002983 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2984 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2985 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2986
2987 // Check each element to see if the element overlaps with the queried range.
2988 for (unsigned i = 0; i != NumElts; ++i) {
2989 // If the element is after the span we care about, then we're done..
2990 unsigned EltOffset = i*EltSize;
2991 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002992
Chris Lattner98076a22010-07-29 07:43:55 +00002993 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2994 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2995 EndBit-EltOffset, Context))
2996 return false;
2997 }
2998 // If it overlaps no elements, then it is safe to process as padding.
2999 return true;
3000 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003001
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003002 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3003 const RecordDecl *RD = RT->getDecl();
3004 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003005
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003006 // If this is a C++ record, check the bases first.
3007 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003008 for (const auto &I : CXXRD->bases()) {
3009 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003010 "Unexpected base class!");
3011 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003012 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003013
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003014 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003015 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003016 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003017
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003018 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003019 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003020 EndBit-BaseOffset, Context))
3021 return false;
3022 }
3023 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003024
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003025 // Verify that no field has data that overlaps the region of interest. Yes
3026 // this could be sped up a lot by being smarter about queried fields,
3027 // however we're only looking at structs up to 16 bytes, so we don't care
3028 // much.
3029 unsigned idx = 0;
3030 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3031 i != e; ++i, ++idx) {
3032 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003033
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003034 // If we found a field after the region we care about, then we're done.
3035 if (FieldOffset >= EndBit) break;
3036
3037 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3038 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3039 Context))
3040 return false;
3041 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003042
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003043 // If nothing in this record overlapped the area of interest, then we're
3044 // clean.
3045 return true;
3046 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003047
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003048 return false;
3049}
3050
Chris Lattnere556a712010-07-29 18:39:32 +00003051/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3052/// float member at the specified offset. For example, {int,{float}} has a
3053/// float at offset 4. It is conservatively correct for this routine to return
3054/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003055static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003056 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003057 // Base case if we find a float.
3058 if (IROffset == 0 && IRType->isFloatTy())
3059 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003060
Chris Lattnere556a712010-07-29 18:39:32 +00003061 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003062 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003063 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3064 unsigned Elt = SL->getElementContainingOffset(IROffset);
3065 IROffset -= SL->getElementOffset(Elt);
3066 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3067 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003068
Chris Lattnere556a712010-07-29 18:39:32 +00003069 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003070 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3071 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003072 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3073 IROffset -= IROffset/EltSize*EltSize;
3074 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3075 }
3076
3077 return false;
3078}
3079
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003080
3081/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3082/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003083llvm::Type *X86_64ABIInfo::
3084GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003085 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003086 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003087 // pass as float if the last 4 bytes is just padding. This happens for
3088 // structs that contain 3 floats.
3089 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3090 SourceOffset*8+64, getContext()))
3091 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003092
Chris Lattnere556a712010-07-29 18:39:32 +00003093 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3094 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3095 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003096 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3097 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003098 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003099
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003100 return llvm::Type::getDoubleTy(getVMContext());
3101}
3102
3103
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003104/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3105/// an 8-byte GPR. This means that we either have a scalar or we are talking
3106/// about the high or low part of an up-to-16-byte struct. This routine picks
3107/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003108/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3109/// etc).
3110///
3111/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3112/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3113/// the 8-byte value references. PrefType may be null.
3114///
Alp Toker9907f082014-07-09 14:06:35 +00003115/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003116/// an offset into this that we're processing (which is always either 0 or 8).
3117///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003118llvm::Type *X86_64ABIInfo::
3119GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003120 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003121 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3122 // returning an 8-byte unit starting with it. See if we can safely use it.
3123 if (IROffset == 0) {
3124 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003125 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3126 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003127 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003128
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003129 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3130 // goodness in the source type is just tail padding. This is allowed to
3131 // kick in for struct {double,int} on the int, but not on
3132 // struct{double,int,int} because we wouldn't return the second int. We
3133 // have to do this analysis on the source type because we can't depend on
3134 // unions being lowered a specific way etc.
3135 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003136 IRType->isIntegerTy(32) ||
3137 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3138 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3139 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003140
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003141 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3142 SourceOffset*8+64, getContext()))
3143 return IRType;
3144 }
3145 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003146
Chris Lattner2192fe52011-07-18 04:24:23 +00003147 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003148 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003149 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003150 if (IROffset < SL->getSizeInBytes()) {
3151 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3152 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003153
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003154 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3155 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003156 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003157 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003158
Chris Lattner2192fe52011-07-18 04:24:23 +00003159 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003160 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003161 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003162 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003163 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3164 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003165 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003166
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003167 // Okay, we don't have any better idea of what to pass, so we pass this in an
3168 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003169 unsigned TySizeInBytes =
3170 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003171
Chris Lattner3f763422010-07-29 17:34:39 +00003172 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003173
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003174 // It is always safe to classify this as an integer type up to i64 that
3175 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003176 return llvm::IntegerType::get(getVMContext(),
3177 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003178}
3179
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003180
3181/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3182/// be used as elements of a two register pair to pass or return, return a
3183/// first class aggregate to represent them. For example, if the low part of
3184/// a by-value argument should be passed as i32* and the high part as float,
3185/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003186static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003187GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003188 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003189 // In order to correctly satisfy the ABI, we need to the high part to start
3190 // at offset 8. If the high and low parts we inferred are both 4-byte types
3191 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3192 // the second element at offset 8. Check for this:
3193 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3194 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003195 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003196 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003197
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003198 // To handle this, we have to increase the size of the low part so that the
3199 // second element will start at an 8 byte offset. We can't increase the size
3200 // of the second element because it might make us access off the end of the
3201 // struct.
3202 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003203 // There are usually two sorts of types the ABI generation code can produce
3204 // for the low part of a pair that aren't 8 bytes in size: float or
3205 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3206 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003207 // Promote these to a larger type.
3208 if (Lo->isFloatTy())
3209 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3210 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003211 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3212 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003213 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3214 }
3215 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003216
Serge Guelton1d993272017-05-09 19:31:30 +00003217 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003218
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003219 // Verify that the second element is at an 8-byte offset.
3220 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3221 "Invalid x86-64 argument pair!");
3222 return Result;
3223}
3224
Chris Lattner31faff52010-07-28 23:06:14 +00003225ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003226classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003227 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3228 // classification algorithm.
3229 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003230 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003231
3232 // Check some invariants.
3233 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003234 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3235
Craig Topper8a13c412014-05-21 05:09:00 +00003236 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003237 switch (Lo) {
3238 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003239 if (Hi == NoClass)
3240 return ABIArgInfo::getIgnore();
3241 // If the low part is just padding, it takes no register, leave ResType
3242 // null.
3243 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3244 "Unknown missing lo part");
3245 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003246
3247 case SSEUp:
3248 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003249 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003250
3251 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3252 // hidden argument.
3253 case Memory:
3254 return getIndirectReturnResult(RetTy);
3255
3256 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3257 // available register of the sequence %rax, %rdx is used.
3258 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003259 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003260
Chris Lattner1f3a0632010-07-29 21:42:50 +00003261 // If we have a sign or zero extended integer, make sure to return Extend
3262 // so that the parameter gets the right LLVM IR attributes.
3263 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3264 // Treat an enum type as its underlying type.
3265 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3266 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003267
Chris Lattner1f3a0632010-07-29 21:42:50 +00003268 if (RetTy->isIntegralOrEnumerationType() &&
3269 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003270 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003271 }
Chris Lattner31faff52010-07-28 23:06:14 +00003272 break;
3273
3274 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3275 // available SSE register of the sequence %xmm0, %xmm1 is used.
3276 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003277 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003278 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003279
3280 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3281 // returned on the X87 stack in %st0 as 80-bit x87 number.
3282 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003283 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003284 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003285
3286 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3287 // part of the value is returned in %st0 and the imaginary part in
3288 // %st1.
3289 case ComplexX87:
3290 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003291 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003292 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003293 break;
3294 }
3295
Craig Topper8a13c412014-05-21 05:09:00 +00003296 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003297 switch (Hi) {
3298 // Memory was handled previously and X87 should
3299 // never occur as a hi class.
3300 case Memory:
3301 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003302 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003303
3304 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003305 case NoClass:
3306 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003307
Chris Lattner52b3c132010-09-01 00:20:33 +00003308 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003309 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003310 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3311 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003312 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003313 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003314 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003315 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3316 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003317 break;
3318
3319 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003320 // is passed in the next available eightbyte chunk if the last used
3321 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003322 //
Chris Lattner57540c52011-04-15 05:22:18 +00003323 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003324 case SSEUp:
3325 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003326 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003327 break;
3328
3329 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3330 // returned together with the previous X87 value in %st0.
3331 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003332 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003333 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003334 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003335 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003336 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003337 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003338 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3339 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003340 }
Chris Lattner31faff52010-07-28 23:06:14 +00003341 break;
3342 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003343
Chris Lattner52b3c132010-09-01 00:20:33 +00003344 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003345 // known to pass in the high eightbyte of the result. We do this by forming a
3346 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003347 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003348 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003349
Chris Lattner1f3a0632010-07-29 21:42:50 +00003350 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003351}
3352
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003353ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003354 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3355 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003356 const
3357{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003358 Ty = useFirstFieldIfTransparentUnion(Ty);
3359
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003360 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003361 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003362
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003363 // Check some invariants.
3364 // FIXME: Enforce these by construction.
3365 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3367
3368 neededInt = 0;
3369 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003370 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003371 switch (Lo) {
3372 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003373 if (Hi == NoClass)
3374 return ABIArgInfo::getIgnore();
3375 // If the low part is just padding, it takes no register, leave ResType
3376 // null.
3377 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3378 "Unknown missing lo part");
3379 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003380
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003381 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3382 // on the stack.
3383 case Memory:
3384
3385 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3386 // COMPLEX_X87, it is passed in memory.
3387 case X87:
3388 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003389 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003390 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003391 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003392
3393 case SSEUp:
3394 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003395 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003396
3397 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3398 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3399 // and %r9 is used.
3400 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003401 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003402
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003403 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003404 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003405
3406 // If we have a sign or zero extended integer, make sure to return Extend
3407 // so that the parameter gets the right LLVM IR attributes.
3408 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3409 // Treat an enum type as its underlying type.
3410 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3411 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003412
Chris Lattner1f3a0632010-07-29 21:42:50 +00003413 if (Ty->isIntegralOrEnumerationType() &&
3414 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003415 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003416 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003417
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003418 break;
3419
3420 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3421 // available SSE register is used, the registers are taken in the
3422 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003423 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003424 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003425 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003426 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003427 break;
3428 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003429 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003430
Craig Topper8a13c412014-05-21 05:09:00 +00003431 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003432 switch (Hi) {
3433 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003434 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003435 // which is passed in memory.
3436 case Memory:
3437 case X87:
3438 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003439 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440
3441 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003442
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003443 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003444 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003445 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003446 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003447
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003448 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3449 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450 break;
3451
3452 // X87Up generally doesn't occur here (long double is passed in
3453 // memory), except in situations involving unions.
3454 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003455 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003456 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003457
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003458 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3459 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003460
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003461 ++neededSSE;
3462 break;
3463
3464 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3465 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003466 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003467 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003468 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003469 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003470 break;
3471 }
3472
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003473 // If a high part was specified, merge it together with the low part. It is
3474 // known to pass in the high eightbyte of the result. We do this by forming a
3475 // first class struct aggregate with the high and low part: {low, high}
3476 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003477 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003478
Chris Lattner1f3a0632010-07-29 21:42:50 +00003479 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003480}
3481
Erich Keane757d3172016-11-02 18:29:35 +00003482ABIArgInfo
3483X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3484 unsigned &NeededSSE) const {
3485 auto RT = Ty->getAs<RecordType>();
3486 assert(RT && "classifyRegCallStructType only valid with struct types");
3487
3488 if (RT->getDecl()->hasFlexibleArrayMember())
3489 return getIndirectReturnResult(Ty);
3490
3491 // Sum up bases
3492 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3493 if (CXXRD->isDynamicClass()) {
3494 NeededInt = NeededSSE = 0;
3495 return getIndirectReturnResult(Ty);
3496 }
3497
3498 for (const auto &I : CXXRD->bases())
3499 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3500 .isIndirect()) {
3501 NeededInt = NeededSSE = 0;
3502 return getIndirectReturnResult(Ty);
3503 }
3504 }
3505
3506 // Sum up members
3507 for (const auto *FD : RT->getDecl()->fields()) {
3508 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3509 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3510 .isIndirect()) {
3511 NeededInt = NeededSSE = 0;
3512 return getIndirectReturnResult(Ty);
3513 }
3514 } else {
3515 unsigned LocalNeededInt, LocalNeededSSE;
3516 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3517 LocalNeededSSE, true)
3518 .isIndirect()) {
3519 NeededInt = NeededSSE = 0;
3520 return getIndirectReturnResult(Ty);
3521 }
3522 NeededInt += LocalNeededInt;
3523 NeededSSE += LocalNeededSSE;
3524 }
3525 }
3526
3527 return ABIArgInfo::getDirect();
3528}
3529
3530ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3531 unsigned &NeededInt,
3532 unsigned &NeededSSE) const {
3533
3534 NeededInt = 0;
3535 NeededSSE = 0;
3536
3537 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3538}
3539
Chris Lattner22326a12010-07-29 02:31:05 +00003540void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003541
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003542 const unsigned CallingConv = FI.getCallingConvention();
3543 // It is possible to force Win64 calling convention on any x86_64 target by
3544 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3545 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3546 if (CallingConv == llvm::CallingConv::Win64) {
3547 WinX86_64ABIInfo Win64ABIInfo(CGT);
3548 Win64ABIInfo.computeInfo(FI);
3549 return;
3550 }
3551
3552 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003553
3554 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003555 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3556 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3557 unsigned NeededInt, NeededSSE;
3558
Akira Hatanakad791e922018-03-19 17:38:40 +00003559 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003560 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3561 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3562 FI.getReturnInfo() =
3563 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3564 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3565 FreeIntRegs -= NeededInt;
3566 FreeSSERegs -= NeededSSE;
3567 } else {
3568 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3569 }
3570 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3571 // Complex Long Double Type is passed in Memory when Regcall
3572 // calling convention is used.
3573 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3574 if (getContext().getCanonicalType(CT->getElementType()) ==
3575 getContext().LongDoubleTy)
3576 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3577 } else
3578 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3579 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003580
3581 // If the return value is indirect, then the hidden argument is consuming one
3582 // integer register.
3583 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003584 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585
Peter Collingbournef7706832014-12-12 23:41:25 +00003586 // The chain argument effectively gives us another free register.
3587 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003588 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003589
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003590 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003591 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3592 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003593 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003594 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003595 it != ie; ++it, ++ArgNo) {
3596 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003597
Erich Keane757d3172016-11-02 18:29:35 +00003598 if (IsRegCall && it->type->isStructureOrClassType())
3599 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3600 else
3601 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3602 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003603
3604 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3605 // eightbyte of an argument, the whole argument is passed on the
3606 // stack. If registers have already been assigned for some
3607 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003608 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3609 FreeIntRegs -= NeededInt;
3610 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003611 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003612 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003613 }
3614 }
3615}
3616
John McCall7f416cc2015-09-08 08:05:57 +00003617static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3618 Address VAListAddr, QualType Ty) {
3619 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3620 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003621 llvm::Value *overflow_arg_area =
3622 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3623
3624 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3625 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003626 // It isn't stated explicitly in the standard, but in practice we use
3627 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003628 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3629 if (Align > CharUnits::fromQuantity(8)) {
3630 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3631 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003632 }
3633
3634 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003635 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003636 llvm::Value *Res =
3637 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003638 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639
3640 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3641 // l->overflow_arg_area + sizeof(type).
3642 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3643 // an 8 byte boundary.
3644
3645 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003646 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003647 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003648 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3649 "overflow_arg_area.next");
3650 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3651
3652 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003653 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654}
3655
John McCall7f416cc2015-09-08 08:05:57 +00003656Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3657 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003658 // Assume that va_list type is correct; should be pointer to LLVM type:
3659 // struct {
3660 // i32 gp_offset;
3661 // i32 fp_offset;
3662 // i8* overflow_arg_area;
3663 // i8* reg_save_area;
3664 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003665 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003666
John McCall7f416cc2015-09-08 08:05:57 +00003667 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003668 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003669 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003670
3671 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3672 // in the registers. If not go to step 7.
3673 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003674 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003675
3676 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3677 // general purpose registers needed to pass type and num_fp to hold
3678 // the number of floating point registers needed.
3679
3680 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3681 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3682 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3683 //
3684 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3685 // register save space).
3686
Craig Topper8a13c412014-05-21 05:09:00 +00003687 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003688 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3689 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003690 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003691 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003692 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3693 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003694 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003695 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3696 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003697 }
3698
3699 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003700 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003701 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3702 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003703 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3704 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003705 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3706 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003707 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3708 }
3709
3710 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3711 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3712 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3713 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3714
3715 // Emit code to load the value if it was passed in registers.
3716
3717 CGF.EmitBlock(InRegBlock);
3718
3719 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3720 // an offset of l->gp_offset and/or l->fp_offset. This may require
3721 // copying to a temporary location in case the parameter is passed
3722 // in different register classes or requires an alignment greater
3723 // than 8 for general purpose registers and 16 for XMM registers.
3724 //
3725 // FIXME: This really results in shameful code when we end up needing to
3726 // collect arguments from different places; often what should result in a
3727 // simple assembling of a structure from scattered addresses has many more
3728 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003729 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003730 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3731 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3732 "reg_save_area");
3733
3734 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003735 if (neededInt && neededSSE) {
3736 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003737 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003738 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003739 Address Tmp = CGF.CreateMemTemp(Ty);
3740 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003741 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003742 llvm::Type *TyLo = ST->getElementType(0);
3743 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003744 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003745 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003746 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3747 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003748 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3749 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003750 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3751 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752
John McCall7f416cc2015-09-08 08:05:57 +00003753 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003754 // FIXME: Our choice of alignment here and below is probably pessimistic.
3755 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3756 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3757 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003758 CGF.Builder.CreateStore(V,
3759 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3760
3761 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003762 V = CGF.Builder.CreateAlignedLoad(
3763 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3764 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003765 CharUnits Offset = CharUnits::fromQuantity(
3766 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3767 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3768
3769 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003770 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003771 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3772 CharUnits::fromQuantity(8));
3773 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003774
3775 // Copy to a temporary if necessary to ensure the appropriate alignment.
3776 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003777 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003778 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003779 CharUnits TyAlign = SizeAlign.second;
3780
3781 // Copy into a temporary if the type is more aligned than the
3782 // register save area.
3783 if (TyAlign.getQuantity() > 8) {
3784 Address Tmp = CGF.CreateMemTemp(Ty);
3785 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003786 RegAddr = Tmp;
3787 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003788
Chris Lattner0cf24192010-06-28 20:05:43 +00003789 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003790 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3791 CharUnits::fromQuantity(16));
3792 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003793 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003794 assert(neededSSE == 2 && "Invalid number of needed registers!");
3795 // SSE registers are spaced 16 bytes apart in the register save
3796 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003797 // The ABI isn't explicit about this, but it seems reasonable
3798 // to assume that the slots are 16-byte aligned, since the stack is
3799 // naturally 16-byte aligned and the prologue is expected to store
3800 // all the SSE registers to the RSA.
3801 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3802 CharUnits::fromQuantity(16));
3803 Address RegAddrHi =
3804 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3805 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003806 llvm::Type *ST = AI.canHaveCoerceToType()
3807 ? AI.getCoerceToType()
3808 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003809 llvm::Value *V;
3810 Address Tmp = CGF.CreateMemTemp(Ty);
3811 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003812 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3813 RegAddrLo, ST->getStructElementType(0)));
John McCall7f416cc2015-09-08 08:05:57 +00003814 CGF.Builder.CreateStore(V,
3815 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
Erich Keane24e68402018-02-02 15:53:35 +00003816 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3817 RegAddrHi, ST->getStructElementType(1)));
John McCall7f416cc2015-09-08 08:05:57 +00003818 CGF.Builder.CreateStore(V,
3819 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3820
3821 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003822 }
3823
3824 // AMD64-ABI 3.5.7p5: Step 5. Set:
3825 // l->gp_offset = l->gp_offset + num_gp * 8
3826 // l->fp_offset = l->fp_offset + num_fp * 16.
3827 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003828 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003829 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3830 gp_offset_p);
3831 }
3832 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003833 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003834 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3835 fp_offset_p);
3836 }
3837 CGF.EmitBranch(ContBlock);
3838
3839 // Emit code to load the value if it was passed in memory.
3840
3841 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003842 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003843
3844 // Return the appropriate result.
3845
3846 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003847 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3848 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003849 return ResAddr;
3850}
3851
Charles Davisc7d5c942015-09-17 20:55:33 +00003852Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3853 QualType Ty) const {
3854 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3855 CGF.getContext().getTypeInfoInChars(Ty),
3856 CharUnits::fromQuantity(8),
3857 /*allowHigherAlign*/ false);
3858}
3859
Erich Keane521ed962017-01-05 00:20:51 +00003860ABIArgInfo
3861WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3862 const ABIArgInfo &current) const {
3863 // Assumes vectorCall calling convention.
3864 const Type *Base = nullptr;
3865 uint64_t NumElts = 0;
3866
3867 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3868 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3869 FreeSSERegs -= NumElts;
3870 return getDirectX86Hva();
3871 }
3872 return current;
3873}
3874
Reid Kleckner80944df2014-10-31 22:00:51 +00003875ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003876 bool IsReturnType, bool IsVectorCall,
3877 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003878
3879 if (Ty->isVoidType())
3880 return ABIArgInfo::getIgnore();
3881
3882 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3883 Ty = EnumTy->getDecl()->getIntegerType();
3884
Reid Kleckner80944df2014-10-31 22:00:51 +00003885 TypeInfo Info = getContext().getTypeInfo(Ty);
3886 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003887 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003888
Reid Kleckner9005f412014-05-02 00:51:20 +00003889 const RecordType *RT = Ty->getAs<RecordType>();
3890 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003891 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003892 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003893 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003894 }
3895
3896 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003897 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003898
Reid Kleckner9005f412014-05-02 00:51:20 +00003899 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003900
Reid Kleckner80944df2014-10-31 22:00:51 +00003901 const Type *Base = nullptr;
3902 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003903 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3904 // other targets.
3905 if ((IsVectorCall || IsRegCall) &&
3906 isHomogeneousAggregate(Ty, Base, NumElts)) {
3907 if (IsRegCall) {
3908 if (FreeSSERegs >= NumElts) {
3909 FreeSSERegs -= NumElts;
3910 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3911 return ABIArgInfo::getDirect();
3912 return ABIArgInfo::getExpand();
3913 }
3914 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3915 } else if (IsVectorCall) {
3916 if (FreeSSERegs >= NumElts &&
3917 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3918 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003919 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003920 } else if (IsReturnType) {
3921 return ABIArgInfo::getExpand();
3922 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3923 // HVAs are delayed and reclassified in the 2nd step.
3924 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3925 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003926 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003927 }
3928
Reid Klecknerec87fec2014-05-02 01:17:12 +00003929 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003930 // If the member pointer is represented by an LLVM int or ptr, pass it
3931 // directly.
3932 llvm::Type *LLTy = CGT.ConvertType(Ty);
3933 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3934 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003935 }
3936
Michael Kuperstein4f818702015-02-24 09:35:58 +00003937 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003938 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3939 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003940 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003941 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003942
Reid Kleckner9005f412014-05-02 00:51:20 +00003943 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003944 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003945 }
3946
Reid Kleckner08f64e92018-10-31 17:43:55 +00003947 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3948 switch (BT->getKind()) {
3949 case BuiltinType::Bool:
3950 // Bool type is always extended to the ABI, other builtin types are not
3951 // extended.
3952 return ABIArgInfo::getExtend(Ty);
3953
3954 case BuiltinType::LongDouble:
3955 // Mingw64 GCC uses the old 80 bit extended precision floating point
3956 // unit. It passes them indirectly through memory.
3957 if (IsMingw64) {
3958 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3959 if (LDF == &llvm::APFloat::x87DoubleExtended())
3960 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3961 }
3962 break;
3963
3964 case BuiltinType::Int128:
3965 case BuiltinType::UInt128:
3966 // If it's a parameter type, the normal ABI rule is that arguments larger
3967 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3968 // even though it isn't particularly efficient.
3969 if (!IsReturnType)
3970 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3971
3972 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3973 // Clang matches them for compatibility.
3974 return ABIArgInfo::getDirect(
3975 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
3976
3977 default:
3978 break;
3979 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003980 }
3981
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003982 return ABIArgInfo::getDirect();
3983}
3984
Erich Keane521ed962017-01-05 00:20:51 +00003985void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3986 unsigned FreeSSERegs,
3987 bool IsVectorCall,
3988 bool IsRegCall) const {
3989 unsigned Count = 0;
3990 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003991 // Vectorcall in x64 only permits the first 6 arguments to be passed
3992 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003993 if (Count < VectorcallMaxParamNumAsReg)
3994 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3995 else {
3996 // Since these cannot be passed in registers, pretend no registers
3997 // are left.
3998 unsigned ZeroSSERegsAvail = 0;
3999 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4000 IsVectorCall, IsRegCall);
4001 }
4002 ++Count;
4003 }
4004
Erich Keane521ed962017-01-05 00:20:51 +00004005 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004006 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004007 }
4008}
4009
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004010void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00004011 bool IsVectorCall =
4012 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00004013 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00004014
Erich Keane757d3172016-11-02 18:29:35 +00004015 unsigned FreeSSERegs = 0;
4016 if (IsVectorCall) {
4017 // We can use up to 4 SSE return registers with vectorcall.
4018 FreeSSERegs = 4;
4019 } else if (IsRegCall) {
4020 // RegCall gives us 16 SSE registers.
4021 FreeSSERegs = 16;
4022 }
4023
Reid Kleckner80944df2014-10-31 22:00:51 +00004024 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004025 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4026 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004027
Erich Keane757d3172016-11-02 18:29:35 +00004028 if (IsVectorCall) {
4029 // We can use up to 6 SSE register parameters with vectorcall.
4030 FreeSSERegs = 6;
4031 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004032 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004033 FreeSSERegs = 16;
4034 }
4035
Erich Keane521ed962017-01-05 00:20:51 +00004036 if (IsVectorCall) {
4037 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4038 } else {
4039 for (auto &I : FI.arguments())
4040 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4041 }
4042
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004043}
4044
John McCall7f416cc2015-09-08 08:05:57 +00004045Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4046 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004047
4048 bool IsIndirect = false;
4049
4050 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4051 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4052 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4053 uint64_t Width = getContext().getTypeSize(Ty);
4054 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4055 }
4056
4057 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004058 CGF.getContext().getTypeInfoInChars(Ty),
4059 CharUnits::fromQuantity(8),
4060 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004061}
Chris Lattner0cf24192010-06-28 20:05:43 +00004062
John McCallea8d8bb2010-03-11 00:10:12 +00004063// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004064namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004065/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4066class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004067 bool IsSoftFloatABI;
4068
4069 CharUnits getParamTypeAlignment(QualType Ty) const;
4070
John McCallea8d8bb2010-03-11 00:10:12 +00004071public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004072 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4073 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004074
John McCall7f416cc2015-09-08 08:05:57 +00004075 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4076 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004077};
4078
4079class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4080public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004081 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4082 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004083
Craig Topper4f12f102014-03-12 06:41:41 +00004084 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004085 // This is recovered from gcc output.
4086 return 1; // r1 is the dedicated stack pointer
4087 }
4088
4089 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004090 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004091};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004092}
John McCallea8d8bb2010-03-11 00:10:12 +00004093
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004094CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4095 // Complex types are passed just like their elements
4096 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4097 Ty = CTy->getElementType();
4098
4099 if (Ty->isVectorType())
4100 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4101 : 4);
4102
4103 // For single-element float/vector structs, we consider the whole type
4104 // to have the same alignment requirements as its single element.
4105 const Type *AlignTy = nullptr;
4106 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4107 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4108 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4109 (BT && BT->isFloatingPoint()))
4110 AlignTy = EltType;
4111 }
4112
4113 if (AlignTy)
4114 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4115 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004116}
John McCallea8d8bb2010-03-11 00:10:12 +00004117
James Y Knight29b5f082016-02-24 02:59:33 +00004118// TODO: this implementation is now likely redundant with
4119// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004120Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4121 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004122 if (getTarget().getTriple().isOSDarwin()) {
4123 auto TI = getContext().getTypeInfoInChars(Ty);
4124 TI.second = getParamTypeAlignment(Ty);
4125
4126 CharUnits SlotSize = CharUnits::fromQuantity(4);
4127 return emitVoidPtrVAArg(CGF, VAList, Ty,
4128 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4129 /*AllowHigherAlign=*/true);
4130 }
4131
Roman Divacky039b9702016-02-20 08:31:24 +00004132 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004133 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4134 // TODO: Implement this. For now ignore.
4135 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004136 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004137 }
4138
John McCall7f416cc2015-09-08 08:05:57 +00004139 // struct __va_list_tag {
4140 // unsigned char gpr;
4141 // unsigned char fpr;
4142 // unsigned short reserved;
4143 // void *overflow_arg_area;
4144 // void *reg_save_area;
4145 // };
4146
Roman Divacky8a12d842014-11-03 18:32:54 +00004147 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004148 bool isInt =
4149 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004150 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004151
4152 // All aggregates are passed indirectly? That doesn't seem consistent
4153 // with the argument-lowering code.
4154 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004155
4156 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004157
4158 // The calling convention either uses 1-2 GPRs or 1 FPR.
4159 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004160 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004161 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4162 } else {
4163 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004164 }
John McCall7f416cc2015-09-08 08:05:57 +00004165
4166 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4167
4168 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004169 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004170 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4171 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4172 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004173
Eric Christopher7565e0d2015-05-29 23:09:49 +00004174 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004175 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004176
4177 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4178 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4179 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4180
4181 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4182
John McCall7f416cc2015-09-08 08:05:57 +00004183 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4184 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004185
John McCall7f416cc2015-09-08 08:05:57 +00004186 // Case 1: consume registers.
4187 Address RegAddr = Address::invalid();
4188 {
4189 CGF.EmitBlock(UsingRegs);
4190
4191 Address RegSaveAreaPtr =
4192 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4193 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4194 CharUnits::fromQuantity(8));
4195 assert(RegAddr.getElementType() == CGF.Int8Ty);
4196
4197 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004198 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004199 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4200 CharUnits::fromQuantity(32));
4201 }
4202
4203 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004204 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004205 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004206 llvm::Value *RegOffset =
4207 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4208 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4209 RegAddr.getPointer(), RegOffset),
4210 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4211 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4212
4213 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004214 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004215 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004216 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004217 Builder.CreateStore(NumRegs, NumRegsAddr);
4218
4219 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004220 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004221
John McCall7f416cc2015-09-08 08:05:57 +00004222 // Case 2: consume space in the overflow area.
4223 Address MemAddr = Address::invalid();
4224 {
4225 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004226
Roman Divacky039b9702016-02-20 08:31:24 +00004227 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4228
John McCall7f416cc2015-09-08 08:05:57 +00004229 // Everything in the overflow area is rounded up to a size of at least 4.
4230 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4231
4232 CharUnits Size;
4233 if (!isIndirect) {
4234 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004235 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004236 } else {
4237 Size = CGF.getPointerSize();
4238 }
4239
4240 Address OverflowAreaAddr =
4241 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004242 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004243 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004244 // Round up address of argument to alignment
4245 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4246 if (Align > OverflowAreaAlign) {
4247 llvm::Value *Ptr = OverflowArea.getPointer();
4248 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4249 Align);
4250 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004251
John McCall7f416cc2015-09-08 08:05:57 +00004252 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4253
4254 // Increase the overflow area.
4255 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4256 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4257 CGF.EmitBranch(Cont);
4258 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004259
4260 CGF.EmitBlock(Cont);
4261
John McCall7f416cc2015-09-08 08:05:57 +00004262 // Merge the cases with a phi.
4263 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4264 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004265
John McCall7f416cc2015-09-08 08:05:57 +00004266 // Load the pointer if the argument was passed indirectly.
4267 if (isIndirect) {
4268 Result = Address(Builder.CreateLoad(Result, "aggr"),
4269 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004270 }
4271
4272 return Result;
4273}
4274
John McCallea8d8bb2010-03-11 00:10:12 +00004275bool
4276PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4277 llvm::Value *Address) const {
4278 // This is calculated from the LLVM and GCC tables and verified
4279 // against gcc output. AFAIK all ABIs use the same encoding.
4280
4281 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004282
Chris Lattnerece04092012-02-07 00:39:47 +00004283 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004284 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4285 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4286 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4287
4288 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004289 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004290
4291 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004292 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004293
4294 // 64-76 are various 4-byte special-purpose registers:
4295 // 64: mq
4296 // 65: lr
4297 // 66: ctr
4298 // 67: ap
4299 // 68-75 cr0-7
4300 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004301 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004302
4303 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004304 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004305
4306 // 109: vrsave
4307 // 110: vscr
4308 // 111: spe_acc
4309 // 112: spefscr
4310 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004311 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004312
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004313 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004314}
4315
Roman Divackyd966e722012-05-09 18:22:46 +00004316// PowerPC-64
4317
4318namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004319/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004320class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004321public:
4322 enum ABIKind {
4323 ELFv1 = 0,
4324 ELFv2
4325 };
4326
4327private:
4328 static const unsigned GPRBits = 64;
4329 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004330 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004331 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004332
4333 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4334 // will be passed in a QPX register.
4335 bool IsQPXVectorTy(const Type *Ty) const {
4336 if (!HasQPX)
4337 return false;
4338
4339 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4340 unsigned NumElements = VT->getNumElements();
4341 if (NumElements == 1)
4342 return false;
4343
4344 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4345 if (getContext().getTypeSize(Ty) <= 256)
4346 return true;
4347 } else if (VT->getElementType()->
4348 isSpecificBuiltinType(BuiltinType::Float)) {
4349 if (getContext().getTypeSize(Ty) <= 128)
4350 return true;
4351 }
4352 }
4353
4354 return false;
4355 }
4356
4357 bool IsQPXVectorTy(QualType Ty) const {
4358 return IsQPXVectorTy(Ty.getTypePtr());
4359 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004360
4361public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004362 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4363 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004364 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004365 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004366
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004367 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004368 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004369
4370 ABIArgInfo classifyReturnType(QualType RetTy) const;
4371 ABIArgInfo classifyArgumentType(QualType Ty) const;
4372
Reid Klecknere9f6a712014-10-31 17:10:41 +00004373 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4374 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4375 uint64_t Members) const override;
4376
Bill Schmidt84d37792012-10-12 19:26:17 +00004377 // TODO: We can add more logic to computeInfo to improve performance.
4378 // Example: For aggregate arguments that fit in a register, we could
4379 // use getDirectInReg (as is done below for structs containing a single
4380 // floating-point value) to avoid pushing them to memory on function
4381 // entry. This would require changing the logic in PPCISelLowering
4382 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004383 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004384 if (!getCXXABI().classifyReturnType(FI))
4385 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004386 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004387 // We rely on the default argument classification for the most part.
4388 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004389 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004390 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004391 if (T) {
4392 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004393 if (IsQPXVectorTy(T) ||
4394 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004395 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004396 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004397 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004398 continue;
4399 }
4400 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004401 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004402 }
4403 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004404
John McCall7f416cc2015-09-08 08:05:57 +00004405 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4406 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004407
4408 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4409 bool asReturnValue) const override {
4410 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4411 }
4412
4413 bool isSwiftErrorInRegister() const override {
4414 return false;
4415 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004416};
4417
4418class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004419
Bill Schmidt25cb3492012-10-03 19:18:57 +00004420public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004421 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004422 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4423 bool SoftFloatABI)
4424 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4425 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004426
Craig Topper4f12f102014-03-12 06:41:41 +00004427 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004428 // This is recovered from gcc output.
4429 return 1; // r1 is the dedicated stack pointer
4430 }
4431
4432 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004433 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004434};
4435
Roman Divackyd966e722012-05-09 18:22:46 +00004436class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4437public:
4438 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4439
Craig Topper4f12f102014-03-12 06:41:41 +00004440 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004441 // This is recovered from gcc output.
4442 return 1; // r1 is the dedicated stack pointer
4443 }
4444
4445 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004446 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004447};
4448
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004449}
Roman Divackyd966e722012-05-09 18:22:46 +00004450
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004451// Return true if the ABI requires Ty to be passed sign- or zero-
4452// extended to 64 bits.
4453bool
4454PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4455 // Treat an enum type as its underlying type.
4456 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4457 Ty = EnumTy->getDecl()->getIntegerType();
4458
4459 // Promotable integer types are required to be promoted by the ABI.
4460 if (Ty->isPromotableIntegerType())
4461 return true;
4462
4463 // In addition to the usual promotable integer types, we also need to
4464 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4465 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4466 switch (BT->getKind()) {
4467 case BuiltinType::Int:
4468 case BuiltinType::UInt:
4469 return true;
4470 default:
4471 break;
4472 }
4473
4474 return false;
4475}
4476
John McCall7f416cc2015-09-08 08:05:57 +00004477/// isAlignedParamType - Determine whether a type requires 16-byte or
4478/// higher alignment in the parameter area. Always returns at least 8.
4479CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004480 // Complex types are passed just like their elements.
4481 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4482 Ty = CTy->getElementType();
4483
4484 // Only vector types of size 16 bytes need alignment (larger types are
4485 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004486 if (IsQPXVectorTy(Ty)) {
4487 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004488 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004489
John McCall7f416cc2015-09-08 08:05:57 +00004490 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004491 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004492 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004493 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004494
4495 // For single-element float/vector structs, we consider the whole type
4496 // to have the same alignment requirements as its single element.
4497 const Type *AlignAsType = nullptr;
4498 const Type *EltType = isSingleElementStruct(Ty, getContext());
4499 if (EltType) {
4500 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004501 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004502 getContext().getTypeSize(EltType) == 128) ||
4503 (BT && BT->isFloatingPoint()))
4504 AlignAsType = EltType;
4505 }
4506
Ulrich Weigandb7122372014-07-21 00:48:09 +00004507 // Likewise for ELFv2 homogeneous aggregates.
4508 const Type *Base = nullptr;
4509 uint64_t Members = 0;
4510 if (!AlignAsType && Kind == ELFv2 &&
4511 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4512 AlignAsType = Base;
4513
Ulrich Weigand581badc2014-07-10 17:20:07 +00004514 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004515 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4516 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004517 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004518
John McCall7f416cc2015-09-08 08:05:57 +00004519 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004520 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004521 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004522 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004523
4524 // Otherwise, we only need alignment for any aggregate type that
4525 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004526 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4527 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004528 return CharUnits::fromQuantity(32);
4529 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004530 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004531
John McCall7f416cc2015-09-08 08:05:57 +00004532 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004533}
4534
Ulrich Weigandb7122372014-07-21 00:48:09 +00004535/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4536/// aggregate. Base is set to the base element type, and Members is set
4537/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004538bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4539 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004540 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4541 uint64_t NElements = AT->getSize().getZExtValue();
4542 if (NElements == 0)
4543 return false;
4544 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4545 return false;
4546 Members *= NElements;
4547 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4548 const RecordDecl *RD = RT->getDecl();
4549 if (RD->hasFlexibleArrayMember())
4550 return false;
4551
4552 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004553
4554 // If this is a C++ record, check the bases first.
4555 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4556 for (const auto &I : CXXRD->bases()) {
4557 // Ignore empty records.
4558 if (isEmptyRecord(getContext(), I.getType(), true))
4559 continue;
4560
4561 uint64_t FldMembers;
4562 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4563 return false;
4564
4565 Members += FldMembers;
4566 }
4567 }
4568
Ulrich Weigandb7122372014-07-21 00:48:09 +00004569 for (const auto *FD : RD->fields()) {
4570 // Ignore (non-zero arrays of) empty records.
4571 QualType FT = FD->getType();
4572 while (const ConstantArrayType *AT =
4573 getContext().getAsConstantArrayType(FT)) {
4574 if (AT->getSize().getZExtValue() == 0)
4575 return false;
4576 FT = AT->getElementType();
4577 }
4578 if (isEmptyRecord(getContext(), FT, true))
4579 continue;
4580
4581 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4582 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004583 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004584 continue;
4585
4586 uint64_t FldMembers;
4587 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4588 return false;
4589
4590 Members = (RD->isUnion() ?
4591 std::max(Members, FldMembers) : Members + FldMembers);
4592 }
4593
4594 if (!Base)
4595 return false;
4596
4597 // Ensure there is no padding.
4598 if (getContext().getTypeSize(Base) * Members !=
4599 getContext().getTypeSize(Ty))
4600 return false;
4601 } else {
4602 Members = 1;
4603 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4604 Members = 2;
4605 Ty = CT->getElementType();
4606 }
4607
Reid Klecknere9f6a712014-10-31 17:10:41 +00004608 // Most ABIs only support float, double, and some vector type widths.
4609 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004610 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004611
4612 // The base type must be the same for all members. Types that
4613 // agree in both total size and mode (float vs. vector) are
4614 // treated as being equivalent here.
4615 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004616 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004617 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004618 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4619 // so make sure to widen it explicitly.
4620 if (const VectorType *VT = Base->getAs<VectorType>()) {
4621 QualType EltTy = VT->getElementType();
4622 unsigned NumElements =
4623 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4624 Base = getContext()
4625 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4626 .getTypePtr();
4627 }
4628 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004629
4630 if (Base->isVectorType() != TyPtr->isVectorType() ||
4631 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4632 return false;
4633 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004634 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4635}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004636
Reid Klecknere9f6a712014-10-31 17:10:41 +00004637bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4638 // Homogeneous aggregates for ELFv2 must have base types of float,
4639 // double, long double, or 128-bit vectors.
4640 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4641 if (BT->getKind() == BuiltinType::Float ||
4642 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004643 BT->getKind() == BuiltinType::LongDouble ||
4644 (getContext().getTargetInfo().hasFloat128Type() &&
4645 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004646 if (IsSoftFloatABI)
4647 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004648 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004649 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004650 }
4651 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004652 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004653 return true;
4654 }
4655 return false;
4656}
4657
4658bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4659 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004660 // Vector and fp128 types require one register, other floating point types
4661 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004662 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004663 ((getContext().getTargetInfo().hasFloat128Type() &&
4664 Base->isFloat128Type()) ||
4665 Base->isVectorType()) ? 1
4666 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004667
4668 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004669 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004670}
4671
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004672ABIArgInfo
4673PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004674 Ty = useFirstFieldIfTransparentUnion(Ty);
4675
Bill Schmidt90b22c92012-11-27 02:46:43 +00004676 if (Ty->isAnyComplexType())
4677 return ABIArgInfo::getDirect();
4678
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004679 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4680 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004681 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004682 uint64_t Size = getContext().getTypeSize(Ty);
4683 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004684 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004685 else if (Size < 128) {
4686 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4687 return ABIArgInfo::getDirect(CoerceTy);
4688 }
4689 }
4690
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004691 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004692 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004693 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004694
John McCall7f416cc2015-09-08 08:05:57 +00004695 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4696 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004697
4698 // ELFv2 homogeneous aggregates are passed as array types.
4699 const Type *Base = nullptr;
4700 uint64_t Members = 0;
4701 if (Kind == ELFv2 &&
4702 isHomogeneousAggregate(Ty, Base, Members)) {
4703 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4704 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4705 return ABIArgInfo::getDirect(CoerceTy);
4706 }
4707
Ulrich Weigand601957f2014-07-21 00:56:36 +00004708 // If an aggregate may end up fully in registers, we do not
4709 // use the ByVal method, but pass the aggregate as array.
4710 // This is usually beneficial since we avoid forcing the
4711 // back-end to store the argument to memory.
4712 uint64_t Bits = getContext().getTypeSize(Ty);
4713 if (Bits > 0 && Bits <= 8 * GPRBits) {
4714 llvm::Type *CoerceTy;
4715
4716 // Types up to 8 bytes are passed as integer type (which will be
4717 // properly aligned in the argument save area doubleword).
4718 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004719 CoerceTy =
4720 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004721 // Larger types are passed as arrays, with the base type selected
4722 // according to the required alignment in the save area.
4723 else {
4724 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004725 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004726 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4727 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4728 }
4729
4730 return ABIArgInfo::getDirect(CoerceTy);
4731 }
4732
Ulrich Weigandb7122372014-07-21 00:48:09 +00004733 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004734 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4735 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004736 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004737 }
4738
Alex Bradburye41a5e22018-01-12 20:08:16 +00004739 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4740 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004741}
4742
4743ABIArgInfo
4744PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4745 if (RetTy->isVoidType())
4746 return ABIArgInfo::getIgnore();
4747
Bill Schmidta3d121c2012-12-17 04:20:17 +00004748 if (RetTy->isAnyComplexType())
4749 return ABIArgInfo::getDirect();
4750
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004751 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4752 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004753 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004754 uint64_t Size = getContext().getTypeSize(RetTy);
4755 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004756 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004757 else if (Size < 128) {
4758 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4759 return ABIArgInfo::getDirect(CoerceTy);
4760 }
4761 }
4762
Ulrich Weigandb7122372014-07-21 00:48:09 +00004763 if (isAggregateTypeForABI(RetTy)) {
4764 // ELFv2 homogeneous aggregates are returned as array types.
4765 const Type *Base = nullptr;
4766 uint64_t Members = 0;
4767 if (Kind == ELFv2 &&
4768 isHomogeneousAggregate(RetTy, Base, Members)) {
4769 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4770 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4771 return ABIArgInfo::getDirect(CoerceTy);
4772 }
4773
4774 // ELFv2 small aggregates are returned in up to two registers.
4775 uint64_t Bits = getContext().getTypeSize(RetTy);
4776 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4777 if (Bits == 0)
4778 return ABIArgInfo::getIgnore();
4779
4780 llvm::Type *CoerceTy;
4781 if (Bits > GPRBits) {
4782 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004783 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004784 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004785 CoerceTy =
4786 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004787 return ABIArgInfo::getDirect(CoerceTy);
4788 }
4789
4790 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004791 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004792 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004793
Alex Bradburye41a5e22018-01-12 20:08:16 +00004794 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4795 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004796}
4797
Bill Schmidt25cb3492012-10-03 19:18:57 +00004798// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004799Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4800 QualType Ty) const {
4801 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4802 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004803
John McCall7f416cc2015-09-08 08:05:57 +00004804 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004805
Bill Schmidt924c4782013-01-14 17:45:36 +00004806 // If we have a complex type and the base type is smaller than 8 bytes,
4807 // the ABI calls for the real and imaginary parts to be right-adjusted
4808 // in separate doublewords. However, Clang expects us to produce a
4809 // pointer to a structure with the two parts packed tightly. So generate
4810 // loads of the real and imaginary parts relative to the va_list pointer,
4811 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004812 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4813 CharUnits EltSize = TypeInfo.first / 2;
4814 if (EltSize < SlotSize) {
4815 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4816 SlotSize * 2, SlotSize,
4817 SlotSize, /*AllowHigher*/ true);
4818
4819 Address RealAddr = Addr;
4820 Address ImagAddr = RealAddr;
4821 if (CGF.CGM.getDataLayout().isBigEndian()) {
4822 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4823 SlotSize - EltSize);
4824 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4825 2 * SlotSize - EltSize);
4826 } else {
4827 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4828 }
4829
4830 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4831 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4832 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4833 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4834 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4835
4836 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4837 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4838 /*init*/ true);
4839 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004840 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004841 }
4842
John McCall7f416cc2015-09-08 08:05:57 +00004843 // Otherwise, just use the general rule.
4844 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4845 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004846}
4847
4848static bool
4849PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4850 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004851 // This is calculated from the LLVM and GCC tables and verified
4852 // against gcc output. AFAIK all ABIs use the same encoding.
4853
4854 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4855
4856 llvm::IntegerType *i8 = CGF.Int8Ty;
4857 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4858 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4859 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4860
4861 // 0-31: r0-31, the 8-byte general-purpose registers
4862 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4863
4864 // 32-63: fp0-31, the 8-byte floating-point registers
4865 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4866
Hal Finkel84832a72016-08-30 02:38:34 +00004867 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004868 // 64: mq
4869 // 65: lr
4870 // 66: ctr
4871 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004872 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4873
4874 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004875 // 68-75 cr0-7
4876 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004877 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004878
4879 // 77-108: v0-31, the 16-byte vector registers
4880 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4881
4882 // 109: vrsave
4883 // 110: vscr
4884 // 111: spe_acc
4885 // 112: spefscr
4886 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004887 // 114: tfhar
4888 // 115: tfiar
4889 // 116: texasr
4890 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004891
4892 return false;
4893}
John McCallea8d8bb2010-03-11 00:10:12 +00004894
Bill Schmidt25cb3492012-10-03 19:18:57 +00004895bool
4896PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4897 CodeGen::CodeGenFunction &CGF,
4898 llvm::Value *Address) const {
4899
4900 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4901}
4902
4903bool
4904PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4905 llvm::Value *Address) const {
4906
4907 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4908}
4909
Chris Lattner0cf24192010-06-28 20:05:43 +00004910//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004911// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004912//===----------------------------------------------------------------------===//
4913
4914namespace {
4915
John McCall12f23522016-04-04 18:33:08 +00004916class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004917public:
4918 enum ABIKind {
4919 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004920 DarwinPCS,
4921 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004922 };
4923
4924private:
4925 ABIKind Kind;
4926
4927public:
John McCall12f23522016-04-04 18:33:08 +00004928 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4929 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004930
4931private:
4932 ABIKind getABIKind() const { return Kind; }
4933 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4934
4935 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004936 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004937 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4938 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4939 uint64_t Members) const override;
4940
Tim Northovera2ee4332014-03-29 15:09:45 +00004941 bool isIllegalVectorType(QualType Ty) const;
4942
David Blaikie1cbb9712014-11-14 19:09:44 +00004943 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004944 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004945 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004946
Tim Northoverb047bfa2014-11-27 21:02:49 +00004947 for (auto &it : FI.arguments())
4948 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004949 }
4950
John McCall7f416cc2015-09-08 08:05:57 +00004951 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4952 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004953
John McCall7f416cc2015-09-08 08:05:57 +00004954 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4955 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004956
John McCall7f416cc2015-09-08 08:05:57 +00004957 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4958 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004959 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4960 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4961 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004962 }
John McCall12f23522016-04-04 18:33:08 +00004963
Martin Storsjo502de222017-07-13 17:59:14 +00004964 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4965 QualType Ty) const override;
4966
John McCall56331e22018-01-07 06:28:49 +00004967 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004968 bool asReturnValue) const override {
4969 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4970 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004971 bool isSwiftErrorInRegister() const override {
4972 return true;
4973 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004974
4975 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4976 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004977};
4978
Tim Northover573cbee2014-05-24 12:52:07 +00004979class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004980public:
Tim Northover573cbee2014-05-24 12:52:07 +00004981 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4982 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004983
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004984 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004985 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004986 }
4987
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004988 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4989 return 31;
4990 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004991
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004992 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00004993
4994 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4995 CodeGen::CodeGenModule &CGM) const override {
4996 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
4997 if (!FD)
4998 return;
4999 llvm::Function *Fn = cast<llvm::Function>(GV);
5000
5001 auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005002 if (Kind != CodeGenOptions::SignReturnAddressScope::None) {
5003 Fn->addFnAttr("sign-return-address",
5004 Kind == CodeGenOptions::SignReturnAddressScope::All
5005 ? "all"
5006 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005007
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005008 auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5009 Fn->addFnAttr("sign-return-address-key",
5010 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5011 ? "a_key"
5012 : "b_key");
5013 }
5014
5015 if (CGM.getCodeGenOpts().BranchTargetEnforcement)
5016 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005017 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005018};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005019
5020class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5021public:
5022 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5023 : AArch64TargetCodeGenInfo(CGT, K) {}
5024
Eli Friedman540be6d2018-10-26 01:31:57 +00005025 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5026 CodeGen::CodeGenModule &CGM) const override;
5027
Martin Storsjo1c8af272017-07-20 05:47:06 +00005028 void getDependentLibraryOption(llvm::StringRef Lib,
5029 llvm::SmallString<24> &Opt) const override {
5030 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5031 }
5032
5033 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5034 llvm::SmallString<32> &Opt) const override {
5035 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5036 }
5037};
Eli Friedman540be6d2018-10-26 01:31:57 +00005038
5039void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5040 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5041 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5042 if (GV->isDeclaration())
5043 return;
5044 addStackProbeTargetAttributes(D, GV, CGM);
5045}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005046}
Tim Northovera2ee4332014-03-29 15:09:45 +00005047
Tim Northoverb047bfa2014-11-27 21:02:49 +00005048ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005049 Ty = useFirstFieldIfTransparentUnion(Ty);
5050
Tim Northovera2ee4332014-03-29 15:09:45 +00005051 // Handle illegal vector types here.
5052 if (isIllegalVectorType(Ty)) {
5053 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005054 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005055 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005056 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5057 return ABIArgInfo::getDirect(ResType);
5058 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005059 if (Size <= 32) {
5060 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005061 return ABIArgInfo::getDirect(ResType);
5062 }
5063 if (Size == 64) {
5064 llvm::Type *ResType =
5065 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005066 return ABIArgInfo::getDirect(ResType);
5067 }
5068 if (Size == 128) {
5069 llvm::Type *ResType =
5070 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005071 return ABIArgInfo::getDirect(ResType);
5072 }
John McCall7f416cc2015-09-08 08:05:57 +00005073 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005074 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005075
5076 if (!isAggregateTypeForABI(Ty)) {
5077 // Treat an enum type as its underlying type.
5078 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5079 Ty = EnumTy->getDecl()->getIntegerType();
5080
Tim Northovera2ee4332014-03-29 15:09:45 +00005081 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005082 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005083 : ABIArgInfo::getDirect());
5084 }
5085
5086 // Structures with either a non-trivial destructor or a non-trivial
5087 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005088 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005089 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5090 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005091 }
5092
5093 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5094 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005095 uint64_t Size = getContext().getTypeSize(Ty);
5096 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5097 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005098 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5099 return ABIArgInfo::getIgnore();
5100
Tim Northover23bcad22017-05-05 22:36:06 +00005101 // GNU C mode. The only argument that gets ignored is an empty one with size
5102 // 0.
5103 if (IsEmpty && Size == 0)
5104 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005105 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5106 }
5107
5108 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005109 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005110 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005111 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005112 return ABIArgInfo::getDirect(
5113 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005114 }
5115
5116 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005117 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005118 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5119 // same size and alignment.
5120 if (getTarget().isRenderScriptTarget()) {
5121 return coerceToIntArray(Ty, getContext(), getVMContext());
5122 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005123 unsigned Alignment;
5124 if (Kind == AArch64ABIInfo::AAPCS) {
5125 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5126 Alignment = Alignment < 128 ? 64 : 128;
5127 } else {
5128 Alignment = getContext().getTypeAlign(Ty);
5129 }
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005130 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005131
Tim Northovera2ee4332014-03-29 15:09:45 +00005132 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5133 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005134 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005135 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5136 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5137 }
5138 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5139 }
5140
John McCall7f416cc2015-09-08 08:05:57 +00005141 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005142}
5143
Tim Northover573cbee2014-05-24 12:52:07 +00005144ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005145 if (RetTy->isVoidType())
5146 return ABIArgInfo::getIgnore();
5147
5148 // Large vector types should be returned via memory.
5149 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005150 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005151
5152 if (!isAggregateTypeForABI(RetTy)) {
5153 // Treat an enum type as its underlying type.
5154 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5155 RetTy = EnumTy->getDecl()->getIntegerType();
5156
Tim Northover4dab6982014-04-18 13:46:08 +00005157 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005158 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005159 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005160 }
5161
Tim Northover23bcad22017-05-05 22:36:06 +00005162 uint64_t Size = getContext().getTypeSize(RetTy);
5163 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005164 return ABIArgInfo::getIgnore();
5165
Craig Topper8a13c412014-05-21 05:09:00 +00005166 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005167 uint64_t Members = 0;
5168 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005169 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5170 return ABIArgInfo::getDirect();
5171
5172 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005173 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005174 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5175 // same size and alignment.
5176 if (getTarget().isRenderScriptTarget()) {
5177 return coerceToIntArray(RetTy, getContext(), getVMContext());
5178 }
Pete Cooper635b5092015-04-17 22:16:24 +00005179 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005180 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005181
5182 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5183 // For aggregates with 16-byte alignment, we use i128.
5184 if (Alignment < 128 && Size == 128) {
5185 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5186 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5187 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005188 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5189 }
5190
John McCall7f416cc2015-09-08 08:05:57 +00005191 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005192}
5193
Tim Northover573cbee2014-05-24 12:52:07 +00005194/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5195bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005196 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5197 // Check whether VT is legal.
5198 unsigned NumElements = VT->getNumElements();
5199 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005200 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005201 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005202 return true;
5203 return Size != 64 && (Size != 128 || NumElements == 1);
5204 }
5205 return false;
5206}
5207
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005208bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5209 llvm::Type *eltTy,
5210 unsigned elts) const {
5211 if (!llvm::isPowerOf2_32(elts))
5212 return false;
5213 if (totalSize.getQuantity() != 8 &&
5214 (totalSize.getQuantity() != 16 || elts == 1))
5215 return false;
5216 return true;
5217}
5218
Reid Klecknere9f6a712014-10-31 17:10:41 +00005219bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5220 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5221 // point type or a short-vector type. This is the same as the 32-bit ABI,
5222 // but with the difference that any floating-point type is allowed,
5223 // including __fp16.
5224 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5225 if (BT->isFloatingPoint())
5226 return true;
5227 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5228 unsigned VecSize = getContext().getTypeSize(VT);
5229 if (VecSize == 64 || VecSize == 128)
5230 return true;
5231 }
5232 return false;
5233}
5234
5235bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5236 uint64_t Members) const {
5237 return Members <= 4;
5238}
5239
John McCall7f416cc2015-09-08 08:05:57 +00005240Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005241 QualType Ty,
5242 CodeGenFunction &CGF) const {
5243 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005244 bool IsIndirect = AI.isIndirect();
5245
Tim Northoverb047bfa2014-11-27 21:02:49 +00005246 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5247 if (IsIndirect)
5248 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5249 else if (AI.getCoerceToType())
5250 BaseTy = AI.getCoerceToType();
5251
5252 unsigned NumRegs = 1;
5253 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5254 BaseTy = ArrTy->getElementType();
5255 NumRegs = ArrTy->getNumElements();
5256 }
5257 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5258
Tim Northovera2ee4332014-03-29 15:09:45 +00005259 // The AArch64 va_list type and handling is specified in the Procedure Call
5260 // Standard, section B.4:
5261 //
5262 // struct {
5263 // void *__stack;
5264 // void *__gr_top;
5265 // void *__vr_top;
5266 // int __gr_offs;
5267 // int __vr_offs;
5268 // };
5269
5270 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5271 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5272 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5273 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005274
John McCall7f416cc2015-09-08 08:05:57 +00005275 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5276 CharUnits TyAlign = TyInfo.second;
5277
5278 Address reg_offs_p = Address::invalid();
5279 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005280 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005281 CharUnits reg_top_offset;
5282 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005283 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005284 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005285 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005286 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5287 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005288 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5289 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005290 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005291 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005292 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005293 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005294 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005295 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5296 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005297 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5298 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005299 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005300 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005301 }
5302
5303 //=======================================
5304 // Find out where argument was passed
5305 //=======================================
5306
5307 // If reg_offs >= 0 we're already using the stack for this type of
5308 // argument. We don't want to keep updating reg_offs (in case it overflows,
5309 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5310 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005311 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005312 UsingStack = CGF.Builder.CreateICmpSGE(
5313 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5314
5315 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5316
5317 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005318 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005319 CGF.EmitBlock(MaybeRegBlock);
5320
5321 // Integer arguments may need to correct register alignment (for example a
5322 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5323 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005324 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5325 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005326
5327 reg_offs = CGF.Builder.CreateAdd(
5328 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5329 "align_regoffs");
5330 reg_offs = CGF.Builder.CreateAnd(
5331 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5332 "aligned_regoffs");
5333 }
5334
5335 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005336 // The fact that this is done unconditionally reflects the fact that
5337 // allocating an argument to the stack also uses up all the remaining
5338 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005339 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005340 NewOffset = CGF.Builder.CreateAdd(
5341 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5342 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5343
5344 // Now we're in a position to decide whether this argument really was in
5345 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005346 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005347 InRegs = CGF.Builder.CreateICmpSLE(
5348 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5349
5350 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5351
5352 //=======================================
5353 // Argument was in registers
5354 //=======================================
5355
5356 // Now we emit the code for if the argument was originally passed in
5357 // registers. First start the appropriate block:
5358 CGF.EmitBlock(InRegBlock);
5359
John McCall7f416cc2015-09-08 08:05:57 +00005360 llvm::Value *reg_top = nullptr;
5361 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5362 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005363 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005364 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5365 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5366 Address RegAddr = Address::invalid();
5367 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005368
5369 if (IsIndirect) {
5370 // If it's been passed indirectly (actually a struct), whatever we find from
5371 // stored registers or on the stack will actually be a struct **.
5372 MemTy = llvm::PointerType::getUnqual(MemTy);
5373 }
5374
Craig Topper8a13c412014-05-21 05:09:00 +00005375 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005376 uint64_t NumMembers = 0;
5377 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005378 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005379 // Homogeneous aggregates passed in registers will have their elements split
5380 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5381 // qN+1, ...). We reload and store into a temporary local variable
5382 // contiguously.
5383 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005384 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005385 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5386 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005387 Address Tmp = CGF.CreateTempAlloca(HFATy,
5388 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005389
John McCall7f416cc2015-09-08 08:05:57 +00005390 // On big-endian platforms, the value will be right-aligned in its slot.
5391 int Offset = 0;
5392 if (CGF.CGM.getDataLayout().isBigEndian() &&
5393 BaseTyInfo.first.getQuantity() < 16)
5394 Offset = 16 - BaseTyInfo.first.getQuantity();
5395
Tim Northovera2ee4332014-03-29 15:09:45 +00005396 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005397 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5398 Address LoadAddr =
5399 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5400 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5401
5402 Address StoreAddr =
5403 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005404
5405 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5406 CGF.Builder.CreateStore(Elem, StoreAddr);
5407 }
5408
John McCall7f416cc2015-09-08 08:05:57 +00005409 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005410 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005411 // Otherwise the object is contiguous in memory.
5412
5413 // It might be right-aligned in its slot.
5414 CharUnits SlotSize = BaseAddr.getAlignment();
5415 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005416 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005417 TyInfo.first < SlotSize) {
5418 CharUnits Offset = SlotSize - TyInfo.first;
5419 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005420 }
5421
John McCall7f416cc2015-09-08 08:05:57 +00005422 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005423 }
5424
5425 CGF.EmitBranch(ContBlock);
5426
5427 //=======================================
5428 // Argument was on the stack
5429 //=======================================
5430 CGF.EmitBlock(OnStackBlock);
5431
John McCall7f416cc2015-09-08 08:05:57 +00005432 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5433 CharUnits::Zero(), "stack_p");
5434 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005435
John McCall7f416cc2015-09-08 08:05:57 +00005436 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005437 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005438 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5439 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005440
John McCall7f416cc2015-09-08 08:05:57 +00005441 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005442
John McCall7f416cc2015-09-08 08:05:57 +00005443 OnStackPtr = CGF.Builder.CreateAdd(
5444 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005445 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005446 OnStackPtr = CGF.Builder.CreateAnd(
5447 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005448 "align_stack");
5449
John McCall7f416cc2015-09-08 08:05:57 +00005450 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005451 }
John McCall7f416cc2015-09-08 08:05:57 +00005452 Address OnStackAddr(OnStackPtr,
5453 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005454
John McCall7f416cc2015-09-08 08:05:57 +00005455 // All stack slots are multiples of 8 bytes.
5456 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5457 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005458 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005459 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005460 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005461 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005462
John McCall7f416cc2015-09-08 08:05:57 +00005463 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005464 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005465 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005466
5467 // Write the new value of __stack for the next call to va_arg
5468 CGF.Builder.CreateStore(NewStack, stack_p);
5469
5470 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005471 TyInfo.first < StackSlotSize) {
5472 CharUnits Offset = StackSlotSize - TyInfo.first;
5473 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005474 }
5475
John McCall7f416cc2015-09-08 08:05:57 +00005476 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005477
5478 CGF.EmitBranch(ContBlock);
5479
5480 //=======================================
5481 // Tidy up
5482 //=======================================
5483 CGF.EmitBlock(ContBlock);
5484
John McCall7f416cc2015-09-08 08:05:57 +00005485 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5486 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005487
5488 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005489 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5490 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005491
5492 return ResAddr;
5493}
5494
John McCall7f416cc2015-09-08 08:05:57 +00005495Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5496 CodeGenFunction &CGF) const {
5497 // The backend's lowering doesn't support va_arg for aggregates or
5498 // illegal vector types. Lower VAArg here for these cases and use
5499 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005500 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005501 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005502
John McCall7f416cc2015-09-08 08:05:57 +00005503 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005504
John McCall7f416cc2015-09-08 08:05:57 +00005505 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005506 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005507 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5508 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5509 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005510 }
5511
John McCall7f416cc2015-09-08 08:05:57 +00005512 // The size of the actual thing passed, which might end up just
5513 // being a pointer for indirect types.
5514 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5515
5516 // Arguments bigger than 16 bytes which aren't homogeneous
5517 // aggregates should be passed indirectly.
5518 bool IsIndirect = false;
5519 if (TyInfo.first.getQuantity() > 16) {
5520 const Type *Base = nullptr;
5521 uint64_t Members = 0;
5522 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005523 }
5524
John McCall7f416cc2015-09-08 08:05:57 +00005525 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5526 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005527}
5528
Martin Storsjo502de222017-07-13 17:59:14 +00005529Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5530 QualType Ty) const {
5531 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5532 CGF.getContext().getTypeInfoInChars(Ty),
5533 CharUnits::fromQuantity(8),
5534 /*allowHigherAlign*/ false);
5535}
5536
Tim Northovera2ee4332014-03-29 15:09:45 +00005537//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005538// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005539//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005540
5541namespace {
5542
John McCall12f23522016-04-04 18:33:08 +00005543class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005544public:
5545 enum ABIKind {
5546 APCS = 0,
5547 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005548 AAPCS_VFP = 2,
5549 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005550 };
5551
5552private:
5553 ABIKind Kind;
5554
5555public:
John McCall12f23522016-04-04 18:33:08 +00005556 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5557 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005558 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005559 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005560
John McCall3480ef22011-08-30 01:42:09 +00005561 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005562 switch (getTarget().getTriple().getEnvironment()) {
5563 case llvm::Triple::Android:
5564 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005565 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005566 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005567 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005568 case llvm::Triple::MuslEABI:
5569 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005570 return true;
5571 default:
5572 return false;
5573 }
John McCall3480ef22011-08-30 01:42:09 +00005574 }
5575
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005576 bool isEABIHF() const {
5577 switch (getTarget().getTriple().getEnvironment()) {
5578 case llvm::Triple::EABIHF:
5579 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005580 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005581 return true;
5582 default:
5583 return false;
5584 }
5585 }
5586
Daniel Dunbar020daa92009-09-12 01:00:39 +00005587 ABIKind getABIKind() const { return Kind; }
5588
Tim Northovera484bc02013-10-01 14:34:25 +00005589private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005590 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005591 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005592 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5593 uint64_t Members) const;
5594 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005595 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005596
Reid Klecknere9f6a712014-10-31 17:10:41 +00005597 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5598 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5599 uint64_t Members) const override;
5600
Craig Topper4f12f102014-03-12 06:41:41 +00005601 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005602
John McCall7f416cc2015-09-08 08:05:57 +00005603 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5604 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005605
5606 llvm::CallingConv::ID getLLVMDefaultCC() const;
5607 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005608 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005609
John McCall56331e22018-01-07 06:28:49 +00005610 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005611 bool asReturnValue) const override {
5612 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5613 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005614 bool isSwiftErrorInRegister() const override {
5615 return true;
5616 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005617 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5618 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005619};
5620
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005621class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5622public:
Chris Lattner2b037972010-07-29 02:01:43 +00005623 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5624 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005625
John McCall3480ef22011-08-30 01:42:09 +00005626 const ARMABIInfo &getABIInfo() const {
5627 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5628 }
5629
Craig Topper4f12f102014-03-12 06:41:41 +00005630 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005631 return 13;
5632 }
Roman Divackyc1617352011-05-18 19:36:54 +00005633
Craig Topper4f12f102014-03-12 06:41:41 +00005634 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005635 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005636 }
5637
Roman Divackyc1617352011-05-18 19:36:54 +00005638 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005639 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005640 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005641
5642 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005643 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005644 return false;
5645 }
John McCall3480ef22011-08-30 01:42:09 +00005646
Craig Topper4f12f102014-03-12 06:41:41 +00005647 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005648 if (getABIInfo().isEABI()) return 88;
5649 return TargetCodeGenInfo::getSizeOfUnwindException();
5650 }
Tim Northovera484bc02013-10-01 14:34:25 +00005651
Eric Christopher162c91c2015-06-05 22:03:00 +00005652 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005653 CodeGen::CodeGenModule &CGM) const override {
5654 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005655 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005656 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005657 if (!FD)
5658 return;
5659
5660 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5661 if (!Attr)
5662 return;
5663
5664 const char *Kind;
5665 switch (Attr->getInterrupt()) {
5666 case ARMInterruptAttr::Generic: Kind = ""; break;
5667 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5668 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5669 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5670 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5671 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5672 }
5673
5674 llvm::Function *Fn = cast<llvm::Function>(GV);
5675
5676 Fn->addFnAttr("interrupt", Kind);
5677
Tim Northover5627d392015-10-30 16:30:45 +00005678 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5679 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005680 return;
5681
5682 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5683 // however this is not necessarily true on taking any interrupt. Instruct
5684 // the backend to perform a realignment as part of the function prologue.
5685 llvm::AttrBuilder B;
5686 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005687 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005688 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005689};
5690
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005691class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005692public:
5693 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5694 : ARMTargetCodeGenInfo(CGT, K) {}
5695
Eric Christopher162c91c2015-06-05 22:03:00 +00005696 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005697 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005698
5699 void getDependentLibraryOption(llvm::StringRef Lib,
5700 llvm::SmallString<24> &Opt) const override {
5701 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5702 }
5703
5704 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5705 llvm::SmallString<32> &Opt) const override {
5706 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5707 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005708};
5709
Eric Christopher162c91c2015-06-05 22:03:00 +00005710void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005711 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5712 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5713 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005714 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005715 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005716}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005717}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005718
Chris Lattner22326a12010-07-29 02:31:05 +00005719void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005720 if (!::classifyReturnType(getCXXABI(), FI, *this))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005721 FI.getReturnInfo() =
5722 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005723
Tim Northoverbc784d12015-02-24 17:22:40 +00005724 for (auto &I : FI.arguments())
5725 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005726
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005727 // Always honor user-specified calling convention.
5728 if (FI.getCallingConvention() != llvm::CallingConv::C)
5729 return;
5730
John McCall882987f2013-02-28 19:01:20 +00005731 llvm::CallingConv::ID cc = getRuntimeCC();
5732 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005733 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005734}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005735
John McCall882987f2013-02-28 19:01:20 +00005736/// Return the default calling convention that LLVM will use.
5737llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5738 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005739 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005740 return llvm::CallingConv::ARM_AAPCS_VFP;
5741 else if (isEABI())
5742 return llvm::CallingConv::ARM_AAPCS;
5743 else
5744 return llvm::CallingConv::ARM_APCS;
5745}
5746
5747/// Return the calling convention that our ABI would like us to use
5748/// as the C calling convention.
5749llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005750 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005751 case APCS: return llvm::CallingConv::ARM_APCS;
5752 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5753 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005754 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005755 }
John McCall882987f2013-02-28 19:01:20 +00005756 llvm_unreachable("bad ABI kind");
5757}
5758
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005759void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005760 assert(getRuntimeCC() == llvm::CallingConv::C);
5761
5762 // Don't muddy up the IR with a ton of explicit annotations if
5763 // they'd just match what LLVM will infer from the triple.
5764 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5765 if (abiCC != getLLVMDefaultCC())
5766 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005767}
5768
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005769ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5770 uint64_t Size = getContext().getTypeSize(Ty);
5771 if (Size <= 32) {
5772 llvm::Type *ResType =
5773 llvm::Type::getInt32Ty(getVMContext());
5774 return ABIArgInfo::getDirect(ResType);
5775 }
5776 if (Size == 64 || Size == 128) {
5777 llvm::Type *ResType = llvm::VectorType::get(
5778 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5779 return ABIArgInfo::getDirect(ResType);
5780 }
5781 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5782}
5783
5784ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5785 const Type *Base,
5786 uint64_t Members) const {
5787 assert(Base && "Base class should be set for homogeneous aggregate");
5788 // Base can be a floating-point or a vector.
5789 if (const VectorType *VT = Base->getAs<VectorType>()) {
5790 // FP16 vectors should be converted to integer vectors
5791 if (!getTarget().hasLegalHalfType() &&
5792 (VT->getElementType()->isFloat16Type() ||
5793 VT->getElementType()->isHalfType())) {
5794 uint64_t Size = getContext().getTypeSize(VT);
5795 llvm::Type *NewVecTy = llvm::VectorType::get(
5796 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5797 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5798 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5799 }
5800 }
5801 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5802}
5803
Tim Northoverbc784d12015-02-24 17:22:40 +00005804ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5805 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005806 // 6.1.2.1 The following argument types are VFP CPRCs:
5807 // A single-precision floating-point type (including promoted
5808 // half-precision types); A double-precision floating-point type;
5809 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5810 // with a Base Type of a single- or double-precision floating-point type,
5811 // 64-bit containerized vectors or 128-bit containerized vectors with one
5812 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005813 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005814
Reid Klecknerb1be6832014-11-15 01:41:41 +00005815 Ty = useFirstFieldIfTransparentUnion(Ty);
5816
Manman Renfef9e312012-10-16 19:18:39 +00005817 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005818 if (isIllegalVectorType(Ty))
5819 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005820
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005821 // _Float16 and __fp16 get passed as if it were an int or float, but with
5822 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5823 // half type natively, and does not need to interwork with AAPCS code.
5824 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5825 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005826 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5827 llvm::Type::getFloatTy(getVMContext()) :
5828 llvm::Type::getInt32Ty(getVMContext());
5829 return ABIArgInfo::getDirect(ResType);
5830 }
5831
John McCalla1dee5302010-08-22 10:59:02 +00005832 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005833 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005834 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005835 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005836 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005837
Alex Bradburye41a5e22018-01-12 20:08:16 +00005838 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005839 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005840 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005841
Oliver Stannard405bded2014-02-11 09:25:50 +00005842 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005843 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005844 }
Tim Northover1060eae2013-06-21 22:49:34 +00005845
Daniel Dunbar09d33622009-09-14 21:54:03 +00005846 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005847 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005848 return ABIArgInfo::getIgnore();
5849
Tim Northover5a1558e2014-11-07 22:30:50 +00005850 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005851 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5852 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005853 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005854 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005855 if (isHomogeneousAggregate(Ty, Base, Members))
5856 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005857 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5858 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5859 // this convention even for a variadic function: the backend will use GPRs
5860 // if needed.
5861 const Type *Base = nullptr;
5862 uint64_t Members = 0;
5863 if (isHomogeneousAggregate(Ty, Base, Members)) {
5864 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5865 llvm::Type *Ty =
5866 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5867 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5868 }
5869 }
5870
5871 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5872 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5873 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5874 // bigger than 128-bits, they get placed in space allocated by the caller,
5875 // and a pointer is passed.
5876 return ABIArgInfo::getIndirect(
5877 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005878 }
5879
Manman Ren6c30e132012-08-13 21:23:55 +00005880 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005881 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5882 // most 8-byte. We realign the indirect argument if type alignment is bigger
5883 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005884 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005885 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005886 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005887 getABIKind() == ARMABIInfo::AAPCS) {
5888 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005889 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005890 } else {
5891 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5892 }
Manman Ren8cd99812012-11-06 04:58:01 +00005893 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005894 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005895 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5896 /*ByVal=*/true,
5897 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005898 }
5899
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005900 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5901 // same size and alignment.
5902 if (getTarget().isRenderScriptTarget()) {
5903 return coerceToIntArray(Ty, getContext(), getVMContext());
5904 }
5905
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005906 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005907 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005908 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005909 // FIXME: Try to match the types of the arguments more accurately where
5910 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00005911 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005912 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5913 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005914 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005915 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5916 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005917 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005918
Tim Northover5a1558e2014-11-07 22:30:50 +00005919 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005920}
5921
Chris Lattner458b2aa2010-07-29 02:16:43 +00005922static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005923 llvm::LLVMContext &VMContext) {
5924 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5925 // is called integer-like if its size is less than or equal to one word, and
5926 // the offset of each of its addressable sub-fields is zero.
5927
5928 uint64_t Size = Context.getTypeSize(Ty);
5929
5930 // Check that the type fits in a word.
5931 if (Size > 32)
5932 return false;
5933
5934 // FIXME: Handle vector types!
5935 if (Ty->isVectorType())
5936 return false;
5937
Daniel Dunbard53bac72009-09-14 02:20:34 +00005938 // Float types are never treated as "integer like".
5939 if (Ty->isRealFloatingType())
5940 return false;
5941
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005942 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005943 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005944 return true;
5945
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005946 // Small complex integer types are "integer like".
5947 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5948 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005949
5950 // Single element and zero sized arrays should be allowed, by the definition
5951 // above, but they are not.
5952
5953 // Otherwise, it must be a record type.
5954 const RecordType *RT = Ty->getAs<RecordType>();
5955 if (!RT) return false;
5956
5957 // Ignore records with flexible arrays.
5958 const RecordDecl *RD = RT->getDecl();
5959 if (RD->hasFlexibleArrayMember())
5960 return false;
5961
5962 // Check that all sub-fields are at offset 0, and are themselves "integer
5963 // like".
5964 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5965
5966 bool HadField = false;
5967 unsigned idx = 0;
5968 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5969 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005970 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005971
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005972 // Bit-fields are not addressable, we only need to verify they are "integer
5973 // like". We still have to disallow a subsequent non-bitfield, for example:
5974 // struct { int : 0; int x }
5975 // is non-integer like according to gcc.
5976 if (FD->isBitField()) {
5977 if (!RD->isUnion())
5978 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005979
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005980 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5981 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005982
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005983 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005984 }
5985
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005986 // Check if this field is at offset 0.
5987 if (Layout.getFieldOffset(idx) != 0)
5988 return false;
5989
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005990 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5991 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005992
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005993 // Only allow at most one field in a structure. This doesn't match the
5994 // wording above, but follows gcc in situations with a field following an
5995 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005996 if (!RD->isUnion()) {
5997 if (HadField)
5998 return false;
5999
6000 HadField = true;
6001 }
6002 }
6003
6004 return true;
6005}
6006
Oliver Stannard405bded2014-02-11 09:25:50 +00006007ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
6008 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00006009 bool IsEffectivelyAAPCS_VFP =
6010 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006011
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006012 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006013 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006014
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006015 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6016 // Large vector types should be returned via memory.
6017 if (getContext().getTypeSize(RetTy) > 128)
6018 return getNaturalAlignIndirect(RetTy);
6019 // FP16 vectors should be converted to integer vectors
6020 if (!getTarget().hasLegalHalfType() &&
6021 (VT->getElementType()->isFloat16Type() ||
6022 VT->getElementType()->isHalfType()))
6023 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006024 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006025
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006026 // _Float16 and __fp16 get returned as if it were an int or float, but with
6027 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6028 // half type natively, and does not need to interwork with AAPCS code.
6029 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6030 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006031 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
6032 llvm::Type::getFloatTy(getVMContext()) :
6033 llvm::Type::getInt32Ty(getVMContext());
6034 return ABIArgInfo::getDirect(ResType);
6035 }
6036
John McCalla1dee5302010-08-22 10:59:02 +00006037 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006038 // Treat an enum type as its underlying type.
6039 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6040 RetTy = EnumTy->getDecl()->getIntegerType();
6041
Alex Bradburye41a5e22018-01-12 20:08:16 +00006042 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006043 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006044 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006045
6046 // Are we following APCS?
6047 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006048 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006049 return ABIArgInfo::getIgnore();
6050
Daniel Dunbareedf1512010-02-01 23:31:19 +00006051 // Complex types are all returned as packed integers.
6052 //
6053 // FIXME: Consider using 2 x vector types if the back end handles them
6054 // correctly.
6055 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006056 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6057 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006058
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006059 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006060 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006061 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006062 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006063 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006064 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006065 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006066 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6067 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006068 }
6069
6070 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006071 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006072 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006073
6074 // Otherwise this is an AAPCS variant.
6075
Chris Lattner458b2aa2010-07-29 02:16:43 +00006076 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006077 return ABIArgInfo::getIgnore();
6078
Bob Wilson1d9269a2011-11-02 04:51:36 +00006079 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00006080 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006081 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006082 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006083 if (isHomogeneousAggregate(RetTy, Base, Members))
6084 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006085 }
6086
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006087 // Aggregates <= 4 bytes are returned in r0; other aggregates
6088 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006089 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006090 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006091 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6092 // same size and alignment.
6093 if (getTarget().isRenderScriptTarget()) {
6094 return coerceToIntArray(RetTy, getContext(), getVMContext());
6095 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006096 if (getDataLayout().isBigEndian())
6097 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006098 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006099
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006100 // Return in the smallest viable integer type.
6101 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006102 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006103 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006104 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6105 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006106 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6107 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6108 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006109 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006110 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006111 }
6112
John McCall7f416cc2015-09-08 08:05:57 +00006113 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006114}
6115
Manman Renfef9e312012-10-16 19:18:39 +00006116/// isIllegalVector - check whether Ty is an illegal vector type.
6117bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006118 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006119 // On targets that don't support FP16, FP16 is expanded into float, and we
6120 // don't want the ABI to depend on whether or not FP16 is supported in
6121 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6122 if (!getTarget().hasLegalHalfType() &&
6123 (VT->getElementType()->isFloat16Type() ||
6124 VT->getElementType()->isHalfType()))
6125 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006126 if (isAndroid()) {
6127 // Android shipped using Clang 3.1, which supported a slightly different
6128 // vector ABI. The primary differences were that 3-element vector types
6129 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6130 // accepts that legacy behavior for Android only.
6131 // Check whether VT is legal.
6132 unsigned NumElements = VT->getNumElements();
6133 // NumElements should be power of 2 or equal to 3.
6134 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6135 return true;
6136 } else {
6137 // Check whether VT is legal.
6138 unsigned NumElements = VT->getNumElements();
6139 uint64_t Size = getContext().getTypeSize(VT);
6140 // NumElements should be power of 2.
6141 if (!llvm::isPowerOf2_32(NumElements))
6142 return true;
6143 // Size should be greater than 32 bits.
6144 return Size <= 32;
6145 }
Manman Renfef9e312012-10-16 19:18:39 +00006146 }
6147 return false;
6148}
6149
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006150bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6151 llvm::Type *eltTy,
6152 unsigned numElts) const {
6153 if (!llvm::isPowerOf2_32(numElts))
6154 return false;
6155 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6156 if (size > 64)
6157 return false;
6158 if (vectorSize.getQuantity() != 8 &&
6159 (vectorSize.getQuantity() != 16 || numElts == 1))
6160 return false;
6161 return true;
6162}
6163
Reid Klecknere9f6a712014-10-31 17:10:41 +00006164bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6165 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6166 // double, or 64-bit or 128-bit vectors.
6167 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6168 if (BT->getKind() == BuiltinType::Float ||
6169 BT->getKind() == BuiltinType::Double ||
6170 BT->getKind() == BuiltinType::LongDouble)
6171 return true;
6172 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6173 unsigned VecSize = getContext().getTypeSize(VT);
6174 if (VecSize == 64 || VecSize == 128)
6175 return true;
6176 }
6177 return false;
6178}
6179
6180bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6181 uint64_t Members) const {
6182 return Members <= 4;
6183}
6184
John McCall7f416cc2015-09-08 08:05:57 +00006185Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6186 QualType Ty) const {
6187 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006188
John McCall7f416cc2015-09-08 08:05:57 +00006189 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006190 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006191 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6192 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6193 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006194 }
6195
John McCall7f416cc2015-09-08 08:05:57 +00006196 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6197 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006198
John McCall7f416cc2015-09-08 08:05:57 +00006199 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6200 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006201 const Type *Base = nullptr;
6202 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006203 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6204 IsIndirect = true;
6205
Tim Northover5627d392015-10-30 16:30:45 +00006206 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6207 // allocated by the caller.
6208 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6209 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6210 !isHomogeneousAggregate(Ty, Base, Members)) {
6211 IsIndirect = true;
6212
John McCall7f416cc2015-09-08 08:05:57 +00006213 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006214 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6215 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006216 // Our callers should be prepared to handle an under-aligned address.
6217 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6218 getABIKind() == ARMABIInfo::AAPCS) {
6219 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6220 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006221 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6222 // ARMv7k allows type alignment up to 16 bytes.
6223 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6224 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006225 } else {
6226 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006227 }
John McCall7f416cc2015-09-08 08:05:57 +00006228 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006229
John McCall7f416cc2015-09-08 08:05:57 +00006230 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6231 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006232}
6233
Chris Lattner0cf24192010-06-28 20:05:43 +00006234//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006235// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006236//===----------------------------------------------------------------------===//
6237
6238namespace {
6239
Justin Holewinski83e96682012-05-24 17:43:12 +00006240class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006241public:
Justin Holewinski36837432013-03-30 14:38:24 +00006242 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006243
6244 ABIArgInfo classifyReturnType(QualType RetTy) const;
6245 ABIArgInfo classifyArgumentType(QualType Ty) const;
6246
Craig Topper4f12f102014-03-12 06:41:41 +00006247 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006248 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6249 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006250};
6251
Justin Holewinski83e96682012-05-24 17:43:12 +00006252class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006253public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006254 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6255 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006256
Eric Christopher162c91c2015-06-05 22:03:00 +00006257 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006258 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006259 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006260
Justin Holewinski36837432013-03-30 14:38:24 +00006261private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006262 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6263 // resulting MDNode to the nvvm.annotations MDNode.
6264 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006265};
6266
Justin Holewinski83e96682012-05-24 17:43:12 +00006267ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006268 if (RetTy->isVoidType())
6269 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006270
6271 // note: this is different from default ABI
6272 if (!RetTy->isScalarType())
6273 return ABIArgInfo::getDirect();
6274
6275 // Treat an enum type as its underlying type.
6276 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6277 RetTy = EnumTy->getDecl()->getIntegerType();
6278
Alex Bradburye41a5e22018-01-12 20:08:16 +00006279 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6280 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006281}
6282
Justin Holewinski83e96682012-05-24 17:43:12 +00006283ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006284 // Treat an enum type as its underlying type.
6285 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6286 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006287
Eli Bendersky95338a02014-10-29 13:43:21 +00006288 // Return aggregates type as indirect by value
6289 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006290 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006291
Alex Bradburye41a5e22018-01-12 20:08:16 +00006292 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6293 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006294}
6295
Justin Holewinski83e96682012-05-24 17:43:12 +00006296void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006297 if (!getCXXABI().classifyReturnType(FI))
6298 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006299 for (auto &I : FI.arguments())
6300 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006301
6302 // Always honor user-specified calling convention.
6303 if (FI.getCallingConvention() != llvm::CallingConv::C)
6304 return;
6305
John McCall882987f2013-02-28 19:01:20 +00006306 FI.setEffectiveCallingConvention(getRuntimeCC());
6307}
6308
John McCall7f416cc2015-09-08 08:05:57 +00006309Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6310 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006311 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006312}
6313
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006314void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006315 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6316 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006317 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006318 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006319 if (!FD) return;
6320
6321 llvm::Function *F = cast<llvm::Function>(GV);
6322
6323 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006324 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006325 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006326 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006327 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006328 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006329 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6330 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006331 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006332 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006333 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006334 }
Justin Holewinski38031972011-10-05 17:58:44 +00006335
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006336 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006337 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006338 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006339 // __global__ functions cannot be called from the device, we do not
6340 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006341 if (FD->hasAttr<CUDAGlobalAttr>()) {
6342 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6343 addNVVMMetadata(F, "kernel", 1);
6344 }
Artem Belevich7093e402015-04-21 22:55:54 +00006345 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006346 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006347 llvm::APSInt MaxThreads(32);
6348 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6349 if (MaxThreads > 0)
6350 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6351
6352 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6353 // not specified in __launch_bounds__ or if the user specified a 0 value,
6354 // we don't have to add a PTX directive.
6355 if (Attr->getMinBlocks()) {
6356 llvm::APSInt MinBlocks(32);
6357 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6358 if (MinBlocks > 0)
6359 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6360 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006361 }
6362 }
Justin Holewinski38031972011-10-05 17:58:44 +00006363 }
6364}
6365
Eli Benderskye06a2c42014-04-15 16:57:05 +00006366void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6367 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006368 llvm::Module *M = F->getParent();
6369 llvm::LLVMContext &Ctx = M->getContext();
6370
6371 // Get "nvvm.annotations" metadata node
6372 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6373
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006374 llvm::Metadata *MDVals[] = {
6375 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6376 llvm::ConstantAsMetadata::get(
6377 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006378 // Append metadata to nvvm.annotations
6379 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6380}
Yaxun Liub0eee292018-03-29 14:50:00 +00006381
6382bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6383 return false;
6384}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006385}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006386
6387//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006388// SystemZ ABI Implementation
6389//===----------------------------------------------------------------------===//
6390
6391namespace {
6392
Bryan Chane3f1ed52016-04-28 13:56:43 +00006393class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006394 bool HasVector;
6395
Ulrich Weigand47445072013-05-06 16:26:41 +00006396public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006397 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006398 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006399
6400 bool isPromotableIntegerType(QualType Ty) const;
6401 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006402 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006403 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006404 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006405
6406 ABIArgInfo classifyReturnType(QualType RetTy) const;
6407 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6408
Craig Topper4f12f102014-03-12 06:41:41 +00006409 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006410 if (!getCXXABI().classifyReturnType(FI))
6411 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006412 for (auto &I : FI.arguments())
6413 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006414 }
6415
John McCall7f416cc2015-09-08 08:05:57 +00006416 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6417 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006418
John McCall56331e22018-01-07 06:28:49 +00006419 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006420 bool asReturnValue) const override {
6421 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6422 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006423 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006424 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006425 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006426};
6427
6428class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6429public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006430 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6431 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006432};
6433
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006434}
Ulrich Weigand47445072013-05-06 16:26:41 +00006435
6436bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6437 // Treat an enum type as its underlying type.
6438 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6439 Ty = EnumTy->getDecl()->getIntegerType();
6440
6441 // Promotable integer types are required to be promoted by the ABI.
6442 if (Ty->isPromotableIntegerType())
6443 return true;
6444
6445 // 32-bit values must also be promoted.
6446 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6447 switch (BT->getKind()) {
6448 case BuiltinType::Int:
6449 case BuiltinType::UInt:
6450 return true;
6451 default:
6452 return false;
6453 }
6454 return false;
6455}
6456
6457bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006458 return (Ty->isAnyComplexType() ||
6459 Ty->isVectorType() ||
6460 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006461}
6462
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006463bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6464 return (HasVector &&
6465 Ty->isVectorType() &&
6466 getContext().getTypeSize(Ty) <= 128);
6467}
6468
Ulrich Weigand47445072013-05-06 16:26:41 +00006469bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6470 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6471 switch (BT->getKind()) {
6472 case BuiltinType::Float:
6473 case BuiltinType::Double:
6474 return true;
6475 default:
6476 return false;
6477 }
6478
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006479 return false;
6480}
6481
6482QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006483 if (const RecordType *RT = Ty->getAsStructureType()) {
6484 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006485 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006486
6487 // If this is a C++ record, check the bases first.
6488 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006489 for (const auto &I : CXXRD->bases()) {
6490 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006491
6492 // Empty bases don't affect things either way.
6493 if (isEmptyRecord(getContext(), Base, true))
6494 continue;
6495
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006496 if (!Found.isNull())
6497 return Ty;
6498 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006499 }
6500
6501 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006502 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006503 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006504 // Unlike isSingleElementStruct(), empty structure and array fields
6505 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006506 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006507 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006508 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006509
6510 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006511 // Nested structures still do though.
6512 if (!Found.isNull())
6513 return Ty;
6514 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006515 }
6516
6517 // Unlike isSingleElementStruct(), trailing padding is allowed.
6518 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006519 if (!Found.isNull())
6520 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006521 }
6522
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006523 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006524}
6525
John McCall7f416cc2015-09-08 08:05:57 +00006526Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6527 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006528 // Assume that va_list type is correct; should be pointer to LLVM type:
6529 // struct {
6530 // i64 __gpr;
6531 // i64 __fpr;
6532 // i8 *__overflow_arg_area;
6533 // i8 *__reg_save_area;
6534 // };
6535
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006536 // Every non-vector argument occupies 8 bytes and is passed by preference
6537 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6538 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006539 Ty = getContext().getCanonicalType(Ty);
6540 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006541 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006542 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006543 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006544 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006545 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006546 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006547 CharUnits UnpaddedSize;
6548 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006549 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006550 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6551 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006552 } else {
6553 if (AI.getCoerceToType())
6554 ArgTy = AI.getCoerceToType();
6555 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006556 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006557 UnpaddedSize = TyInfo.first;
6558 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006559 }
John McCall7f416cc2015-09-08 08:05:57 +00006560 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6561 if (IsVector && UnpaddedSize > PaddedSize)
6562 PaddedSize = CharUnits::fromQuantity(16);
6563 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006564
John McCall7f416cc2015-09-08 08:05:57 +00006565 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006566
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006567 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006568 llvm::Value *PaddedSizeV =
6569 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006570
6571 if (IsVector) {
6572 // Work out the address of a vector argument on the stack.
6573 // Vector arguments are always passed in the high bits of a
6574 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006575 Address OverflowArgAreaPtr =
6576 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006577 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006578 Address OverflowArgArea =
6579 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6580 TyInfo.second);
6581 Address MemAddr =
6582 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006583
6584 // Update overflow_arg_area_ptr pointer
6585 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006586 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6587 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006588 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6589
6590 return MemAddr;
6591 }
6592
John McCall7f416cc2015-09-08 08:05:57 +00006593 assert(PaddedSize.getQuantity() == 8);
6594
6595 unsigned MaxRegs, RegCountField, RegSaveIndex;
6596 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006597 if (InFPRs) {
6598 MaxRegs = 4; // Maximum of 4 FPR arguments
6599 RegCountField = 1; // __fpr
6600 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006601 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006602 } else {
6603 MaxRegs = 5; // Maximum of 5 GPR arguments
6604 RegCountField = 0; // __gpr
6605 RegSaveIndex = 2; // save offset for r2
6606 RegPadding = Padding; // values are passed in the low bits of a GPR
6607 }
6608
John McCall7f416cc2015-09-08 08:05:57 +00006609 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6610 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6611 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006612 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006613 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6614 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006615 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006616
6617 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6618 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6619 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6620 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6621
6622 // Emit code to load the value if it was passed in registers.
6623 CGF.EmitBlock(InRegBlock);
6624
6625 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006626 llvm::Value *ScaledRegCount =
6627 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6628 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006629 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6630 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006631 llvm::Value *RegOffset =
6632 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006633 Address RegSaveAreaPtr =
6634 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6635 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006636 llvm::Value *RegSaveArea =
6637 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006638 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6639 "raw_reg_addr"),
6640 PaddedSize);
6641 Address RegAddr =
6642 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006643
6644 // Update the register count
6645 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6646 llvm::Value *NewRegCount =
6647 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6648 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6649 CGF.EmitBranch(ContBlock);
6650
6651 // Emit code to load the value if it was passed in memory.
6652 CGF.EmitBlock(InMemBlock);
6653
6654 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006655 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6656 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6657 Address OverflowArgArea =
6658 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6659 PaddedSize);
6660 Address RawMemAddr =
6661 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6662 Address MemAddr =
6663 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006664
6665 // Update overflow_arg_area_ptr pointer
6666 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006667 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6668 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006669 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6670 CGF.EmitBranch(ContBlock);
6671
6672 // Return the appropriate result.
6673 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006674 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6675 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006676
6677 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006678 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6679 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006680
6681 return ResAddr;
6682}
6683
Ulrich Weigand47445072013-05-06 16:26:41 +00006684ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6685 if (RetTy->isVoidType())
6686 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006687 if (isVectorArgumentType(RetTy))
6688 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006689 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006690 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006691 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6692 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006693}
6694
6695ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6696 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006697 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006698 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006699
6700 // Integers and enums are extended to full register width.
6701 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006702 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006703
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006704 // Handle vector types and vector-like structure types. Note that
6705 // as opposed to float-like structure types, we do not allow any
6706 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006707 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006708 QualType SingleElementTy = GetSingleElementType(Ty);
6709 if (isVectorArgumentType(SingleElementTy) &&
6710 getContext().getTypeSize(SingleElementTy) == Size)
6711 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6712
6713 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006714 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006715 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006716
6717 // Handle small structures.
6718 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6719 // Structures with flexible arrays have variable length, so really
6720 // fail the size test above.
6721 const RecordDecl *RD = RT->getDecl();
6722 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006723 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006724
6725 // The structure is passed as an unextended integer, a float, or a double.
6726 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006727 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006728 assert(Size == 32 || Size == 64);
6729 if (Size == 32)
6730 PassTy = llvm::Type::getFloatTy(getVMContext());
6731 else
6732 PassTy = llvm::Type::getDoubleTy(getVMContext());
6733 } else
6734 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6735 return ABIArgInfo::getDirect(PassTy);
6736 }
6737
6738 // Non-structure compounds are passed indirectly.
6739 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006740 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006741
Craig Topper8a13c412014-05-21 05:09:00 +00006742 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006743}
6744
6745//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006746// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006747//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006748
6749namespace {
6750
6751class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6752public:
Chris Lattner2b037972010-07-29 02:01:43 +00006753 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6754 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006755 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006756 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006757};
6758
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006759}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006760
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006761void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006762 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6763 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006764 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006765 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006766 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6767 // Handle 'interrupt' attribute:
6768 llvm::Function *F = cast<llvm::Function>(GV);
6769
6770 // Step 1: Set ISR calling convention.
6771 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6772
6773 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006774 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006775
6776 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006777 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006778 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6779 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006780 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006781 }
6782}
6783
Chris Lattner0cf24192010-06-28 20:05:43 +00006784//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006785// MIPS ABI Implementation. This works for both little-endian and
6786// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006787//===----------------------------------------------------------------------===//
6788
John McCall943fae92010-05-27 06:19:26 +00006789namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006790class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006791 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006792 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6793 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006794 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006795 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006796 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006797 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006798public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006799 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006800 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006801 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006802
6803 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006804 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006805 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006806 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6807 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006808 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006809};
6810
John McCall943fae92010-05-27 06:19:26 +00006811class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006812 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006813public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006814 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6815 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006816 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006817
Craig Topper4f12f102014-03-12 06:41:41 +00006818 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006819 return 29;
6820 }
6821
Eric Christopher162c91c2015-06-05 22:03:00 +00006822 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006823 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006824 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006825 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006826 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006827
6828 if (FD->hasAttr<MipsLongCallAttr>())
6829 Fn->addFnAttr("long-call");
6830 else if (FD->hasAttr<MipsShortCallAttr>())
6831 Fn->addFnAttr("short-call");
6832
6833 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006834 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006835 return;
6836
Reed Kotler3d5966f2013-03-13 20:40:30 +00006837 if (FD->hasAttr<Mips16Attr>()) {
6838 Fn->addFnAttr("mips16");
6839 }
6840 else if (FD->hasAttr<NoMips16Attr>()) {
6841 Fn->addFnAttr("nomips16");
6842 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006843
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006844 if (FD->hasAttr<MicroMipsAttr>())
6845 Fn->addFnAttr("micromips");
6846 else if (FD->hasAttr<NoMicroMipsAttr>())
6847 Fn->addFnAttr("nomicromips");
6848
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006849 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6850 if (!Attr)
6851 return;
6852
6853 const char *Kind;
6854 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006855 case MipsInterruptAttr::eic: Kind = "eic"; break;
6856 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6857 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6858 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6859 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6860 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6861 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6862 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6863 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6864 }
6865
6866 Fn->addFnAttr("interrupt", Kind);
6867
Reed Kotler373feca2013-01-16 17:10:28 +00006868 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006869
John McCall943fae92010-05-27 06:19:26 +00006870 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006871 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006872
Craig Topper4f12f102014-03-12 06:41:41 +00006873 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006874 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006875 }
John McCall943fae92010-05-27 06:19:26 +00006876};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006877}
John McCall943fae92010-05-27 06:19:26 +00006878
Eric Christopher7565e0d2015-05-29 23:09:49 +00006879void MipsABIInfo::CoerceToIntArgs(
6880 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006881 llvm::IntegerType *IntTy =
6882 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006883
6884 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6885 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6886 ArgList.push_back(IntTy);
6887
6888 // If necessary, add one more integer type to ArgList.
6889 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6890
6891 if (R)
6892 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006893}
6894
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006895// In N32/64, an aligned double precision floating point field is passed in
6896// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006897llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006898 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6899
6900 if (IsO32) {
6901 CoerceToIntArgs(TySize, ArgList);
6902 return llvm::StructType::get(getVMContext(), ArgList);
6903 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006904
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006905 if (Ty->isComplexType())
6906 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006907
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006908 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006909
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006910 // Unions/vectors are passed in integer registers.
6911 if (!RT || !RT->isStructureOrClassType()) {
6912 CoerceToIntArgs(TySize, ArgList);
6913 return llvm::StructType::get(getVMContext(), ArgList);
6914 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006915
6916 const RecordDecl *RD = RT->getDecl();
6917 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006918 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006919
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006920 uint64_t LastOffset = 0;
6921 unsigned idx = 0;
6922 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6923
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006924 // Iterate over fields in the struct/class and check if there are any aligned
6925 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006926 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6927 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006928 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006929 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6930
6931 if (!BT || BT->getKind() != BuiltinType::Double)
6932 continue;
6933
6934 uint64_t Offset = Layout.getFieldOffset(idx);
6935 if (Offset % 64) // Ignore doubles that are not aligned.
6936 continue;
6937
6938 // Add ((Offset - LastOffset) / 64) args of type i64.
6939 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6940 ArgList.push_back(I64);
6941
6942 // Add double type.
6943 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6944 LastOffset = Offset + 64;
6945 }
6946
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006947 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6948 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006949
6950 return llvm::StructType::get(getVMContext(), ArgList);
6951}
6952
Akira Hatanakaddd66342013-10-29 18:41:15 +00006953llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6954 uint64_t Offset) const {
6955 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006956 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006957
Akira Hatanakaddd66342013-10-29 18:41:15 +00006958 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006959}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006960
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006961ABIArgInfo
6962MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006963 Ty = useFirstFieldIfTransparentUnion(Ty);
6964
Akira Hatanaka1632af62012-01-09 19:31:25 +00006965 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006966 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006967 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006968
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006969 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6970 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006971 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6972 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006973
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006974 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006975 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006976 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006977 return ABIArgInfo::getIgnore();
6978
Mark Lacey3825e832013-10-06 01:33:34 +00006979 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006980 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006981 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006982 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006983
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006984 // If we have reached here, aggregates are passed directly by coercing to
6985 // another structure type. Padding is inserted if the offset of the
6986 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006987 ABIArgInfo ArgInfo =
6988 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6989 getPaddingType(OrigOffset, CurrOffset));
6990 ArgInfo.setInReg(true);
6991 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006992 }
6993
6994 // Treat an enum type as its underlying type.
6995 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6996 Ty = EnumTy->getDecl()->getIntegerType();
6997
Daniel Sanders5b445b32014-10-24 14:42:42 +00006998 // All integral types are promoted to the GPR width.
6999 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007000 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007001
Akira Hatanakaddd66342013-10-29 18:41:15 +00007002 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007003 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007004}
7005
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007006llvm::Type*
7007MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007008 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007009 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007010
Akira Hatanakab6f74432012-02-09 18:49:26 +00007011 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007012 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007013 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7014 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007015
Akira Hatanakab6f74432012-02-09 18:49:26 +00007016 // N32/64 returns struct/classes in floating point registers if the
7017 // following conditions are met:
7018 // 1. The size of the struct/class is no larger than 128-bit.
7019 // 2. The struct/class has one or two fields all of which are floating
7020 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007021 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007022 //
7023 // Any other composite results are returned in integer registers.
7024 //
7025 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7026 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7027 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007028 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007029
Akira Hatanakab6f74432012-02-09 18:49:26 +00007030 if (!BT || !BT->isFloatingPoint())
7031 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007032
David Blaikie2d7c57e2012-04-30 02:36:29 +00007033 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007034 }
7035
7036 if (b == e)
7037 return llvm::StructType::get(getVMContext(), RTList,
7038 RD->hasAttr<PackedAttr>());
7039
7040 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007041 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007042 }
7043
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007044 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007045 return llvm::StructType::get(getVMContext(), RTList);
7046}
7047
Akira Hatanakab579fe52011-06-02 00:09:17 +00007048ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007049 uint64_t Size = getContext().getTypeSize(RetTy);
7050
Daniel Sandersed39f582014-09-04 13:28:14 +00007051 if (RetTy->isVoidType())
7052 return ABIArgInfo::getIgnore();
7053
7054 // O32 doesn't treat zero-sized structs differently from other structs.
7055 // However, N32/N64 ignores zero sized return values.
7056 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007057 return ABIArgInfo::getIgnore();
7058
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007059 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007060 if (Size <= 128) {
7061 if (RetTy->isAnyComplexType())
7062 return ABIArgInfo::getDirect();
7063
Daniel Sanderse5018b62014-09-04 15:05:39 +00007064 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007065 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007066 if (!IsO32 ||
7067 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7068 ABIArgInfo ArgInfo =
7069 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7070 ArgInfo.setInReg(true);
7071 return ArgInfo;
7072 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007073 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007074
John McCall7f416cc2015-09-08 08:05:57 +00007075 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007076 }
7077
7078 // Treat an enum type as its underlying type.
7079 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7080 RetTy = EnumTy->getDecl()->getIntegerType();
7081
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007082 if (RetTy->isPromotableIntegerType())
7083 return ABIArgInfo::getExtend(RetTy);
7084
7085 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7086 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7087 return ABIArgInfo::getSignExtend(RetTy);
7088
7089 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007090}
7091
7092void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007093 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007094 if (!getCXXABI().classifyReturnType(FI))
7095 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007096
Eric Christopher7565e0d2015-05-29 23:09:49 +00007097 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007098 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007099
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007100 for (auto &I : FI.arguments())
7101 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007102}
7103
John McCall7f416cc2015-09-08 08:05:57 +00007104Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7105 QualType OrigTy) const {
7106 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007107
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007108 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7109 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007110 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007111 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007112 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007113 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007114 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007115 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007116 DidPromote = true;
7117 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7118 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007119 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007120
John McCall7f416cc2015-09-08 08:05:57 +00007121 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007122
John McCall7f416cc2015-09-08 08:05:57 +00007123 // The alignment of things in the argument area is never larger than
7124 // StackAlignInBytes.
7125 TyInfo.second =
7126 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7127
7128 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7129 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7130
7131 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7132 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7133
7134
7135 // If there was a promotion, "unpromote" into a temporary.
7136 // TODO: can we just use a pointer into a subset of the original slot?
7137 if (DidPromote) {
7138 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7139 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7140
7141 // Truncate down to the right width.
7142 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7143 : CGF.IntPtrTy);
7144 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7145 if (OrigTy->isPointerType())
7146 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7147
7148 CGF.Builder.CreateStore(V, Temp);
7149 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007150 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007151
John McCall7f416cc2015-09-08 08:05:57 +00007152 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007153}
7154
Alex Bradburye41a5e22018-01-12 20:08:16 +00007155ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007156 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007157
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007158 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7159 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007160 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007161
Alex Bradburye41a5e22018-01-12 20:08:16 +00007162 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007163}
7164
John McCall943fae92010-05-27 06:19:26 +00007165bool
7166MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7167 llvm::Value *Address) const {
7168 // This information comes from gcc's implementation, which seems to
7169 // as canonical as it gets.
7170
John McCall943fae92010-05-27 06:19:26 +00007171 // Everything on MIPS is 4 bytes. Double-precision FP registers
7172 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007173 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007174
7175 // 0-31 are the general purpose registers, $0 - $31.
7176 // 32-63 are the floating-point registers, $f0 - $f31.
7177 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7178 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007179 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007180
7181 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7182 // They are one bit wide and ignored here.
7183
7184 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7185 // (coprocessor 1 is the FP unit)
7186 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7187 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7188 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007189 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007190 return false;
7191}
7192
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007193//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007194// AVR ABI Implementation.
7195//===----------------------------------------------------------------------===//
7196
7197namespace {
7198class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7199public:
7200 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7201 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7202
7203 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007204 CodeGen::CodeGenModule &CGM) const override {
7205 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007206 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007207 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7208 if (!FD) return;
7209 auto *Fn = cast<llvm::Function>(GV);
7210
7211 if (FD->getAttr<AVRInterruptAttr>())
7212 Fn->addFnAttr("interrupt");
7213
7214 if (FD->getAttr<AVRSignalAttr>())
7215 Fn->addFnAttr("signal");
7216 }
7217};
7218}
7219
7220//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007221// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007222// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007223// handling.
7224//===----------------------------------------------------------------------===//
7225
7226namespace {
7227
7228class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7229public:
7230 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7231 : DefaultTargetCodeGenInfo(CGT) {}
7232
Eric Christopher162c91c2015-06-05 22:03:00 +00007233 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007234 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007235};
7236
Eric Christopher162c91c2015-06-05 22:03:00 +00007237void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007238 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7239 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007240 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007241 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007242 if (!FD) return;
7243
7244 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007245
David Blaikiebbafb8a2012-03-11 07:00:24 +00007246 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007247 if (FD->hasAttr<OpenCLKernelAttr>()) {
7248 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007249 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007250 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7251 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007252 // Convert the reqd_work_group_size() attributes to metadata.
7253 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007254 llvm::NamedMDNode *OpenCLMetadata =
7255 M.getModule().getOrInsertNamedMetadata(
7256 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007257
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007258 SmallVector<llvm::Metadata *, 5> Operands;
7259 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007260
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007261 Operands.push_back(
7262 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7263 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7264 Operands.push_back(
7265 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7266 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7267 Operands.push_back(
7268 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7269 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007270
Eric Christopher7565e0d2015-05-29 23:09:49 +00007271 // Add a boolean constant operand for "required" (true) or "hint"
7272 // (false) for implementing the work_group_size_hint attr later.
7273 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007274 Operands.push_back(
7275 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007276 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7277 }
7278 }
7279 }
7280}
7281
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007282}
John McCall943fae92010-05-27 06:19:26 +00007283
Tony Linthicum76329bf2011-12-12 21:14:55 +00007284//===----------------------------------------------------------------------===//
7285// Hexagon ABI Implementation
7286//===----------------------------------------------------------------------===//
7287
7288namespace {
7289
7290class HexagonABIInfo : public ABIInfo {
7291
7292
7293public:
7294 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7295
7296private:
7297
7298 ABIArgInfo classifyReturnType(QualType RetTy) const;
7299 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7300
Craig Topper4f12f102014-03-12 06:41:41 +00007301 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007302
John McCall7f416cc2015-09-08 08:05:57 +00007303 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7304 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007305};
7306
7307class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7308public:
7309 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7310 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7311
Craig Topper4f12f102014-03-12 06:41:41 +00007312 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007313 return 29;
7314 }
7315};
7316
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007317}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007318
7319void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007320 if (!getCXXABI().classifyReturnType(FI))
7321 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007322 for (auto &I : FI.arguments())
7323 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007324}
7325
7326ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7327 if (!isAggregateTypeForABI(Ty)) {
7328 // Treat an enum type as its underlying type.
7329 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7330 Ty = EnumTy->getDecl()->getIntegerType();
7331
Alex Bradburye41a5e22018-01-12 20:08:16 +00007332 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7333 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007334 }
7335
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007336 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7337 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7338
Tony Linthicum76329bf2011-12-12 21:14:55 +00007339 // Ignore empty records.
7340 if (isEmptyRecord(getContext(), Ty, true))
7341 return ABIArgInfo::getIgnore();
7342
Tony Linthicum76329bf2011-12-12 21:14:55 +00007343 uint64_t Size = getContext().getTypeSize(Ty);
7344 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007345 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007346 // Pass in the smallest viable integer type.
7347 else if (Size > 32)
7348 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7349 else if (Size > 16)
7350 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7351 else if (Size > 8)
7352 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7353 else
7354 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7355}
7356
7357ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7358 if (RetTy->isVoidType())
7359 return ABIArgInfo::getIgnore();
7360
7361 // Large vector types should be returned via memory.
7362 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007363 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007364
7365 if (!isAggregateTypeForABI(RetTy)) {
7366 // Treat an enum type as its underlying type.
7367 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7368 RetTy = EnumTy->getDecl()->getIntegerType();
7369
Alex Bradburye41a5e22018-01-12 20:08:16 +00007370 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7371 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007372 }
7373
Tony Linthicum76329bf2011-12-12 21:14:55 +00007374 if (isEmptyRecord(getContext(), RetTy, true))
7375 return ABIArgInfo::getIgnore();
7376
7377 // Aggregates <= 8 bytes are returned in r0; other aggregates
7378 // are returned indirectly.
7379 uint64_t Size = getContext().getTypeSize(RetTy);
7380 if (Size <= 64) {
7381 // Return in the smallest viable integer type.
7382 if (Size <= 8)
7383 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7384 if (Size <= 16)
7385 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7386 if (Size <= 32)
7387 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7388 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7389 }
7390
John McCall7f416cc2015-09-08 08:05:57 +00007391 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007392}
7393
John McCall7f416cc2015-09-08 08:05:57 +00007394Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7395 QualType Ty) const {
7396 // FIXME: Someone needs to audit that this handle alignment correctly.
7397 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7398 getContext().getTypeInfoInChars(Ty),
7399 CharUnits::fromQuantity(4),
7400 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007401}
7402
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007403//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007404// Lanai ABI Implementation
7405//===----------------------------------------------------------------------===//
7406
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007407namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007408class LanaiABIInfo : public DefaultABIInfo {
7409public:
7410 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7411
7412 bool shouldUseInReg(QualType Ty, CCState &State) const;
7413
7414 void computeInfo(CGFunctionInfo &FI) const override {
7415 CCState State(FI.getCallingConvention());
7416 // Lanai uses 4 registers to pass arguments unless the function has the
7417 // regparm attribute set.
7418 if (FI.getHasRegParm()) {
7419 State.FreeRegs = FI.getRegParm();
7420 } else {
7421 State.FreeRegs = 4;
7422 }
7423
7424 if (!getCXXABI().classifyReturnType(FI))
7425 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7426 for (auto &I : FI.arguments())
7427 I.info = classifyArgumentType(I.type, State);
7428 }
7429
Jacques Pienaare74d9132016-04-26 00:09:29 +00007430 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007431 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7432};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007433} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007434
7435bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7436 unsigned Size = getContext().getTypeSize(Ty);
7437 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7438
7439 if (SizeInRegs == 0)
7440 return false;
7441
7442 if (SizeInRegs > State.FreeRegs) {
7443 State.FreeRegs = 0;
7444 return false;
7445 }
7446
7447 State.FreeRegs -= SizeInRegs;
7448
7449 return true;
7450}
7451
Jacques Pienaare74d9132016-04-26 00:09:29 +00007452ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7453 CCState &State) const {
7454 if (!ByVal) {
7455 if (State.FreeRegs) {
7456 --State.FreeRegs; // Non-byval indirects just use one pointer.
7457 return getNaturalAlignIndirectInReg(Ty);
7458 }
7459 return getNaturalAlignIndirect(Ty, false);
7460 }
7461
7462 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007463 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007464 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7465 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7466 /*Realign=*/TypeAlign >
7467 MinABIStackAlignInBytes);
7468}
7469
Jacques Pienaard964cc22016-03-28 21:02:54 +00007470ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7471 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007472 // Check with the C++ ABI first.
7473 const RecordType *RT = Ty->getAs<RecordType>();
7474 if (RT) {
7475 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7476 if (RAA == CGCXXABI::RAA_Indirect) {
7477 return getIndirectResult(Ty, /*ByVal=*/false, State);
7478 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7479 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7480 }
7481 }
7482
7483 if (isAggregateTypeForABI(Ty)) {
7484 // Structures with flexible arrays are always indirect.
7485 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7486 return getIndirectResult(Ty, /*ByVal=*/true, State);
7487
7488 // Ignore empty structs/unions.
7489 if (isEmptyRecord(getContext(), Ty, true))
7490 return ABIArgInfo::getIgnore();
7491
7492 llvm::LLVMContext &LLVMContext = getVMContext();
7493 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7494 if (SizeInRegs <= State.FreeRegs) {
7495 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7496 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7497 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7498 State.FreeRegs -= SizeInRegs;
7499 return ABIArgInfo::getDirectInReg(Result);
7500 } else {
7501 State.FreeRegs = 0;
7502 }
7503 return getIndirectResult(Ty, true, State);
7504 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007505
7506 // Treat an enum type as its underlying type.
7507 if (const auto *EnumTy = Ty->getAs<EnumType>())
7508 Ty = EnumTy->getDecl()->getIntegerType();
7509
Jacques Pienaare74d9132016-04-26 00:09:29 +00007510 bool InReg = shouldUseInReg(Ty, State);
7511 if (Ty->isPromotableIntegerType()) {
7512 if (InReg)
7513 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007514 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007515 }
7516 if (InReg)
7517 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007518 return ABIArgInfo::getDirect();
7519}
7520
7521namespace {
7522class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7523public:
7524 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7525 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7526};
7527}
7528
7529//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007530// AMDGPU ABI Implementation
7531//===----------------------------------------------------------------------===//
7532
7533namespace {
7534
Matt Arsenault88d7da02016-08-22 19:25:59 +00007535class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007536private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007537 static const unsigned MaxNumRegsForArgsRet = 16;
7538
Matt Arsenault3fe73952017-08-09 21:44:58 +00007539 unsigned numRegsForType(QualType Ty) const;
7540
7541 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7542 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7543 uint64_t Members) const override;
7544
7545public:
7546 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7547 DefaultABIInfo(CGT) {}
7548
7549 ABIArgInfo classifyReturnType(QualType RetTy) const;
7550 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7551 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007552
7553 void computeInfo(CGFunctionInfo &FI) const override;
7554};
7555
Matt Arsenault3fe73952017-08-09 21:44:58 +00007556bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7557 return true;
7558}
7559
7560bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7561 const Type *Base, uint64_t Members) const {
7562 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7563
7564 // Homogeneous Aggregates may occupy at most 16 registers.
7565 return Members * NumRegs <= MaxNumRegsForArgsRet;
7566}
7567
Matt Arsenault3fe73952017-08-09 21:44:58 +00007568/// Estimate number of registers the type will use when passed in registers.
7569unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7570 unsigned NumRegs = 0;
7571
7572 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7573 // Compute from the number of elements. The reported size is based on the
7574 // in-memory size, which includes the padding 4th element for 3-vectors.
7575 QualType EltTy = VT->getElementType();
7576 unsigned EltSize = getContext().getTypeSize(EltTy);
7577
7578 // 16-bit element vectors should be passed as packed.
7579 if (EltSize == 16)
7580 return (VT->getNumElements() + 1) / 2;
7581
7582 unsigned EltNumRegs = (EltSize + 31) / 32;
7583 return EltNumRegs * VT->getNumElements();
7584 }
7585
7586 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7587 const RecordDecl *RD = RT->getDecl();
7588 assert(!RD->hasFlexibleArrayMember());
7589
7590 for (const FieldDecl *Field : RD->fields()) {
7591 QualType FieldTy = Field->getType();
7592 NumRegs += numRegsForType(FieldTy);
7593 }
7594
7595 return NumRegs;
7596 }
7597
7598 return (getContext().getTypeSize(Ty) + 31) / 32;
7599}
7600
Matt Arsenault88d7da02016-08-22 19:25:59 +00007601void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007602 llvm::CallingConv::ID CC = FI.getCallingConvention();
7603
Matt Arsenault88d7da02016-08-22 19:25:59 +00007604 if (!getCXXABI().classifyReturnType(FI))
7605 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7606
Matt Arsenault3fe73952017-08-09 21:44:58 +00007607 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7608 for (auto &Arg : FI.arguments()) {
7609 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7610 Arg.info = classifyKernelArgumentType(Arg.type);
7611 } else {
7612 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7613 }
7614 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007615}
7616
Matt Arsenault3fe73952017-08-09 21:44:58 +00007617ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7618 if (isAggregateTypeForABI(RetTy)) {
7619 // Records with non-trivial destructors/copy-constructors should not be
7620 // returned by value.
7621 if (!getRecordArgABI(RetTy, getCXXABI())) {
7622 // Ignore empty structs/unions.
7623 if (isEmptyRecord(getContext(), RetTy, true))
7624 return ABIArgInfo::getIgnore();
7625
7626 // Lower single-element structs to just return a regular value.
7627 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7628 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7629
7630 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7631 const RecordDecl *RD = RT->getDecl();
7632 if (RD->hasFlexibleArrayMember())
7633 return DefaultABIInfo::classifyReturnType(RetTy);
7634 }
7635
7636 // Pack aggregates <= 4 bytes into single VGPR or pair.
7637 uint64_t Size = getContext().getTypeSize(RetTy);
7638 if (Size <= 16)
7639 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7640
7641 if (Size <= 32)
7642 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7643
7644 if (Size <= 64) {
7645 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7646 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7647 }
7648
7649 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7650 return ABIArgInfo::getDirect();
7651 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007652 }
7653
Matt Arsenault3fe73952017-08-09 21:44:58 +00007654 // Otherwise just do the default thing.
7655 return DefaultABIInfo::classifyReturnType(RetTy);
7656}
7657
7658/// For kernels all parameters are really passed in a special buffer. It doesn't
7659/// make sense to pass anything byval, so everything must be direct.
7660ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7661 Ty = useFirstFieldIfTransparentUnion(Ty);
7662
7663 // TODO: Can we omit empty structs?
7664
Matt Arsenault88d7da02016-08-22 19:25:59 +00007665 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007666 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7667 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007668
7669 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7670 // individual elements, which confuses the Clover OpenCL backend; therefore we
7671 // have to set it to false here. Other args of getDirect() are just defaults.
7672 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7673}
7674
Matt Arsenault3fe73952017-08-09 21:44:58 +00007675ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7676 unsigned &NumRegsLeft) const {
7677 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7678
7679 Ty = useFirstFieldIfTransparentUnion(Ty);
7680
7681 if (isAggregateTypeForABI(Ty)) {
7682 // Records with non-trivial destructors/copy-constructors should not be
7683 // passed by value.
7684 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7685 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7686
7687 // Ignore empty structs/unions.
7688 if (isEmptyRecord(getContext(), Ty, true))
7689 return ABIArgInfo::getIgnore();
7690
7691 // Lower single-element structs to just pass a regular value. TODO: We
7692 // could do reasonable-size multiple-element structs too, using getExpand(),
7693 // though watch out for things like bitfields.
7694 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7695 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7696
7697 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7698 const RecordDecl *RD = RT->getDecl();
7699 if (RD->hasFlexibleArrayMember())
7700 return DefaultABIInfo::classifyArgumentType(Ty);
7701 }
7702
7703 // Pack aggregates <= 8 bytes into single VGPR or pair.
7704 uint64_t Size = getContext().getTypeSize(Ty);
7705 if (Size <= 64) {
7706 unsigned NumRegs = (Size + 31) / 32;
7707 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7708
7709 if (Size <= 16)
7710 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7711
7712 if (Size <= 32)
7713 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7714
7715 // XXX: Should this be i64 instead, and should the limit increase?
7716 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7717 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7718 }
7719
7720 if (NumRegsLeft > 0) {
7721 unsigned NumRegs = numRegsForType(Ty);
7722 if (NumRegsLeft >= NumRegs) {
7723 NumRegsLeft -= NumRegs;
7724 return ABIArgInfo::getDirect();
7725 }
7726 }
7727 }
7728
7729 // Otherwise just do the default thing.
7730 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7731 if (!ArgInfo.isIndirect()) {
7732 unsigned NumRegs = numRegsForType(Ty);
7733 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7734 }
7735
7736 return ArgInfo;
7737}
7738
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007739class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7740public:
7741 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007742 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007743 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007744 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007745 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007746
Yaxun Liu402804b2016-12-15 08:09:08 +00007747 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7748 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007749
Alexander Richardson6d989432017-10-15 18:48:14 +00007750 LangAS getASTAllocaAddressSpace() const override {
7751 return getLangASFromTargetAS(
7752 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007753 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007754 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7755 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007756 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7757 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007758 llvm::Function *
7759 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7760 llvm::Function *BlockInvokeFunc,
7761 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007762 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007763 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007764};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007765}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007766
Eric Christopher162c91c2015-06-05 22:03:00 +00007767void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007768 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7769 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007770 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007771 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007772 if (!FD)
7773 return;
7774
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007775 llvm::Function *F = cast<llvm::Function>(GV);
7776
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007777 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7778 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007779
7780 if (M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>() &&
7781 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Tony Tye68e11a62018-03-23 18:51:45 +00007782 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007783
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007784 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7785 if (ReqdWGS || FlatWGS) {
7786 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7787 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7788 if (ReqdWGS && Min == 0 && Max == 0)
7789 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007790
7791 if (Min != 0) {
7792 assert(Min <= Max && "Min must be less than or equal Max");
7793
7794 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7795 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7796 } else
7797 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007798 }
7799
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007800 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7801 unsigned Min = Attr->getMin();
7802 unsigned Max = Attr->getMax();
7803
7804 if (Min != 0) {
7805 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7806
7807 std::string AttrVal = llvm::utostr(Min);
7808 if (Max != 0)
7809 AttrVal = AttrVal + "," + llvm::utostr(Max);
7810 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7811 } else
7812 assert(Max == 0 && "Max must be zero");
7813 }
7814
7815 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007816 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007817
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007818 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007819 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7820 }
7821
7822 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7823 uint32_t NumVGPR = Attr->getNumVGPR();
7824
7825 if (NumVGPR != 0)
7826 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007827 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007828}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007829
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007830unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7831 return llvm::CallingConv::AMDGPU_KERNEL;
7832}
7833
Yaxun Liu402804b2016-12-15 08:09:08 +00007834// Currently LLVM assumes null pointers always have value 0,
7835// which results in incorrectly transformed IR. Therefore, instead of
7836// emitting null pointers in private and local address spaces, a null
7837// pointer in generic address space is emitted which is casted to a
7838// pointer in local or private address space.
7839llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7840 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7841 QualType QT) const {
7842 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7843 return llvm::ConstantPointerNull::get(PT);
7844
7845 auto &Ctx = CGM.getContext();
7846 auto NPT = llvm::PointerType::get(PT->getElementType(),
7847 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7848 return llvm::ConstantExpr::getAddrSpaceCast(
7849 llvm::ConstantPointerNull::get(NPT), PT);
7850}
7851
Alexander Richardson6d989432017-10-15 18:48:14 +00007852LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007853AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7854 const VarDecl *D) const {
7855 assert(!CGM.getLangOpts().OpenCL &&
7856 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7857 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007858 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7859 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007860 if (!D)
7861 return DefaultGlobalAS;
7862
Alexander Richardson6d989432017-10-15 18:48:14 +00007863 LangAS AddrSpace = D->getType().getAddressSpace();
7864 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007865 if (AddrSpace != LangAS::Default)
7866 return AddrSpace;
7867
7868 if (CGM.isTypeConstant(D->getType(), false)) {
7869 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7870 return ConstAS.getValue();
7871 }
7872 return DefaultGlobalAS;
7873}
7874
Yaxun Liu39195062017-08-04 18:16:31 +00007875llvm::SyncScope::ID
7876AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7877 llvm::LLVMContext &C) const {
7878 StringRef Name;
7879 switch (S) {
7880 case SyncScope::OpenCLWorkGroup:
7881 Name = "workgroup";
7882 break;
7883 case SyncScope::OpenCLDevice:
7884 Name = "agent";
7885 break;
7886 case SyncScope::OpenCLAllSVMDevices:
7887 Name = "";
7888 break;
7889 case SyncScope::OpenCLSubGroup:
7890 Name = "subgroup";
7891 }
7892 return C.getOrInsertSyncScopeID(Name);
7893}
7894
Yaxun Liub0eee292018-03-29 14:50:00 +00007895bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7896 return false;
7897}
7898
Yaxun Liu4306f202018-04-20 17:01:03 +00007899void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00007900 const FunctionType *&FT) const {
7901 FT = getABIInfo().getContext().adjustFunctionType(
7902 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00007903}
7904
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007905//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007906// SPARC v8 ABI Implementation.
7907// Based on the SPARC Compliance Definition version 2.4.1.
7908//
7909// Ensures that complex values are passed in registers.
7910//
7911namespace {
7912class SparcV8ABIInfo : public DefaultABIInfo {
7913public:
7914 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7915
7916private:
7917 ABIArgInfo classifyReturnType(QualType RetTy) const;
7918 void computeInfo(CGFunctionInfo &FI) const override;
7919};
7920} // end anonymous namespace
7921
7922
7923ABIArgInfo
7924SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7925 if (Ty->isAnyComplexType()) {
7926 return ABIArgInfo::getDirect();
7927 }
7928 else {
7929 return DefaultABIInfo::classifyReturnType(Ty);
7930 }
7931}
7932
7933void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7934
7935 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7936 for (auto &Arg : FI.arguments())
7937 Arg.info = classifyArgumentType(Arg.type);
7938}
7939
7940namespace {
7941class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7942public:
7943 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7944 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7945};
7946} // end anonymous namespace
7947
7948//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007949// SPARC v9 ABI Implementation.
7950// Based on the SPARC Compliance Definition version 2.4.1.
7951//
7952// Function arguments a mapped to a nominal "parameter array" and promoted to
7953// registers depending on their type. Each argument occupies 8 or 16 bytes in
7954// the array, structs larger than 16 bytes are passed indirectly.
7955//
7956// One case requires special care:
7957//
7958// struct mixed {
7959// int i;
7960// float f;
7961// };
7962//
7963// When a struct mixed is passed by value, it only occupies 8 bytes in the
7964// parameter array, but the int is passed in an integer register, and the float
7965// is passed in a floating point register. This is represented as two arguments
7966// with the LLVM IR inreg attribute:
7967//
7968// declare void f(i32 inreg %i, float inreg %f)
7969//
7970// The code generator will only allocate 4 bytes from the parameter array for
7971// the inreg arguments. All other arguments are allocated a multiple of 8
7972// bytes.
7973//
7974namespace {
7975class SparcV9ABIInfo : public ABIInfo {
7976public:
7977 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7978
7979private:
7980 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007981 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007982 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7983 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007984
7985 // Coercion type builder for structs passed in registers. The coercion type
7986 // serves two purposes:
7987 //
7988 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7989 // in registers.
7990 // 2. Expose aligned floating point elements as first-level elements, so the
7991 // code generator knows to pass them in floating point registers.
7992 //
7993 // We also compute the InReg flag which indicates that the struct contains
7994 // aligned 32-bit floats.
7995 //
7996 struct CoerceBuilder {
7997 llvm::LLVMContext &Context;
7998 const llvm::DataLayout &DL;
7999 SmallVector<llvm::Type*, 8> Elems;
8000 uint64_t Size;
8001 bool InReg;
8002
8003 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8004 : Context(c), DL(dl), Size(0), InReg(false) {}
8005
8006 // Pad Elems with integers until Size is ToSize.
8007 void pad(uint64_t ToSize) {
8008 assert(ToSize >= Size && "Cannot remove elements");
8009 if (ToSize == Size)
8010 return;
8011
8012 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008013 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008014 if (Aligned > Size && Aligned <= ToSize) {
8015 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8016 Size = Aligned;
8017 }
8018
8019 // Add whole 64-bit words.
8020 while (Size + 64 <= ToSize) {
8021 Elems.push_back(llvm::Type::getInt64Ty(Context));
8022 Size += 64;
8023 }
8024
8025 // Final in-word padding.
8026 if (Size < ToSize) {
8027 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8028 Size = ToSize;
8029 }
8030 }
8031
8032 // Add a floating point element at Offset.
8033 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8034 // Unaligned floats are treated as integers.
8035 if (Offset % Bits)
8036 return;
8037 // The InReg flag is only required if there are any floats < 64 bits.
8038 if (Bits < 64)
8039 InReg = true;
8040 pad(Offset);
8041 Elems.push_back(Ty);
8042 Size = Offset + Bits;
8043 }
8044
8045 // Add a struct type to the coercion type, starting at Offset (in bits).
8046 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8047 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8048 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8049 llvm::Type *ElemTy = StrTy->getElementType(i);
8050 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8051 switch (ElemTy->getTypeID()) {
8052 case llvm::Type::StructTyID:
8053 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8054 break;
8055 case llvm::Type::FloatTyID:
8056 addFloat(ElemOffset, ElemTy, 32);
8057 break;
8058 case llvm::Type::DoubleTyID:
8059 addFloat(ElemOffset, ElemTy, 64);
8060 break;
8061 case llvm::Type::FP128TyID:
8062 addFloat(ElemOffset, ElemTy, 128);
8063 break;
8064 case llvm::Type::PointerTyID:
8065 if (ElemOffset % 64 == 0) {
8066 pad(ElemOffset);
8067 Elems.push_back(ElemTy);
8068 Size += 64;
8069 }
8070 break;
8071 default:
8072 break;
8073 }
8074 }
8075 }
8076
8077 // Check if Ty is a usable substitute for the coercion type.
8078 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008079 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008080 }
8081
8082 // Get the coercion type as a literal struct type.
8083 llvm::Type *getType() const {
8084 if (Elems.size() == 1)
8085 return Elems.front();
8086 else
8087 return llvm::StructType::get(Context, Elems);
8088 }
8089 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008090};
8091} // end anonymous namespace
8092
8093ABIArgInfo
8094SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8095 if (Ty->isVoidType())
8096 return ABIArgInfo::getIgnore();
8097
8098 uint64_t Size = getContext().getTypeSize(Ty);
8099
8100 // Anything too big to fit in registers is passed with an explicit indirect
8101 // pointer / sret pointer.
8102 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008103 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008104
8105 // Treat an enum type as its underlying type.
8106 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8107 Ty = EnumTy->getDecl()->getIntegerType();
8108
8109 // Integer types smaller than a register are extended.
8110 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008111 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008112
8113 // Other non-aggregates go in registers.
8114 if (!isAggregateTypeForABI(Ty))
8115 return ABIArgInfo::getDirect();
8116
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008117 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8118 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8119 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008120 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008121
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008122 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008123 // Build a coercion type from the LLVM struct type.
8124 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8125 if (!StrTy)
8126 return ABIArgInfo::getDirect();
8127
8128 CoerceBuilder CB(getVMContext(), getDataLayout());
8129 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008130 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008131
8132 // Try to use the original type for coercion.
8133 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8134
8135 if (CB.InReg)
8136 return ABIArgInfo::getDirectInReg(CoerceTy);
8137 else
8138 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008139}
8140
John McCall7f416cc2015-09-08 08:05:57 +00008141Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8142 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008143 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8144 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8145 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8146 AI.setCoerceToType(ArgTy);
8147
John McCall7f416cc2015-09-08 08:05:57 +00008148 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008149
John McCall7f416cc2015-09-08 08:05:57 +00008150 CGBuilderTy &Builder = CGF.Builder;
8151 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8152 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8153
8154 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8155
8156 Address ArgAddr = Address::invalid();
8157 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008158 switch (AI.getKind()) {
8159 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008160 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008161 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008162 llvm_unreachable("Unsupported ABI kind for va_arg");
8163
John McCall7f416cc2015-09-08 08:05:57 +00008164 case ABIArgInfo::Extend: {
8165 Stride = SlotSize;
8166 CharUnits Offset = SlotSize - TypeInfo.first;
8167 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008168 break;
John McCall7f416cc2015-09-08 08:05:57 +00008169 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008170
John McCall7f416cc2015-09-08 08:05:57 +00008171 case ABIArgInfo::Direct: {
8172 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008173 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008174 ArgAddr = Addr;
8175 break;
John McCall7f416cc2015-09-08 08:05:57 +00008176 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008177
8178 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008179 Stride = SlotSize;
8180 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8181 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8182 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008183 break;
8184
8185 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008186 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008187 }
8188
8189 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008190 llvm::Value *NextPtr =
8191 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8192 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008193
John McCall7f416cc2015-09-08 08:05:57 +00008194 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008195}
8196
8197void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8198 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008199 for (auto &I : FI.arguments())
8200 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008201}
8202
8203namespace {
8204class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8205public:
8206 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8207 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008208
Craig Topper4f12f102014-03-12 06:41:41 +00008209 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008210 return 14;
8211 }
8212
8213 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008214 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008215};
8216} // end anonymous namespace
8217
Roman Divackyf02c9942014-02-24 18:46:27 +00008218bool
8219SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8220 llvm::Value *Address) const {
8221 // This is calculated from the LLVM and GCC tables and verified
8222 // against gcc output. AFAIK all ABIs use the same encoding.
8223
8224 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8225
8226 llvm::IntegerType *i8 = CGF.Int8Ty;
8227 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8228 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8229
8230 // 0-31: the 8-byte general-purpose registers
8231 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8232
8233 // 32-63: f0-31, the 4-byte floating-point registers
8234 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8235
8236 // Y = 64
8237 // PSR = 65
8238 // WIM = 66
8239 // TBR = 67
8240 // PC = 68
8241 // NPC = 69
8242 // FSR = 70
8243 // CSR = 71
8244 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008245
Roman Divackyf02c9942014-02-24 18:46:27 +00008246 // 72-87: d0-15, the 8-byte floating-point registers
8247 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8248
8249 return false;
8250}
8251
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008252
Robert Lytton0e076492013-08-13 09:43:10 +00008253//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008254// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008255//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008256
Robert Lytton0e076492013-08-13 09:43:10 +00008257namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008258
8259/// A SmallStringEnc instance is used to build up the TypeString by passing
8260/// it by reference between functions that append to it.
8261typedef llvm::SmallString<128> SmallStringEnc;
8262
8263/// TypeStringCache caches the meta encodings of Types.
8264///
8265/// The reason for caching TypeStrings is two fold:
8266/// 1. To cache a type's encoding for later uses;
8267/// 2. As a means to break recursive member type inclusion.
8268///
8269/// A cache Entry can have a Status of:
8270/// NonRecursive: The type encoding is not recursive;
8271/// Recursive: The type encoding is recursive;
8272/// Incomplete: An incomplete TypeString;
8273/// IncompleteUsed: An incomplete TypeString that has been used in a
8274/// Recursive type encoding.
8275///
8276/// A NonRecursive entry will have all of its sub-members expanded as fully
8277/// as possible. Whilst it may contain types which are recursive, the type
8278/// itself is not recursive and thus its encoding may be safely used whenever
8279/// the type is encountered.
8280///
8281/// A Recursive entry will have all of its sub-members expanded as fully as
8282/// possible. The type itself is recursive and it may contain other types which
8283/// are recursive. The Recursive encoding must not be used during the expansion
8284/// of a recursive type's recursive branch. For simplicity the code uses
8285/// IncompleteCount to reject all usage of Recursive encodings for member types.
8286///
8287/// An Incomplete entry is always a RecordType and only encodes its
8288/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8289/// are placed into the cache during type expansion as a means to identify and
8290/// handle recursive inclusion of types as sub-members. If there is recursion
8291/// the entry becomes IncompleteUsed.
8292///
8293/// During the expansion of a RecordType's members:
8294///
8295/// If the cache contains a NonRecursive encoding for the member type, the
8296/// cached encoding is used;
8297///
8298/// If the cache contains a Recursive encoding for the member type, the
8299/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8300///
8301/// If the member is a RecordType, an Incomplete encoding is placed into the
8302/// cache to break potential recursive inclusion of itself as a sub-member;
8303///
8304/// Once a member RecordType has been expanded, its temporary incomplete
8305/// entry is removed from the cache. If a Recursive encoding was swapped out
8306/// it is swapped back in;
8307///
8308/// If an incomplete entry is used to expand a sub-member, the incomplete
8309/// entry is marked as IncompleteUsed. The cache keeps count of how many
8310/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8311///
8312/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8313/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8314/// Else the member is part of a recursive type and thus the recursion has
8315/// been exited too soon for the encoding to be correct for the member.
8316///
8317class TypeStringCache {
8318 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8319 struct Entry {
8320 std::string Str; // The encoded TypeString for the type.
8321 enum Status State; // Information about the encoding in 'Str'.
8322 std::string Swapped; // A temporary place holder for a Recursive encoding
8323 // during the expansion of RecordType's members.
8324 };
8325 std::map<const IdentifierInfo *, struct Entry> Map;
8326 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8327 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8328public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008329 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008330 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8331 bool removeIncomplete(const IdentifierInfo *ID);
8332 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8333 bool IsRecursive);
8334 StringRef lookupStr(const IdentifierInfo *ID);
8335};
8336
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008337/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008338/// FieldEncoding is a helper for this ordering process.
8339class FieldEncoding {
8340 bool HasName;
8341 std::string Enc;
8342public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008343 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008344 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008345 bool operator<(const FieldEncoding &rhs) const {
8346 if (HasName != rhs.HasName) return HasName;
8347 return Enc < rhs.Enc;
8348 }
8349};
8350
Robert Lytton7d1db152013-08-19 09:46:39 +00008351class XCoreABIInfo : public DefaultABIInfo {
8352public:
8353 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008354 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8355 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008356};
8357
Robert Lyttond21e2d72014-03-03 13:45:29 +00008358class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008359 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008360public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008361 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008362 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008363 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8364 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008365};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008366
Robert Lytton2d196952013-10-11 10:29:34 +00008367} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008368
James Y Knight29b5f082016-02-24 02:59:33 +00008369// TODO: this implementation is likely now redundant with the default
8370// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008371Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8372 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008373 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008374
Robert Lytton2d196952013-10-11 10:29:34 +00008375 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008376 CharUnits SlotSize = CharUnits::fromQuantity(4);
8377 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008378
Robert Lytton2d196952013-10-11 10:29:34 +00008379 // Handle the argument.
8380 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008381 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008382 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8383 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8384 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008385 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008386
8387 Address Val = Address::invalid();
8388 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008389 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008390 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008391 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008392 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008393 llvm_unreachable("Unsupported ABI kind for va_arg");
8394 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008395 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8396 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008397 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008398 case ABIArgInfo::Extend:
8399 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008400 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8401 ArgSize = CharUnits::fromQuantity(
8402 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008403 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008404 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008405 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008406 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8407 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8408 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008409 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008410 }
Robert Lytton2d196952013-10-11 10:29:34 +00008411
8412 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008413 if (!ArgSize.isZero()) {
8414 llvm::Value *APN =
8415 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8416 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008417 }
John McCall7f416cc2015-09-08 08:05:57 +00008418
Robert Lytton2d196952013-10-11 10:29:34 +00008419 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008420}
Robert Lytton0e076492013-08-13 09:43:10 +00008421
Robert Lytton844aeeb2014-05-02 09:33:20 +00008422/// During the expansion of a RecordType, an incomplete TypeString is placed
8423/// into the cache as a means to identify and break recursion.
8424/// If there is a Recursive encoding in the cache, it is swapped out and will
8425/// be reinserted by removeIncomplete().
8426/// All other types of encoding should have been used rather than arriving here.
8427void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8428 std::string StubEnc) {
8429 if (!ID)
8430 return;
8431 Entry &E = Map[ID];
8432 assert( (E.Str.empty() || E.State == Recursive) &&
8433 "Incorrectly use of addIncomplete");
8434 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8435 E.Swapped.swap(E.Str); // swap out the Recursive
8436 E.Str.swap(StubEnc);
8437 E.State = Incomplete;
8438 ++IncompleteCount;
8439}
8440
8441/// Once the RecordType has been expanded, the temporary incomplete TypeString
8442/// must be removed from the cache.
8443/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8444/// Returns true if the RecordType was defined recursively.
8445bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8446 if (!ID)
8447 return false;
8448 auto I = Map.find(ID);
8449 assert(I != Map.end() && "Entry not present");
8450 Entry &E = I->second;
8451 assert( (E.State == Incomplete ||
8452 E.State == IncompleteUsed) &&
8453 "Entry must be an incomplete type");
8454 bool IsRecursive = false;
8455 if (E.State == IncompleteUsed) {
8456 // We made use of our Incomplete encoding, thus we are recursive.
8457 IsRecursive = true;
8458 --IncompleteUsedCount;
8459 }
8460 if (E.Swapped.empty())
8461 Map.erase(I);
8462 else {
8463 // Swap the Recursive back.
8464 E.Swapped.swap(E.Str);
8465 E.Swapped.clear();
8466 E.State = Recursive;
8467 }
8468 --IncompleteCount;
8469 return IsRecursive;
8470}
8471
8472/// Add the encoded TypeString to the cache only if it is NonRecursive or
8473/// Recursive (viz: all sub-members were expanded as fully as possible).
8474void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8475 bool IsRecursive) {
8476 if (!ID || IncompleteUsedCount)
8477 return; // No key or it is is an incomplete sub-type so don't add.
8478 Entry &E = Map[ID];
8479 if (IsRecursive && !E.Str.empty()) {
8480 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8481 "This is not the same Recursive entry");
8482 // The parent container was not recursive after all, so we could have used
8483 // this Recursive sub-member entry after all, but we assumed the worse when
8484 // we started viz: IncompleteCount!=0.
8485 return;
8486 }
8487 assert(E.Str.empty() && "Entry already present");
8488 E.Str = Str.str();
8489 E.State = IsRecursive? Recursive : NonRecursive;
8490}
8491
8492/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8493/// are recursively expanding a type (IncompleteCount != 0) and the cached
8494/// encoding is Recursive, return an empty StringRef.
8495StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8496 if (!ID)
8497 return StringRef(); // We have no key.
8498 auto I = Map.find(ID);
8499 if (I == Map.end())
8500 return StringRef(); // We have no encoding.
8501 Entry &E = I->second;
8502 if (E.State == Recursive && IncompleteCount)
8503 return StringRef(); // We don't use Recursive encodings for member types.
8504
8505 if (E.State == Incomplete) {
8506 // The incomplete type is being used to break out of recursion.
8507 E.State = IncompleteUsed;
8508 ++IncompleteUsedCount;
8509 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008510 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008511}
8512
8513/// The XCore ABI includes a type information section that communicates symbol
8514/// type information to the linker. The linker uses this information to verify
8515/// safety/correctness of things such as array bound and pointers et al.
8516/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8517/// This type information (TypeString) is emitted into meta data for all global
8518/// symbols: definitions, declarations, functions & variables.
8519///
8520/// The TypeString carries type, qualifier, name, size & value details.
8521/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008522/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008523/// The output is tested by test/CodeGen/xcore-stringtype.c.
8524///
8525static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8526 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8527
8528/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8529void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8530 CodeGen::CodeGenModule &CGM) const {
8531 SmallStringEnc Enc;
8532 if (getTypeString(Enc, D, CGM, TSC)) {
8533 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008534 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8535 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008536 llvm::NamedMDNode *MD =
8537 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8538 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8539 }
8540}
8541
Xiuli Pan972bea82016-03-24 03:57:17 +00008542//===----------------------------------------------------------------------===//
8543// SPIR ABI Implementation
8544//===----------------------------------------------------------------------===//
8545
8546namespace {
8547class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8548public:
8549 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8550 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008551 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008552};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008553
Xiuli Pan972bea82016-03-24 03:57:17 +00008554} // End anonymous namespace.
8555
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008556namespace clang {
8557namespace CodeGen {
8558void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8559 DefaultABIInfo SPIRABI(CGM.getTypes());
8560 SPIRABI.computeInfo(FI);
8561}
8562}
8563}
8564
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008565unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8566 return llvm::CallingConv::SPIR_KERNEL;
8567}
8568
Robert Lytton844aeeb2014-05-02 09:33:20 +00008569static bool appendType(SmallStringEnc &Enc, QualType QType,
8570 const CodeGen::CodeGenModule &CGM,
8571 TypeStringCache &TSC);
8572
8573/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008574/// Builds a SmallVector containing the encoded field types in declaration
8575/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008576static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8577 const RecordDecl *RD,
8578 const CodeGen::CodeGenModule &CGM,
8579 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008580 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008581 SmallStringEnc Enc;
8582 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008583 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008584 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008585 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008586 Enc += "b(";
8587 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008588 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008589 Enc += ':';
8590 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008591 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008592 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008593 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008594 Enc += ')';
8595 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008596 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008597 }
8598 return true;
8599}
8600
8601/// Appends structure and union types to Enc and adds encoding to cache.
8602/// Recursively calls appendType (via extractFieldType) for each field.
8603/// Union types have their fields ordered according to the ABI.
8604static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8605 const CodeGen::CodeGenModule &CGM,
8606 TypeStringCache &TSC, const IdentifierInfo *ID) {
8607 // Append the cached TypeString if we have one.
8608 StringRef TypeString = TSC.lookupStr(ID);
8609 if (!TypeString.empty()) {
8610 Enc += TypeString;
8611 return true;
8612 }
8613
8614 // Start to emit an incomplete TypeString.
8615 size_t Start = Enc.size();
8616 Enc += (RT->isUnionType()? 'u' : 's');
8617 Enc += '(';
8618 if (ID)
8619 Enc += ID->getName();
8620 Enc += "){";
8621
8622 // We collect all encoded fields and order as necessary.
8623 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008624 const RecordDecl *RD = RT->getDecl()->getDefinition();
8625 if (RD && !RD->field_empty()) {
8626 // An incomplete TypeString stub is placed in the cache for this RecordType
8627 // so that recursive calls to this RecordType will use it whilst building a
8628 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008629 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008630 std::string StubEnc(Enc.substr(Start).str());
8631 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8632 TSC.addIncomplete(ID, std::move(StubEnc));
8633 if (!extractFieldType(FE, RD, CGM, TSC)) {
8634 (void) TSC.removeIncomplete(ID);
8635 return false;
8636 }
8637 IsRecursive = TSC.removeIncomplete(ID);
8638 // The ABI requires unions to be sorted but not structures.
8639 // See FieldEncoding::operator< for sort algorithm.
8640 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00008641 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008642 // We can now complete the TypeString.
8643 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008644 for (unsigned I = 0; I != E; ++I) {
8645 if (I)
8646 Enc += ',';
8647 Enc += FE[I].str();
8648 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008649 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008650 Enc += '}';
8651 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8652 return true;
8653}
8654
8655/// Appends enum types to Enc and adds the encoding to the cache.
8656static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8657 TypeStringCache &TSC,
8658 const IdentifierInfo *ID) {
8659 // Append the cached TypeString if we have one.
8660 StringRef TypeString = TSC.lookupStr(ID);
8661 if (!TypeString.empty()) {
8662 Enc += TypeString;
8663 return true;
8664 }
8665
8666 size_t Start = Enc.size();
8667 Enc += "e(";
8668 if (ID)
8669 Enc += ID->getName();
8670 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008671
8672 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008673 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008674 SmallVector<FieldEncoding, 16> FE;
8675 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8676 ++I) {
8677 SmallStringEnc EnumEnc;
8678 EnumEnc += "m(";
8679 EnumEnc += I->getName();
8680 EnumEnc += "){";
8681 I->getInitVal().toString(EnumEnc);
8682 EnumEnc += '}';
8683 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8684 }
Fangrui Song55fab262018-09-26 22:16:28 +00008685 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008686 unsigned E = FE.size();
8687 for (unsigned I = 0; I != E; ++I) {
8688 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008689 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008690 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008691 }
8692 }
8693 Enc += '}';
8694 TSC.addIfComplete(ID, Enc.substr(Start), false);
8695 return true;
8696}
8697
8698/// Appends type's qualifier to Enc.
8699/// This is done prior to appending the type's encoding.
8700static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8701 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008702 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008703 int Lookup = 0;
8704 if (QT.isConstQualified())
8705 Lookup += 1<<0;
8706 if (QT.isRestrictQualified())
8707 Lookup += 1<<1;
8708 if (QT.isVolatileQualified())
8709 Lookup += 1<<2;
8710 Enc += Table[Lookup];
8711}
8712
8713/// Appends built-in types to Enc.
8714static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8715 const char *EncType;
8716 switch (BT->getKind()) {
8717 case BuiltinType::Void:
8718 EncType = "0";
8719 break;
8720 case BuiltinType::Bool:
8721 EncType = "b";
8722 break;
8723 case BuiltinType::Char_U:
8724 EncType = "uc";
8725 break;
8726 case BuiltinType::UChar:
8727 EncType = "uc";
8728 break;
8729 case BuiltinType::SChar:
8730 EncType = "sc";
8731 break;
8732 case BuiltinType::UShort:
8733 EncType = "us";
8734 break;
8735 case BuiltinType::Short:
8736 EncType = "ss";
8737 break;
8738 case BuiltinType::UInt:
8739 EncType = "ui";
8740 break;
8741 case BuiltinType::Int:
8742 EncType = "si";
8743 break;
8744 case BuiltinType::ULong:
8745 EncType = "ul";
8746 break;
8747 case BuiltinType::Long:
8748 EncType = "sl";
8749 break;
8750 case BuiltinType::ULongLong:
8751 EncType = "ull";
8752 break;
8753 case BuiltinType::LongLong:
8754 EncType = "sll";
8755 break;
8756 case BuiltinType::Float:
8757 EncType = "ft";
8758 break;
8759 case BuiltinType::Double:
8760 EncType = "d";
8761 break;
8762 case BuiltinType::LongDouble:
8763 EncType = "ld";
8764 break;
8765 default:
8766 return false;
8767 }
8768 Enc += EncType;
8769 return true;
8770}
8771
8772/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8773static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8774 const CodeGen::CodeGenModule &CGM,
8775 TypeStringCache &TSC) {
8776 Enc += "p(";
8777 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8778 return false;
8779 Enc += ')';
8780 return true;
8781}
8782
8783/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008784static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8785 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008786 const CodeGen::CodeGenModule &CGM,
8787 TypeStringCache &TSC, StringRef NoSizeEnc) {
8788 if (AT->getSizeModifier() != ArrayType::Normal)
8789 return false;
8790 Enc += "a(";
8791 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8792 CAT->getSize().toStringUnsigned(Enc);
8793 else
8794 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8795 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008796 // The Qualifiers should be attached to the type rather than the array.
8797 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008798 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8799 return false;
8800 Enc += ')';
8801 return true;
8802}
8803
8804/// Appends a function encoding to Enc, calling appendType for the return type
8805/// and the arguments.
8806static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8807 const CodeGen::CodeGenModule &CGM,
8808 TypeStringCache &TSC) {
8809 Enc += "f{";
8810 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8811 return false;
8812 Enc += "}(";
8813 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8814 // N.B. we are only interested in the adjusted param types.
8815 auto I = FPT->param_type_begin();
8816 auto E = FPT->param_type_end();
8817 if (I != E) {
8818 do {
8819 if (!appendType(Enc, *I, CGM, TSC))
8820 return false;
8821 ++I;
8822 if (I != E)
8823 Enc += ',';
8824 } while (I != E);
8825 if (FPT->isVariadic())
8826 Enc += ",va";
8827 } else {
8828 if (FPT->isVariadic())
8829 Enc += "va";
8830 else
8831 Enc += '0';
8832 }
8833 }
8834 Enc += ')';
8835 return true;
8836}
8837
8838/// Handles the type's qualifier before dispatching a call to handle specific
8839/// type encodings.
8840static bool appendType(SmallStringEnc &Enc, QualType QType,
8841 const CodeGen::CodeGenModule &CGM,
8842 TypeStringCache &TSC) {
8843
8844 QualType QT = QType.getCanonicalType();
8845
Robert Lytton6adb20f2014-06-05 09:06:21 +00008846 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8847 // The Qualifiers should be attached to the type rather than the array.
8848 // Thus we don't call appendQualifier() here.
8849 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8850
Robert Lytton844aeeb2014-05-02 09:33:20 +00008851 appendQualifier(Enc, QT);
8852
8853 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8854 return appendBuiltinType(Enc, BT);
8855
Robert Lytton844aeeb2014-05-02 09:33:20 +00008856 if (const PointerType *PT = QT->getAs<PointerType>())
8857 return appendPointerType(Enc, PT, CGM, TSC);
8858
8859 if (const EnumType *ET = QT->getAs<EnumType>())
8860 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8861
8862 if (const RecordType *RT = QT->getAsStructureType())
8863 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8864
8865 if (const RecordType *RT = QT->getAsUnionType())
8866 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8867
8868 if (const FunctionType *FT = QT->getAs<FunctionType>())
8869 return appendFunctionType(Enc, FT, CGM, TSC);
8870
8871 return false;
8872}
8873
8874static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8875 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8876 if (!D)
8877 return false;
8878
8879 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8880 if (FD->getLanguageLinkage() != CLanguageLinkage)
8881 return false;
8882 return appendType(Enc, FD->getType(), CGM, TSC);
8883 }
8884
8885 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8886 if (VD->getLanguageLinkage() != CLanguageLinkage)
8887 return false;
8888 QualType QT = VD->getType().getCanonicalType();
8889 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8890 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008891 // The Qualifiers should be attached to the type rather than the array.
8892 // Thus we don't call appendQualifier() here.
8893 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008894 }
8895 return appendType(Enc, QT, CGM, TSC);
8896 }
8897 return false;
8898}
8899
Alex Bradbury8cbdd482018-01-15 17:54:52 +00008900//===----------------------------------------------------------------------===//
8901// RISCV ABI Implementation
8902//===----------------------------------------------------------------------===//
8903
8904namespace {
8905class RISCVABIInfo : public DefaultABIInfo {
8906private:
8907 unsigned XLen; // Size of the integer ('x') registers in bits.
8908 static const int NumArgGPRs = 8;
8909
8910public:
8911 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8912 : DefaultABIInfo(CGT), XLen(XLen) {}
8913
8914 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
8915 // non-virtual, but computeInfo is virtual, so we overload it.
8916 void computeInfo(CGFunctionInfo &FI) const override;
8917
8918 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
8919 int &ArgGPRsLeft) const;
8920 ABIArgInfo classifyReturnType(QualType RetTy) const;
8921
8922 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8923 QualType Ty) const override;
8924
8925 ABIArgInfo extendType(QualType Ty) const;
8926};
8927} // end anonymous namespace
8928
8929void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
8930 QualType RetTy = FI.getReturnType();
8931 if (!getCXXABI().classifyReturnType(FI))
8932 FI.getReturnInfo() = classifyReturnType(RetTy);
8933
8934 // IsRetIndirect is true if classifyArgumentType indicated the value should
8935 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
8936 // is passed direct in LLVM IR, relying on the backend lowering code to
8937 // rewrite the argument list and pass indirectly on RV32.
8938 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
8939 getContext().getTypeSize(RetTy) > (2 * XLen);
8940
8941 // We must track the number of GPRs used in order to conform to the RISC-V
8942 // ABI, as integer scalars passed in registers should have signext/zeroext
8943 // when promoted, but are anyext if passed on the stack. As GPR usage is
8944 // different for variadic arguments, we must also track whether we are
8945 // examining a vararg or not.
8946 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
8947 int NumFixedArgs = FI.getNumRequiredArgs();
8948
8949 int ArgNum = 0;
8950 for (auto &ArgInfo : FI.arguments()) {
8951 bool IsFixed = ArgNum < NumFixedArgs;
8952 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
8953 ArgNum++;
8954 }
8955}
8956
8957ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
8958 int &ArgGPRsLeft) const {
8959 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
8960 Ty = useFirstFieldIfTransparentUnion(Ty);
8961
8962 // Structures with either a non-trivial destructor or a non-trivial
8963 // copy constructor are always passed indirectly.
8964 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8965 if (ArgGPRsLeft)
8966 ArgGPRsLeft -= 1;
8967 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
8968 CGCXXABI::RAA_DirectInMemory);
8969 }
8970
8971 // Ignore empty structs/unions.
8972 if (isEmptyRecord(getContext(), Ty, true))
8973 return ABIArgInfo::getIgnore();
8974
8975 uint64_t Size = getContext().getTypeSize(Ty);
8976 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
8977 bool MustUseStack = false;
8978 // Determine the number of GPRs needed to pass the current argument
8979 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
8980 // register pairs, so may consume 3 registers.
8981 int NeededArgGPRs = 1;
8982 if (!IsFixed && NeededAlign == 2 * XLen)
8983 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
8984 else if (Size > XLen && Size <= 2 * XLen)
8985 NeededArgGPRs = 2;
8986
8987 if (NeededArgGPRs > ArgGPRsLeft) {
8988 MustUseStack = true;
8989 NeededArgGPRs = ArgGPRsLeft;
8990 }
8991
8992 ArgGPRsLeft -= NeededArgGPRs;
8993
8994 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
8995 // Treat an enum type as its underlying type.
8996 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8997 Ty = EnumTy->getDecl()->getIntegerType();
8998
8999 // All integral types are promoted to XLen width, unless passed on the
9000 // stack.
9001 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9002 return extendType(Ty);
9003 }
9004
9005 return ABIArgInfo::getDirect();
9006 }
9007
9008 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9009 // so coerce to integers.
9010 if (Size <= 2 * XLen) {
9011 unsigned Alignment = getContext().getTypeAlign(Ty);
9012
9013 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9014 // required, and a 2-element XLen array if only XLen alignment is required.
9015 if (Size <= XLen) {
9016 return ABIArgInfo::getDirect(
9017 llvm::IntegerType::get(getVMContext(), XLen));
9018 } else if (Alignment == 2 * XLen) {
9019 return ABIArgInfo::getDirect(
9020 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9021 } else {
9022 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9023 llvm::IntegerType::get(getVMContext(), XLen), 2));
9024 }
9025 }
9026 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9027}
9028
9029ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9030 if (RetTy->isVoidType())
9031 return ABIArgInfo::getIgnore();
9032
9033 int ArgGPRsLeft = 2;
9034
9035 // The rules for return and argument types are the same, so defer to
9036 // classifyArgumentType.
9037 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
9038}
9039
9040Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9041 QualType Ty) const {
9042 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9043
9044 // Empty records are ignored for parameter passing purposes.
9045 if (isEmptyRecord(getContext(), Ty, true)) {
9046 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9047 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9048 return Addr;
9049 }
9050
9051 std::pair<CharUnits, CharUnits> SizeAndAlign =
9052 getContext().getTypeInfoInChars(Ty);
9053
9054 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9055 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9056
9057 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9058 SlotSize, /*AllowHigherAlign=*/true);
9059}
9060
9061ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9062 int TySize = getContext().getTypeSize(Ty);
9063 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9064 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9065 return ABIArgInfo::getSignExtend(Ty);
9066 return ABIArgInfo::getExtend(Ty);
9067}
9068
9069namespace {
9070class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9071public:
9072 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9073 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009074
9075 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9076 CodeGen::CodeGenModule &CGM) const override {
9077 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9078 if (!FD) return;
9079
9080 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9081 if (!Attr)
9082 return;
9083
9084 const char *Kind;
9085 switch (Attr->getInterrupt()) {
9086 case RISCVInterruptAttr::user: Kind = "user"; break;
9087 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9088 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9089 }
9090
9091 auto *Fn = cast<llvm::Function>(GV);
9092
9093 Fn->addFnAttr("interrupt", Kind);
9094 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009095};
9096} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009097
Robert Lytton0e076492013-08-13 09:43:10 +00009098//===----------------------------------------------------------------------===//
9099// Driver code
9100//===----------------------------------------------------------------------===//
9101
Rafael Espindola9f834732014-09-19 01:54:22 +00009102bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009103 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009104}
9105
Chris Lattner2b037972010-07-29 02:01:43 +00009106const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009107 if (TheTargetCodeGenInfo)
9108 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009109
Reid Kleckner9305fd12016-04-13 23:37:17 +00009110 // Helper to set the unique_ptr while still keeping the return value.
9111 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9112 this->TheTargetCodeGenInfo.reset(P);
9113 return *P;
9114 };
9115
John McCallc8e01702013-04-16 22:48:15 +00009116 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009117 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009118 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009119 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009120
Derek Schuff09338a22012-09-06 17:37:28 +00009121 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009122 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009123 case llvm::Triple::mips:
9124 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009125 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009126 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9127 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009128
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009129 case llvm::Triple::mips64:
9130 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009131 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009132
Dylan McKaye8232d72017-02-08 05:09:26 +00009133 case llvm::Triple::avr:
9134 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9135
Tim Northover25e8a672014-05-24 12:51:25 +00009136 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00009137 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009138 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009139 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009140 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009141 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009142 return SetCGInfo(
9143 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009144
Reid Kleckner9305fd12016-04-13 23:37:17 +00009145 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009146 }
9147
Dan Gohmanc2853072015-09-03 22:51:53 +00009148 case llvm::Triple::wasm32:
9149 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009150 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009151
Daniel Dunbard59655c2009-09-12 00:59:49 +00009152 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009153 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009154 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009155 case llvm::Triple::thumbeb: {
9156 if (Triple.getOS() == llvm::Triple::Win32) {
9157 return SetCGInfo(
9158 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009159 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009160
Reid Kleckner9305fd12016-04-13 23:37:17 +00009161 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9162 StringRef ABIStr = getTarget().getABI();
9163 if (ABIStr == "apcs-gnu")
9164 Kind = ARMABIInfo::APCS;
9165 else if (ABIStr == "aapcs16")
9166 Kind = ARMABIInfo::AAPCS16_VFP;
9167 else if (CodeGenOpts.FloatABI == "hard" ||
9168 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009169 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009170 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009171 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009172 Kind = ARMABIInfo::AAPCS_VFP;
9173
9174 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9175 }
9176
John McCallea8d8bb2010-03-11 00:10:12 +00009177 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009178 return SetCGInfo(
9179 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009180 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009181 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009182 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009183 if (getTarget().getABI() == "elfv2")
9184 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009185 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009186 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009187
Hal Finkel415c2a32016-10-02 02:10:45 +00009188 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9189 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009190 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009191 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009192 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009193 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009194 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009195 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009196 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009197 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009198 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009199
Hal Finkel415c2a32016-10-02 02:10:45 +00009200 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9201 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009202 }
John McCallea8d8bb2010-03-11 00:10:12 +00009203
Peter Collingbournec947aae2012-05-20 23:28:41 +00009204 case llvm::Triple::nvptx:
9205 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009206 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009207
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009208 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009209 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009210
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009211 case llvm::Triple::riscv32:
9212 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9213 case llvm::Triple::riscv64:
9214 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9215
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009216 case llvm::Triple::systemz: {
9217 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009218 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009219 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009220
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009221 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009222 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009223 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009224
Eli Friedman33465822011-07-08 23:31:17 +00009225 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009226 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009227 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009228 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009229 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009230
John McCall1fe2a8c2013-06-18 02:46:29 +00009231 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009232 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9233 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9234 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009235 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009236 return SetCGInfo(new X86_32TargetCodeGenInfo(
9237 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9238 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9239 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009240 }
Eli Friedman33465822011-07-08 23:31:17 +00009241 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009242
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009243 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009244 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009245 X86AVXABILevel AVXLevel =
9246 (ABI == "avx512"
9247 ? X86AVXABILevel::AVX512
9248 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009249
Chris Lattner04dc9572010-08-31 16:44:54 +00009250 switch (Triple.getOS()) {
9251 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009252 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00009253 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009254 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009255 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009256 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009257 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009258 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009259 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009260 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009261 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009262 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009263 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009264 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009265 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009266 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009267 case llvm::Triple::sparc:
9268 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009269 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009270 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009271 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009272 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009273 case llvm::Triple::spir:
9274 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009275 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009276 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009277}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009278
9279/// Create an OpenCL kernel for an enqueued block.
9280///
9281/// The kernel has the same function type as the block invoke function. Its
9282/// name is the name of the block invoke function postfixed with "_kernel".
9283/// It simply calls the block invoke function then returns.
9284llvm::Function *
9285TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9286 llvm::Function *Invoke,
9287 llvm::Value *BlockLiteral) const {
9288 auto *InvokeFT = Invoke->getFunctionType();
9289 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9290 for (auto &P : InvokeFT->params())
9291 ArgTys.push_back(P);
9292 auto &C = CGF.getLLVMContext();
9293 std::string Name = Invoke->getName().str() + "_kernel";
9294 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9295 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9296 &CGF.CGM.getModule());
9297 auto IP = CGF.Builder.saveIP();
9298 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9299 auto &Builder = CGF.Builder;
9300 Builder.SetInsertPoint(BB);
9301 llvm::SmallVector<llvm::Value *, 2> Args;
9302 for (auto &A : F->args())
9303 Args.push_back(&A);
9304 Builder.CreateCall(Invoke, Args);
9305 Builder.CreateRetVoid();
9306 Builder.restoreIP(IP);
9307 return F;
9308}
9309
9310/// Create an OpenCL kernel for an enqueued block.
9311///
9312/// The type of the first argument (the block literal) is the struct type
9313/// of the block literal instead of a pointer type. The first argument
9314/// (block literal) is passed directly by value to the kernel. The kernel
9315/// allocates the same type of struct on stack and stores the block literal
9316/// to it and passes its pointer to the block invoke function. The kernel
9317/// has "enqueued-block" function attribute and kernel argument metadata.
9318llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9319 CodeGenFunction &CGF, llvm::Function *Invoke,
9320 llvm::Value *BlockLiteral) const {
9321 auto &Builder = CGF.Builder;
9322 auto &C = CGF.getLLVMContext();
9323
9324 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9325 auto *InvokeFT = Invoke->getFunctionType();
9326 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9327 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9328 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9329 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9330 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9331 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9332 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9333
9334 ArgTys.push_back(BlockTy);
9335 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9336 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9337 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9338 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9339 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9340 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9341 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9342 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009343 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9344 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9345 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9346 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9347 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9348 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009349 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009350 }
9351 std::string Name = Invoke->getName().str() + "_kernel";
9352 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9353 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9354 &CGF.CGM.getModule());
9355 F->addFnAttr("enqueued-block");
9356 auto IP = CGF.Builder.saveIP();
9357 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9358 Builder.SetInsertPoint(BB);
9359 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9360 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9361 BlockPtr->setAlignment(BlockAlign);
9362 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9363 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9364 llvm::SmallVector<llvm::Value *, 2> Args;
9365 Args.push_back(Cast);
9366 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9367 Args.push_back(I);
9368 Builder.CreateCall(Invoke, Args);
9369 Builder.CreateRetVoid();
9370 Builder.restoreIP(IP);
9371
9372 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9373 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9374 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9375 F->setMetadata("kernel_arg_base_type",
9376 llvm::MDNode::get(C, ArgBaseTypeNames));
9377 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9378 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9379 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9380
9381 return F;
9382}