blob: 934e155ccdf549d74074ef2282a17fde729e46ad [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"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000022#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000023#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000025#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000026#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000029#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000031
Anton Korobeynikov244360d2009-06-05 22:08:42 +000032using namespace clang;
33using namespace CodeGen;
34
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000035// Helper for coercing an aggregate argument or return value into an integer
36// array of the same size (including padding) and alignment. This alternate
37// coercion happens only for the RenderScript ABI and can be removed after
38// runtimes that rely on it are no longer supported.
39//
40// RenderScript assumes that the size of the argument / return value in the IR
41// is the same as the size of the corresponding qualified type. This helper
42// coerces the aggregate type into an array of the same size (including
43// padding). This coercion is used in lieu of expansion of struct members or
44// other canonical coercions that return a coerced-type of larger size.
45//
46// Ty - The argument / return value type
47// Context - The associated ASTContext
48// LLVMContext - The associated LLVMContext
49static ABIArgInfo coerceToIntArray(QualType Ty,
50 ASTContext &Context,
51 llvm::LLVMContext &LLVMContext) {
52 // Alignment and Size are measured in bits.
53 const uint64_t Size = Context.getTypeSize(Ty);
54 const uint64_t Alignment = Context.getTypeAlign(Ty);
55 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
56 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
57 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
58}
59
John McCall943fae92010-05-27 06:19:26 +000060static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
61 llvm::Value *Array,
62 llvm::Value *Value,
63 unsigned FirstIndex,
64 unsigned LastIndex) {
65 // Alternatively, we could emit this as a loop in the source.
66 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000067 llvm::Value *Cell =
68 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000069 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000070 }
71}
72
John McCalla1dee5302010-08-22 10:59:02 +000073static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000074 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000075 T->isMemberFunctionPointerType();
76}
77
John McCall7f416cc2015-09-08 08:05:57 +000078ABIArgInfo
79ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
80 llvm::Type *Padding) const {
81 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
82 ByRef, Realign, Padding);
83}
84
85ABIArgInfo
86ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
87 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
88 /*ByRef*/ false, Realign);
89}
90
Charles Davisc7d5c942015-09-17 20:55:33 +000091Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
92 QualType Ty) const {
93 return Address::invalid();
94}
95
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000096ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000097
John McCall12f23522016-04-04 18:33:08 +000098/// Does the given lowering require more than the given number of
99/// registers when expanded?
100///
101/// This is intended to be the basis of a reasonable basic implementation
102/// of should{Pass,Return}IndirectlyForSwift.
103///
104/// For most targets, a limit of four total registers is reasonable; this
105/// limits the amount of code required in order to move around the value
106/// in case it wasn't produced immediately prior to the call by the caller
107/// (or wasn't produced in exactly the right registers) or isn't used
108/// immediately within the callee. But some targets may need to further
109/// limit the register count due to an inability to support that many
110/// return registers.
111static bool occupiesMoreThan(CodeGenTypes &cgt,
112 ArrayRef<llvm::Type*> scalarTypes,
113 unsigned maxAllRegisters) {
114 unsigned intCount = 0, fpCount = 0;
115 for (llvm::Type *type : scalarTypes) {
116 if (type->isPointerTy()) {
117 intCount++;
118 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
119 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
120 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
121 } else {
122 assert(type->isVectorTy() || type->isFloatingPointTy());
123 fpCount++;
124 }
125 }
126
127 return (intCount + fpCount > maxAllRegisters);
128}
129
130bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
131 llvm::Type *eltTy,
132 unsigned numElts) const {
133 // The default implementation of this assumes that the target guarantees
134 // 128-bit SIMD support but nothing more.
135 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
136}
137
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000138static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000139 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000140 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
141 if (!RD)
142 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000143 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000144}
145
146static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000147 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000148 const RecordType *RT = T->getAs<RecordType>();
149 if (!RT)
150 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000151 return getRecordArgABI(RT, CXXABI);
152}
153
Reid Klecknerb1be6832014-11-15 01:41:41 +0000154/// Pass transparent unions as if they were the type of the first element. Sema
155/// should ensure that all elements of the union have the same "machine type".
156static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
157 if (const RecordType *UT = Ty->getAsUnionType()) {
158 const RecordDecl *UD = UT->getDecl();
159 if (UD->hasAttr<TransparentUnionAttr>()) {
160 assert(!UD->field_empty() && "sema created an empty transparent union");
161 return UD->field_begin()->getType();
162 }
163 }
164 return Ty;
165}
166
Mark Lacey3825e832013-10-06 01:33:34 +0000167CGCXXABI &ABIInfo::getCXXABI() const {
168 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000169}
170
Chris Lattner2b037972010-07-29 02:01:43 +0000171ASTContext &ABIInfo::getContext() const {
172 return CGT.getContext();
173}
174
175llvm::LLVMContext &ABIInfo::getVMContext() const {
176 return CGT.getLLVMContext();
177}
178
Micah Villmowdd31ca12012-10-08 16:25:52 +0000179const llvm::DataLayout &ABIInfo::getDataLayout() const {
180 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000181}
182
John McCallc8e01702013-04-16 22:48:15 +0000183const TargetInfo &ABIInfo::getTarget() const {
184 return CGT.getTarget();
185}
Chris Lattner2b037972010-07-29 02:01:43 +0000186
Richard Smithf667ad52017-08-26 01:04:35 +0000187const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
188 return CGT.getCodeGenOpts();
189}
190
191bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000192
Reid Klecknere9f6a712014-10-31 17:10:41 +0000193bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
194 return false;
195}
196
197bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
198 uint64_t Members) const {
199 return false;
200}
201
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000202bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
203 return false;
204}
205
Yaron Kerencdae9412016-01-29 19:38:18 +0000206LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000207 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000208 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000209 switch (TheKind) {
210 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000211 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000212 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000213 Ty->print(OS);
214 else
215 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000216 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000217 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000218 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000219 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000220 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000221 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000222 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000223 case InAlloca:
224 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
225 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000226 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000227 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000228 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000229 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000230 break;
231 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000232 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 break;
John McCallf26e73d2016-03-11 04:30:43 +0000234 case CoerceAndExpand:
235 OS << "CoerceAndExpand Type=";
236 getCoerceAndExpandType()->print(OS);
237 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000238 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000239 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000240}
241
Petar Jovanovic402257b2015-12-04 00:26:47 +0000242// Dynamically round a pointer up to a multiple of the given alignment.
243static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
244 llvm::Value *Ptr,
245 CharUnits Align) {
246 llvm::Value *PtrAsInt = Ptr;
247 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
248 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
249 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
250 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
251 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
252 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
253 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
254 Ptr->getType(),
255 Ptr->getName() + ".aligned");
256 return PtrAsInt;
257}
258
John McCall7f416cc2015-09-08 08:05:57 +0000259/// Emit va_arg for a platform using the common void* representation,
260/// where arguments are simply emitted in an array of slots on the stack.
261///
262/// This version implements the core direct-value passing rules.
263///
264/// \param SlotSize - The size and alignment of a stack slot.
265/// Each argument will be allocated to a multiple of this number of
266/// slots, and all the slots will be aligned to this value.
267/// \param AllowHigherAlign - The slot alignment is not a cap;
268/// an argument type with an alignment greater than the slot size
269/// will be emitted on a higher-alignment address, potentially
270/// leaving one or more empty slots behind as padding. If this
271/// is false, the returned address might be less-aligned than
272/// DirectAlign.
273static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
274 Address VAListAddr,
275 llvm::Type *DirectTy,
276 CharUnits DirectSize,
277 CharUnits DirectAlign,
278 CharUnits SlotSize,
279 bool AllowHigherAlign) {
280 // Cast the element type to i8* if necessary. Some platforms define
281 // va_list as a struct containing an i8* instead of just an i8*.
282 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
283 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
284
285 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
286
287 // If the CC aligns values higher than the slot size, do so if needed.
288 Address Addr = Address::invalid();
289 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000290 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
291 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000292 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000293 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000294 }
295
296 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000297 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000298 llvm::Value *NextPtr =
299 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
300 "argp.next");
301 CGF.Builder.CreateStore(NextPtr, VAListAddr);
302
303 // If the argument is smaller than a slot, and this is a big-endian
304 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000305 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
306 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000307 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
308 }
309
310 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
311 return Addr;
312}
313
314/// Emit va_arg for a platform using the common void* representation,
315/// where arguments are simply emitted in an array of slots on the stack.
316///
317/// \param IsIndirect - Values of this type are passed indirectly.
318/// \param ValueInfo - The size and alignment of this type, generally
319/// computed with getContext().getTypeInfoInChars(ValueTy).
320/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
321/// Each argument will be allocated to a multiple of this number of
322/// slots, and all the slots will be aligned to this value.
323/// \param AllowHigherAlign - The slot alignment is not a cap;
324/// an argument type with an alignment greater than the slot size
325/// will be emitted on a higher-alignment address, potentially
326/// leaving one or more empty slots behind as padding.
327static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
328 QualType ValueTy, bool IsIndirect,
329 std::pair<CharUnits, CharUnits> ValueInfo,
330 CharUnits SlotSizeAndAlign,
331 bool AllowHigherAlign) {
332 // The size and alignment of the value that was passed directly.
333 CharUnits DirectSize, DirectAlign;
334 if (IsIndirect) {
335 DirectSize = CGF.getPointerSize();
336 DirectAlign = CGF.getPointerAlign();
337 } else {
338 DirectSize = ValueInfo.first;
339 DirectAlign = ValueInfo.second;
340 }
341
342 // Cast the address we've calculated to the right type.
343 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
344 if (IsIndirect)
345 DirectTy = DirectTy->getPointerTo(0);
346
347 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
348 DirectSize, DirectAlign,
349 SlotSizeAndAlign,
350 AllowHigherAlign);
351
352 if (IsIndirect) {
353 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
354 }
355
356 return Addr;
357
358}
359
360static Address emitMergePHI(CodeGenFunction &CGF,
361 Address Addr1, llvm::BasicBlock *Block1,
362 Address Addr2, llvm::BasicBlock *Block2,
363 const llvm::Twine &Name = "") {
364 assert(Addr1.getType() == Addr2.getType());
365 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
366 PHI->addIncoming(Addr1.getPointer(), Block1);
367 PHI->addIncoming(Addr2.getPointer(), Block2);
368 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
369 return Address(PHI, Align);
370}
371
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000372TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
373
John McCall3480ef22011-08-30 01:42:09 +0000374// If someone can figure out a general rule for this, that would be great.
375// It's probably just doomed to be platform-dependent, though.
376unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
377 // Verified for:
378 // x86-64 FreeBSD, Linux, Darwin
379 // x86-32 FreeBSD, Linux, Darwin
380 // PowerPC Linux, Darwin
381 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000382 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000383 return 32;
384}
385
John McCalla729c622012-02-17 03:33:10 +0000386bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
387 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000388 // The following conventions are known to require this to be false:
389 // x86_stdcall
390 // MIPS
391 // For everything else, we just prefer false unless we opt out.
392 return false;
393}
394
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000395void
396TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
397 llvm::SmallString<24> &Opt) const {
398 // This assumes the user is passing a library name like "rt" instead of a
399 // filename like "librt.a/so", and that they don't care whether it's static or
400 // dynamic.
401 Opt = "-l";
402 Opt += Lib;
403}
404
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000405unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000406 // OpenCL kernels are called via an explicit runtime API with arguments
407 // set with clSetKernelArg(), not as normal sub-functions.
408 // Return SPIR_KERNEL by default as the kernel calling convention to
409 // ensure the fingerprint is fixed such way that each OpenCL argument
410 // gets one matching argument in the produced kernel function argument
411 // list to enable feasible implementation of clSetKernelArg() with
412 // aggregates etc. In case we would use the default C calling conv here,
413 // clSetKernelArg() might break depending on the target-specific
414 // conventions; different targets might split structs passed as values
415 // to multiple function arguments etc.
416 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000417}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000418
Yaxun Liu402804b2016-12-15 08:09:08 +0000419llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
420 llvm::PointerType *T, QualType QT) const {
421 return llvm::ConstantPointerNull::get(T);
422}
423
Yaxun Liucbf647c2017-07-08 13:24:52 +0000424unsigned TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
425 const VarDecl *D) const {
426 assert(!CGM.getLangOpts().OpenCL &&
427 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
428 "Address space agnostic languages only");
Yaxun Liu7bce6422017-07-08 19:13:41 +0000429 return D ? D->getType().getAddressSpace()
430 : static_cast<unsigned>(LangAS::Default);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000431}
432
Yaxun Liu402804b2016-12-15 08:09:08 +0000433llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000434 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
435 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000436 // Since target may map different address spaces in AST to the same address
437 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000438 if (auto *C = dyn_cast<llvm::Constant>(Src))
439 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000440 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000441}
442
Yaxun Liucbf647c2017-07-08 13:24:52 +0000443llvm::Constant *
444TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
445 unsigned SrcAddr, unsigned DestAddr,
446 llvm::Type *DestTy) const {
447 // Since target may map different address spaces in AST to the same address
448 // space, an address space conversion may end up as a bitcast.
449 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
450}
451
Yaxun Liu39195062017-08-04 18:16:31 +0000452llvm::SyncScope::ID
453TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
454 return C.getOrInsertSyncScopeID(""); /* default sync scope */
455}
456
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000457static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000458
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000459/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000460/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000461static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
462 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000463 if (FD->isUnnamedBitfield())
464 return true;
465
466 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000467
Eli Friedman0b3f2012011-11-18 03:47:20 +0000468 // Constant arrays of empty records count as empty, strip them off.
469 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000470 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000471 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
472 if (AT->getSize() == 0)
473 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000475 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000476
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000477 const RecordType *RT = FT->getAs<RecordType>();
478 if (!RT)
479 return false;
480
481 // C++ record fields are never empty, at least in the Itanium ABI.
482 //
483 // FIXME: We should use a predicate for whether this behavior is true in the
484 // current ABI.
485 if (isa<CXXRecordDecl>(RT->getDecl()))
486 return false;
487
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000488 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000489}
490
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000491/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000492/// fields. Note that a structure with a flexible array member is not
493/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000494static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000495 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000496 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000497 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000498 const RecordDecl *RD = RT->getDecl();
499 if (RD->hasFlexibleArrayMember())
500 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000501
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000502 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000503 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &I : CXXRD->bases())
505 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000506 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000507
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000508 for (const auto *I : RD->fields())
509 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510 return false;
511 return true;
512}
513
514/// isSingleElementStruct - Determine if a structure is a "single
515/// element struct", i.e. it has exactly one non-empty field or
516/// exactly one field which is itself a single element
517/// struct. Structures with flexible array members are never
518/// considered single element structs.
519///
520/// \return The field declaration for the single non-empty field, if
521/// it exists.
522static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000523 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000524 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000525 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000526
527 const RecordDecl *RD = RT->getDecl();
528 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000529 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000530
Craig Topper8a13c412014-05-21 05:09:00 +0000531 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000532
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000533 // If this is a C++ record, check the bases first.
534 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000535 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000536 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000537 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000538 continue;
539
540 // If we already found an element then this isn't a single-element struct.
541 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000542 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000543
544 // If this is non-empty and not a single element struct, the composite
545 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000546 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000547 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000548 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000549 }
550 }
551
552 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000553 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000554 QualType FT = FD->getType();
555
556 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000557 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000558 continue;
559
560 // If we already found an element then this isn't a single-element
561 // struct.
562 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000563 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000564
565 // Treat single element arrays as the element.
566 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
567 if (AT->getSize().getZExtValue() != 1)
568 break;
569 FT = AT->getElementType();
570 }
571
John McCalla1dee5302010-08-22 10:59:02 +0000572 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000573 Found = FT.getTypePtr();
574 } else {
575 Found = isSingleElementStruct(FT, Context);
576 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000577 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578 }
579 }
580
Eli Friedmanee945342011-11-18 01:25:50 +0000581 // We don't consider a struct a single-element struct if it has
582 // padding beyond the element type.
583 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000584 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000585
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586 return Found;
587}
588
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000590Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
591 const ABIArgInfo &AI) {
592 // This default implementation defers to the llvm backend's va_arg
593 // instruction. It can handle only passing arguments directly
594 // (typically only handled in the backend for primitive types), or
595 // aggregates passed indirectly by pointer (NOTE: if the "byval"
596 // flag has ABI impact in the callee, this implementation cannot
597 // work.)
598
599 // Only a few cases are covered here at the moment -- those needed
600 // by the default abi.
601 llvm::Value *Val;
602
603 if (AI.isIndirect()) {
604 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000605 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000606 assert(
607 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000608 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000609
610 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
611 CharUnits TyAlignForABI = TyInfo.second;
612
613 llvm::Type *BaseTy =
614 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
615 llvm::Value *Addr =
616 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
617 return Address(Addr, TyAlignForABI);
618 } else {
619 assert((AI.isDirect() || AI.isExtend()) &&
620 "Unexpected ArgInfo Kind in generic VAArg emitter!");
621
622 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000623 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000624 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000625 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000626 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000627 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000628 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000629 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000630
631 Address Temp = CGF.CreateMemTemp(Ty, "varet");
632 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
633 CGF.Builder.CreateStore(Val, Temp);
634 return Temp;
635 }
636}
637
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638/// DefaultABIInfo - The default implementation for ABI specific
639/// details. This implementation provides information which results in
640/// self-consistent and sensible LLVM IR generation, but does not
641/// conform to any particular ABI.
642class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000643public:
644 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000645
Chris Lattner458b2aa2010-07-29 02:16:43 +0000646 ABIArgInfo classifyReturnType(QualType RetTy) const;
647 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000648
Craig Topper4f12f102014-03-12 06:41:41 +0000649 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000650 if (!getCXXABI().classifyReturnType(FI))
651 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000652 for (auto &I : FI.arguments())
653 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000654 }
655
John McCall7f416cc2015-09-08 08:05:57 +0000656 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000657 QualType Ty) const override {
658 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
659 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000660};
661
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000662class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
663public:
Chris Lattner2b037972010-07-29 02:01:43 +0000664 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
665 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000666};
667
Chris Lattner458b2aa2010-07-29 02:16:43 +0000668ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000669 Ty = useFirstFieldIfTransparentUnion(Ty);
670
671 if (isAggregateTypeForABI(Ty)) {
672 // Records with non-trivial destructors/copy-constructors should not be
673 // passed by value.
674 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000675 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000676
John McCall7f416cc2015-09-08 08:05:57 +0000677 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000678 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000679
Chris Lattner9723d6c2010-03-11 18:19:55 +0000680 // Treat an enum type as its underlying type.
681 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
682 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000683
Chris Lattner9723d6c2010-03-11 18:19:55 +0000684 return (Ty->isPromotableIntegerType() ?
685 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000686}
687
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000688ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
689 if (RetTy->isVoidType())
690 return ABIArgInfo::getIgnore();
691
692 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000693 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000694
695 // Treat an enum type as its underlying type.
696 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
697 RetTy = EnumTy->getDecl()->getIntegerType();
698
699 return (RetTy->isPromotableIntegerType() ?
700 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
701}
702
Derek Schuff09338a22012-09-06 17:37:28 +0000703//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000704// WebAssembly ABI Implementation
705//
706// This is a very simple ABI that relies a lot on DefaultABIInfo.
707//===----------------------------------------------------------------------===//
708
709class WebAssemblyABIInfo final : public DefaultABIInfo {
710public:
711 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
712 : DefaultABIInfo(CGT) {}
713
714private:
715 ABIArgInfo classifyReturnType(QualType RetTy) const;
716 ABIArgInfo classifyArgumentType(QualType Ty) const;
717
718 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000719 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000720 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000721 void computeInfo(CGFunctionInfo &FI) const override {
722 if (!getCXXABI().classifyReturnType(FI))
723 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
724 for (auto &Arg : FI.arguments())
725 Arg.info = classifyArgumentType(Arg.type);
726 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000727
728 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
729 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000730};
731
732class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
733public:
734 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
735 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
736};
737
738/// \brief Classify argument of given type \p Ty.
739ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
740 Ty = useFirstFieldIfTransparentUnion(Ty);
741
742 if (isAggregateTypeForABI(Ty)) {
743 // Records with non-trivial destructors/copy-constructors should not be
744 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000745 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000746 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000747 // Ignore empty structs/unions.
748 if (isEmptyRecord(getContext(), Ty, true))
749 return ABIArgInfo::getIgnore();
750 // Lower single-element structs to just pass a regular value. TODO: We
751 // could do reasonable-size multiple-element structs too, using getExpand(),
752 // though watch out for things like bitfields.
753 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
754 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000755 }
756
757 // Otherwise just do the default thing.
758 return DefaultABIInfo::classifyArgumentType(Ty);
759}
760
761ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
762 if (isAggregateTypeForABI(RetTy)) {
763 // Records with non-trivial destructors/copy-constructors should not be
764 // returned by value.
765 if (!getRecordArgABI(RetTy, getCXXABI())) {
766 // Ignore empty structs/unions.
767 if (isEmptyRecord(getContext(), RetTy, true))
768 return ABIArgInfo::getIgnore();
769 // Lower single-element structs to just return a regular value. TODO: We
770 // could do reasonable-size multiple-element structs too, using
771 // ABIArgInfo::getDirect().
772 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
773 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
774 }
775 }
776
777 // Otherwise just do the default thing.
778 return DefaultABIInfo::classifyReturnType(RetTy);
779}
780
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000781Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
782 QualType Ty) const {
783 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
784 getContext().getTypeInfoInChars(Ty),
785 CharUnits::fromQuantity(4),
786 /*AllowHigherAlign=*/ true);
787}
788
Dan Gohmanc2853072015-09-03 22:51:53 +0000789//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000790// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000791//
792// This is a simplified version of the x86_32 ABI. Arguments and return values
793// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000794//===----------------------------------------------------------------------===//
795
796class PNaClABIInfo : public ABIInfo {
797 public:
798 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
799
800 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000801 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000802
Craig Topper4f12f102014-03-12 06:41:41 +0000803 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000804 Address EmitVAArg(CodeGenFunction &CGF,
805 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000806};
807
808class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
809 public:
810 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
811 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
812};
813
814void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000815 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000816 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
817
Reid Kleckner40ca9132014-05-13 22:05:45 +0000818 for (auto &I : FI.arguments())
819 I.info = classifyArgumentType(I.type);
820}
Derek Schuff09338a22012-09-06 17:37:28 +0000821
John McCall7f416cc2015-09-08 08:05:57 +0000822Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
823 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000824 // The PNaCL ABI is a bit odd, in that varargs don't use normal
825 // function classification. Structs get passed directly for varargs
826 // functions, through a rewriting transform in
827 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
828 // this target to actually support a va_arg instructions with an
829 // aggregate type, unlike other targets.
830 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000831}
832
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000833/// \brief Classify argument of given type \p Ty.
834ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000835 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000836 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000837 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
838 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000839 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
840 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000841 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000842 } else if (Ty->isFloatingType()) {
843 // Floating-point types don't go inreg.
844 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000845 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000846
847 return (Ty->isPromotableIntegerType() ?
848 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000849}
850
851ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
852 if (RetTy->isVoidType())
853 return ABIArgInfo::getIgnore();
854
Eli Benderskye20dad62013-04-04 22:49:35 +0000855 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000856 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000857 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000858
859 // Treat an enum type as its underlying type.
860 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
861 RetTy = EnumTy->getDecl()->getIntegerType();
862
863 return (RetTy->isPromotableIntegerType() ?
864 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
865}
866
Chad Rosier651c1832013-03-25 21:00:27 +0000867/// IsX86_MMXType - Return true if this is an MMX type.
868bool IsX86_MMXType(llvm::Type *IRType) {
869 // 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 +0000870 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
871 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
872 IRType->getScalarSizeInBits() != 64;
873}
874
Jay Foad7c57be32011-07-11 09:56:20 +0000875static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000877 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000878 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
879 .Cases("y", "&y", "^Ym", true)
880 .Default(false);
881 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000882 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
883 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000884 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000885 }
886
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000887 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000888 }
889
890 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000891 return Ty;
892}
893
Reid Kleckner80944df2014-10-31 22:00:51 +0000894/// Returns true if this type can be passed in SSE registers with the
895/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
896static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
897 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000898 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
899 if (BT->getKind() == BuiltinType::LongDouble) {
900 if (&Context.getTargetInfo().getLongDoubleFormat() ==
901 &llvm::APFloat::x87DoubleExtended())
902 return false;
903 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000904 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000905 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000906 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
907 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
908 // registers specially.
909 unsigned VecSize = Context.getTypeSize(VT);
910 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
911 return true;
912 }
913 return false;
914}
915
916/// Returns true if this aggregate is small enough to be passed in SSE registers
917/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
918static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
919 return NumMembers <= 4;
920}
921
Erich Keane521ed962017-01-05 00:20:51 +0000922/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
923static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
924 auto AI = ABIArgInfo::getDirect(T);
925 AI.setInReg(true);
926 AI.setCanBeFlattened(false);
927 return AI;
928}
929
Chris Lattner0cf24192010-06-28 20:05:43 +0000930//===----------------------------------------------------------------------===//
931// X86-32 ABI Implementation
932//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000933
Reid Kleckner661f35b2014-01-18 01:12:41 +0000934/// \brief Similar to llvm::CCState, but for Clang.
935struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000936 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000937
938 unsigned CC;
939 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000940 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000941};
942
Erich Keane521ed962017-01-05 00:20:51 +0000943enum {
944 // Vectorcall only allows the first 6 parameters to be passed in registers.
945 VectorcallMaxParamNumAsReg = 6
946};
947
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000948/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000949class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000950 enum Class {
951 Integer,
952 Float
953 };
954
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000955 static const unsigned MinABIStackAlignInBytes = 4;
956
David Chisnallde3a0692009-08-17 23:08:21 +0000957 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000958 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000959 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000960 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000961 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000962 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000963
964 static bool isRegisterSize(unsigned Size) {
965 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
966 }
967
Reid Kleckner80944df2014-10-31 22:00:51 +0000968 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
969 // FIXME: Assumes vectorcall is in use.
970 return isX86VectorTypeForVectorCall(getContext(), Ty);
971 }
972
973 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
974 uint64_t NumMembers) const override {
975 // FIXME: Assumes vectorcall is in use.
976 return isX86VectorCallAggregateSmallEnough(NumMembers);
977 }
978
Reid Kleckner40ca9132014-05-13 22:05:45 +0000979 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980
Daniel Dunbar557893d2010-04-21 19:10:51 +0000981 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
982 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000983 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
984
John McCall7f416cc2015-09-08 08:05:57 +0000985 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000986
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000987 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000988 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000989
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000990 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000991 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000992 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000993
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000994 /// \brief Updates the number of available free registers, returns
995 /// true if any registers were allocated.
996 bool updateFreeRegs(QualType Ty, CCState &State) const;
997
998 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
999 bool &NeedsPadding) const;
1000 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001001
Reid Kleckner04046052016-05-02 17:41:07 +00001002 bool canExpandIndirectArgument(QualType Ty) const;
1003
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001004 /// \brief Rewrite the function info so that all memory arguments use
1005 /// inalloca.
1006 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1007
1008 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001009 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001010 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001011 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1012 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001013
Rafael Espindola75419dc2012-07-23 23:30:29 +00001014public:
1015
Craig Topper4f12f102014-03-12 06:41:41 +00001016 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001017 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1018 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001019
Michael Kupersteindc745202015-10-19 07:52:25 +00001020 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1021 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001022 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001023 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001024 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1025 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001026 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001027 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001028 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001029
1030 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1031 ArrayRef<llvm::Type*> scalars,
1032 bool asReturnValue) const override {
1033 // LLVM's x86-32 lowering currently only assigns up to three
1034 // integer registers and three fp registers. Oddly, it'll use up to
1035 // four vector registers for vectors, but those can overlap with the
1036 // scalar registers.
1037 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1038 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001039
1040 bool isSwiftErrorInRegister() const override {
1041 // x86-32 lowering does not support passing swifterror in a register.
1042 return false;
1043 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001044};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001045
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001046class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1047public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001048 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1049 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001050 unsigned NumRegisterParameters, bool SoftFloatABI)
1051 : TargetCodeGenInfo(new X86_32ABIInfo(
1052 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1053 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001054
John McCall1fe2a8c2013-06-18 02:46:29 +00001055 static bool isStructReturnInRegABI(
1056 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1057
Eric Christopher162c91c2015-06-05 22:03:00 +00001058 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001059 CodeGen::CodeGenModule &CGM,
1060 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001061
Craig Topper4f12f102014-03-12 06:41:41 +00001062 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001063 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001064 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001065 return 4;
1066 }
1067
1068 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001069 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001070
Jay Foad7c57be32011-07-11 09:56:20 +00001071 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001073 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001074 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1075 }
1076
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001077 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1078 std::string &Constraints,
1079 std::vector<llvm::Type *> &ResultRegTypes,
1080 std::vector<llvm::Type *> &ResultTruncRegTypes,
1081 std::vector<LValue> &ResultRegDests,
1082 std::string &AsmString,
1083 unsigned NumOutputs) const override;
1084
Craig Topper4f12f102014-03-12 06:41:41 +00001085 llvm::Constant *
1086 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001087 unsigned Sig = (0xeb << 0) | // jmp rel8
1088 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001089 ('v' << 16) |
1090 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001091 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1092 }
John McCall01391782016-02-05 21:37:38 +00001093
1094 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1095 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001096 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001097 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001098};
1099
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001100}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001102/// Rewrite input constraint references after adding some output constraints.
1103/// In the case where there is one output and one input and we add one output,
1104/// we need to replace all operand references greater than or equal to 1:
1105/// mov $0, $1
1106/// mov eax, $1
1107/// The result will be:
1108/// mov $0, $2
1109/// mov eax, $2
1110static void rewriteInputConstraintReferences(unsigned FirstIn,
1111 unsigned NumNewOuts,
1112 std::string &AsmString) {
1113 std::string Buf;
1114 llvm::raw_string_ostream OS(Buf);
1115 size_t Pos = 0;
1116 while (Pos < AsmString.size()) {
1117 size_t DollarStart = AsmString.find('$', Pos);
1118 if (DollarStart == std::string::npos)
1119 DollarStart = AsmString.size();
1120 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1121 if (DollarEnd == std::string::npos)
1122 DollarEnd = AsmString.size();
1123 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1124 Pos = DollarEnd;
1125 size_t NumDollars = DollarEnd - DollarStart;
1126 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1127 // We have an operand reference.
1128 size_t DigitStart = Pos;
1129 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1130 if (DigitEnd == std::string::npos)
1131 DigitEnd = AsmString.size();
1132 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1133 unsigned OperandIndex;
1134 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1135 if (OperandIndex >= FirstIn)
1136 OperandIndex += NumNewOuts;
1137 OS << OperandIndex;
1138 } else {
1139 OS << OperandStr;
1140 }
1141 Pos = DigitEnd;
1142 }
1143 }
1144 AsmString = std::move(OS.str());
1145}
1146
1147/// Add output constraints for EAX:EDX because they are return registers.
1148void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1149 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1150 std::vector<llvm::Type *> &ResultRegTypes,
1151 std::vector<llvm::Type *> &ResultTruncRegTypes,
1152 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1153 unsigned NumOutputs) const {
1154 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1155
1156 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1157 // larger.
1158 if (!Constraints.empty())
1159 Constraints += ',';
1160 if (RetWidth <= 32) {
1161 Constraints += "={eax}";
1162 ResultRegTypes.push_back(CGF.Int32Ty);
1163 } else {
1164 // Use the 'A' constraint for EAX:EDX.
1165 Constraints += "=A";
1166 ResultRegTypes.push_back(CGF.Int64Ty);
1167 }
1168
1169 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1170 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1171 ResultTruncRegTypes.push_back(CoerceTy);
1172
1173 // Coerce the integer by bitcasting the return slot pointer.
1174 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1175 CoerceTy->getPointerTo()));
1176 ResultRegDests.push_back(ReturnSlot);
1177
1178 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1179}
1180
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001182/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001183bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1184 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001185 uint64_t Size = Context.getTypeSize(Ty);
1186
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001187 // For i386, type must be register sized.
1188 // For the MCU ABI, it only needs to be <= 8-byte
1189 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1190 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001191
1192 if (Ty->isVectorType()) {
1193 // 64- and 128- bit vectors inside structures are not returned in
1194 // registers.
1195 if (Size == 64 || Size == 128)
1196 return false;
1197
1198 return true;
1199 }
1200
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001201 // If this is a builtin, pointer, enum, complex type, member pointer, or
1202 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001203 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001204 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001205 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206 return true;
1207
1208 // Arrays are treated like records.
1209 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001210 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001211
1212 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001213 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001214 if (!RT) return false;
1215
Anders Carlsson40446e82010-01-27 03:25:19 +00001216 // FIXME: Traverse bases here too.
1217
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001218 // Structure types are passed in register if all fields would be
1219 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001220 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001222 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223 continue;
1224
1225 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001226 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227 return false;
1228 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001229 return true;
1230}
1231
Reid Kleckner04046052016-05-02 17:41:07 +00001232static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1233 // Treat complex types as the element type.
1234 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1235 Ty = CTy->getElementType();
1236
1237 // Check for a type which we know has a simple scalar argument-passing
1238 // convention without any padding. (We're specifically looking for 32
1239 // and 64-bit integer and integer-equivalents, float, and double.)
1240 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1241 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1242 return false;
1243
1244 uint64_t Size = Context.getTypeSize(Ty);
1245 return Size == 32 || Size == 64;
1246}
1247
Reid Kleckner791bbf62017-01-13 17:18:19 +00001248static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1249 uint64_t &Size) {
1250 for (const auto *FD : RD->fields()) {
1251 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1252 // argument is smaller than 32-bits, expanding the struct will create
1253 // alignment padding.
1254 if (!is32Or64BitBasicType(FD->getType(), Context))
1255 return false;
1256
1257 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1258 // how to expand them yet, and the predicate for telling if a bitfield still
1259 // counts as "basic" is more complicated than what we were doing previously.
1260 if (FD->isBitField())
1261 return false;
1262
1263 Size += Context.getTypeSize(FD->getType());
1264 }
1265 return true;
1266}
1267
1268static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1269 uint64_t &Size) {
1270 // Don't do this if there are any non-empty bases.
1271 for (const CXXBaseSpecifier &Base : RD->bases()) {
1272 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1273 Size))
1274 return false;
1275 }
1276 if (!addFieldSizes(Context, RD, Size))
1277 return false;
1278 return true;
1279}
1280
Reid Kleckner04046052016-05-02 17:41:07 +00001281/// Test whether an argument type which is to be passed indirectly (on the
1282/// stack) would have the equivalent layout if it was expanded into separate
1283/// arguments. If so, we prefer to do the latter to avoid inhibiting
1284/// optimizations.
1285bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1286 // We can only expand structure types.
1287 const RecordType *RT = Ty->getAs<RecordType>();
1288 if (!RT)
1289 return false;
1290 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001291 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001292 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001293 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001294 // On non-Windows, we have to conservatively match our old bitcode
1295 // prototypes in order to be ABI-compatible at the bitcode level.
1296 if (!CXXRD->isCLike())
1297 return false;
1298 } else {
1299 // Don't do this for dynamic classes.
1300 if (CXXRD->isDynamicClass())
1301 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001302 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001303 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001304 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001305 } else {
1306 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001307 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001308 }
1309
1310 // We can do this if there was no alignment padding.
1311 return Size == getContext().getTypeSize(Ty);
1312}
1313
John McCall7f416cc2015-09-08 08:05:57 +00001314ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001315 // If the return value is indirect, then the hidden argument is consuming one
1316 // integer register.
1317 if (State.FreeRegs) {
1318 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001319 if (!IsMCUABI)
1320 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001321 }
John McCall7f416cc2015-09-08 08:05:57 +00001322 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001323}
1324
Eric Christopher7565e0d2015-05-29 23:09:49 +00001325ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1326 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001327 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001328 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001329
Reid Kleckner80944df2014-10-31 22:00:51 +00001330 const Type *Base = nullptr;
1331 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001332 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1333 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001334 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1335 // The LLVM struct type for such an aggregate should lower properly.
1336 return ABIArgInfo::getDirect();
1337 }
1338
Chris Lattner458b2aa2010-07-29 02:16:43 +00001339 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001340 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001341 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001342 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001343
1344 // 128-bit vectors are a special case; they are returned in
1345 // registers and we need to make sure to pick a type the LLVM
1346 // backend will like.
1347 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001348 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001349 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001350
1351 // Always return in register if it fits in a general purpose
1352 // register, or if it is 64 bits and has a single element.
1353 if ((Size == 8 || Size == 16 || Size == 32) ||
1354 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001355 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001356 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001357
John McCall7f416cc2015-09-08 08:05:57 +00001358 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 }
1360
1361 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001362 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001363
John McCalla1dee5302010-08-22 10:59:02 +00001364 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001365 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001366 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001367 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001368 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001369 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001370
David Chisnallde3a0692009-08-17 23:08:21 +00001371 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001372 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001373 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001374
Denis Zobnin380b2242016-02-11 11:26:03 +00001375 // Ignore empty structs/unions.
1376 if (isEmptyRecord(getContext(), RetTy, true))
1377 return ABIArgInfo::getIgnore();
1378
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 // Small structures which are register sized are generally returned
1380 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001381 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001382 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001383
1384 // As a special-case, if the struct is a "single-element" struct, and
1385 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001386 // floating-point register. (MSVC does not apply this special case.)
1387 // We apply a similar transformation for pointer types to improve the
1388 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001389 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001390 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001391 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001392 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1393
1394 // FIXME: We should be able to narrow this integer in cases with dead
1395 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001396 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001397 }
1398
John McCall7f416cc2015-09-08 08:05:57 +00001399 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001401
Chris Lattner458b2aa2010-07-29 02:16:43 +00001402 // Treat an enum type as its underlying type.
1403 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1404 RetTy = EnumTy->getDecl()->getIntegerType();
1405
1406 return (RetTy->isPromotableIntegerType() ?
1407 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001408}
1409
Eli Friedman7919bea2012-06-05 19:40:46 +00001410static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1411 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1412}
1413
Daniel Dunbared23de32010-09-16 20:42:00 +00001414static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1415 const RecordType *RT = Ty->getAs<RecordType>();
1416 if (!RT)
1417 return 0;
1418 const RecordDecl *RD = RT->getDecl();
1419
1420 // If this is a C++ record, check the bases first.
1421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001422 for (const auto &I : CXXRD->bases())
1423 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001424 return false;
1425
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001426 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001427 QualType FT = i->getType();
1428
Eli Friedman7919bea2012-06-05 19:40:46 +00001429 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001430 return true;
1431
1432 if (isRecordWithSSEVectorType(Context, FT))
1433 return true;
1434 }
1435
1436 return false;
1437}
1438
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001439unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1440 unsigned Align) const {
1441 // Otherwise, if the alignment is less than or equal to the minimum ABI
1442 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001443 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001444 return 0; // Use default alignment.
1445
1446 // On non-Darwin, the stack type alignment is always 4.
1447 if (!IsDarwinVectorABI) {
1448 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001449 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001450 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001451
Daniel Dunbared23de32010-09-16 20:42:00 +00001452 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001453 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1454 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001455 return 16;
1456
1457 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001458}
1459
Rafael Espindola703c47f2012-10-19 05:04:37 +00001460ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001461 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001462 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001463 if (State.FreeRegs) {
1464 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001465 if (!IsMCUABI)
1466 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001467 }
John McCall7f416cc2015-09-08 08:05:57 +00001468 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001469 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001470
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001471 // Compute the byval alignment.
1472 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1473 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1474 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001475 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001476
1477 // If the stack alignment is less than the type alignment, realign the
1478 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001479 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001480 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1481 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001482}
1483
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001484X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1485 const Type *T = isSingleElementStruct(Ty, getContext());
1486 if (!T)
1487 T = Ty.getTypePtr();
1488
1489 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1490 BuiltinType::Kind K = BT->getKind();
1491 if (K == BuiltinType::Float || K == BuiltinType::Double)
1492 return Float;
1493 }
1494 return Integer;
1495}
1496
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001498 if (!IsSoftFloatABI) {
1499 Class C = classify(Ty);
1500 if (C == Float)
1501 return false;
1502 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001503
Rafael Espindola077dd592012-10-24 01:58:58 +00001504 unsigned Size = getContext().getTypeSize(Ty);
1505 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001506
1507 if (SizeInRegs == 0)
1508 return false;
1509
Michael Kuperstein68901882015-10-25 08:18:20 +00001510 if (!IsMCUABI) {
1511 if (SizeInRegs > State.FreeRegs) {
1512 State.FreeRegs = 0;
1513 return false;
1514 }
1515 } else {
1516 // The MCU psABI allows passing parameters in-reg even if there are
1517 // earlier parameters that are passed on the stack. Also,
1518 // it does not allow passing >8-byte structs in-register,
1519 // even if there are 3 free registers available.
1520 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1521 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001522 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523
Reid Kleckner661f35b2014-01-18 01:12:41 +00001524 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001525 return true;
1526}
1527
1528bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1529 bool &InReg,
1530 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001531 // On Windows, aggregates other than HFAs are never passed in registers, and
1532 // they do not consume register slots. Homogenous floating-point aggregates
1533 // (HFAs) have already been dealt with at this point.
1534 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1535 return false;
1536
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 NeedsPadding = false;
1538 InReg = !IsMCUABI;
1539
1540 if (!updateFreeRegs(Ty, State))
1541 return false;
1542
1543 if (IsMCUABI)
1544 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001545
Reid Kleckner80944df2014-10-31 22:00:51 +00001546 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001547 State.CC == llvm::CallingConv::X86_VectorCall ||
1548 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001550 NeedsPadding = true;
1551
Rafael Espindola077dd592012-10-24 01:58:58 +00001552 return false;
1553 }
1554
Rafael Espindola703c47f2012-10-19 05:04:37 +00001555 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001556}
1557
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001558bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1559 if (!updateFreeRegs(Ty, State))
1560 return false;
1561
1562 if (IsMCUABI)
1563 return false;
1564
1565 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001566 State.CC == llvm::CallingConv::X86_VectorCall ||
1567 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001568 if (getContext().getTypeSize(Ty) > 32)
1569 return false;
1570
1571 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1572 Ty->isReferenceType());
1573 }
1574
1575 return true;
1576}
1577
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001578ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1579 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001580 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001581
Reid Klecknerb1be6832014-11-15 01:41:41 +00001582 Ty = useFirstFieldIfTransparentUnion(Ty);
1583
Reid Kleckner80944df2014-10-31 22:00:51 +00001584 // Check with the C++ ABI first.
1585 const RecordType *RT = Ty->getAs<RecordType>();
1586 if (RT) {
1587 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1588 if (RAA == CGCXXABI::RAA_Indirect) {
1589 return getIndirectResult(Ty, false, State);
1590 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1591 // The field index doesn't matter, we'll fix it up later.
1592 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1593 }
1594 }
1595
Erich Keane4bd39302017-06-21 16:37:22 +00001596 // Regcall uses the concept of a homogenous vector aggregate, similar
1597 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 const Type *Base = nullptr;
1599 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001600 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001601 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001602
Erich Keane4bd39302017-06-21 16:37:22 +00001603 if (State.FreeSSERegs >= NumElts) {
1604 State.FreeSSERegs -= NumElts;
1605 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001606 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001607 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001608 }
Erich Keane4bd39302017-06-21 16:37:22 +00001609 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001610 }
1611
1612 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001613 // Structures with flexible arrays are always indirect.
1614 // FIXME: This should not be byval!
1615 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1616 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001617
Reid Kleckner04046052016-05-02 17:41:07 +00001618 // Ignore empty structs/unions on non-Windows.
1619 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001620 return ABIArgInfo::getIgnore();
1621
Rafael Espindolafad28de2012-10-24 01:59:00 +00001622 llvm::LLVMContext &LLVMContext = getVMContext();
1623 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001624 bool NeedsPadding = false;
1625 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001626 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001627 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001628 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001629 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001630 if (InReg)
1631 return ABIArgInfo::getDirectInReg(Result);
1632 else
1633 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001634 }
Craig Topper8a13c412014-05-21 05:09:00 +00001635 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001636
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001637 // Expand small (<= 128-bit) record types when we know that the stack layout
1638 // of those arguments will match the struct. This is important because the
1639 // LLVM backend isn't smart enough to remove byval, which inhibits many
1640 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001641 // Don't do this for the MCU if there are still free integer registers
1642 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001643 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1644 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001645 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001646 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001647 State.CC == llvm::CallingConv::X86_VectorCall ||
1648 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001649 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650
Reid Kleckner661f35b2014-01-18 01:12:41 +00001651 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001652 }
1653
Chris Lattnerd774ae92010-08-26 20:05:13 +00001654 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001655 // On Darwin, some vectors are passed in memory, we handle this by passing
1656 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001657 if (IsDarwinVectorABI) {
1658 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001659 if ((Size == 8 || Size == 16 || Size == 32) ||
1660 (Size == 64 && VT->getNumElements() == 1))
1661 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1662 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001663 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001664
Chad Rosier651c1832013-03-25 21:00:27 +00001665 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1666 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001667
Chris Lattnerd774ae92010-08-26 20:05:13 +00001668 return ABIArgInfo::getDirect();
1669 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001670
1671
Chris Lattner458b2aa2010-07-29 02:16:43 +00001672 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1673 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001674
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001675 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001676
1677 if (Ty->isPromotableIntegerType()) {
1678 if (InReg)
1679 return ABIArgInfo::getExtendInReg();
1680 return ABIArgInfo::getExtend();
1681 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001682
Rafael Espindola703c47f2012-10-19 05:04:37 +00001683 if (InReg)
1684 return ABIArgInfo::getDirectInReg();
1685 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686}
1687
Erich Keane521ed962017-01-05 00:20:51 +00001688void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1689 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001690 // Vectorcall x86 works subtly different than in x64, so the format is
1691 // a bit different than the x64 version. First, all vector types (not HVAs)
1692 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1693 // This differs from the x64 implementation, where the first 6 by INDEX get
1694 // registers.
1695 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1696 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1697 // first take up the remaining YMM/XMM registers. If insufficient registers
1698 // remain but an integer register (ECX/EDX) is available, it will be passed
1699 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001700 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001701 // First pass do all the vector types.
1702 const Type *Base = nullptr;
1703 uint64_t NumElts = 0;
1704 const QualType& Ty = I.type;
1705 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1706 isHomogeneousAggregate(Ty, Base, NumElts)) {
1707 if (State.FreeSSERegs >= NumElts) {
1708 State.FreeSSERegs -= NumElts;
1709 I.info = ABIArgInfo::getDirect();
1710 } else {
1711 I.info = classifyArgumentType(Ty, State);
1712 }
1713 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1714 }
Erich Keane521ed962017-01-05 00:20:51 +00001715 }
Erich Keane4bd39302017-06-21 16:37:22 +00001716
Erich Keane521ed962017-01-05 00:20:51 +00001717 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001718 // Second pass, do the rest!
1719 const Type *Base = nullptr;
1720 uint64_t NumElts = 0;
1721 const QualType& Ty = I.type;
1722 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1723
1724 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1725 // Assign true HVAs (non vector/native FP types).
1726 if (State.FreeSSERegs >= NumElts) {
1727 State.FreeSSERegs -= NumElts;
1728 I.info = getDirectX86Hva();
1729 } else {
1730 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1731 }
1732 } else if (!IsHva) {
1733 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1734 I.info = classifyArgumentType(Ty, State);
1735 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1736 }
Erich Keane521ed962017-01-05 00:20:51 +00001737 }
1738}
1739
Rafael Espindolaa6472962012-07-24 00:01:07 +00001740void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001741 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001742 if (IsMCUABI)
1743 State.FreeRegs = 3;
1744 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001745 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001746 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1747 State.FreeRegs = 2;
1748 State.FreeSSERegs = 6;
1749 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001750 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001751 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1752 State.FreeRegs = 5;
1753 State.FreeSSERegs = 8;
1754 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001755 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001756
Reid Kleckner677539d2014-07-10 01:58:55 +00001757 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001758 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001759 } else if (FI.getReturnInfo().isIndirect()) {
1760 // The C++ ABI is not aware of register usage, so we have to check if the
1761 // return value was sret and put it in a register ourselves if appropriate.
1762 if (State.FreeRegs) {
1763 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001764 if (!IsMCUABI)
1765 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001766 }
1767 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001768
Peter Collingbournef7706832014-12-12 23:41:25 +00001769 // The chain argument effectively gives us another free register.
1770 if (FI.isChainCall())
1771 ++State.FreeRegs;
1772
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001774 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1775 computeVectorCallArgs(FI, State, UsedInAlloca);
1776 } else {
1777 // If not vectorcall, revert to normal behavior.
1778 for (auto &I : FI.arguments()) {
1779 I.info = classifyArgumentType(I.type, State);
1780 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1781 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001782 }
1783
1784 // If we needed to use inalloca for any argument, do a second pass and rewrite
1785 // all the memory arguments to use inalloca.
1786 if (UsedInAlloca)
1787 rewriteWithInAlloca(FI);
1788}
1789
1790void
1791X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001792 CharUnits &StackOffset, ABIArgInfo &Info,
1793 QualType Type) const {
1794 // Arguments are always 4-byte-aligned.
1795 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1796
1797 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001798 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1799 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001800 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001801
John McCall7f416cc2015-09-08 08:05:57 +00001802 // Insert padding bytes to respect alignment.
1803 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001804 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001805 if (StackOffset != FieldEnd) {
1806 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001807 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001808 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001809 FrameFields.push_back(Ty);
1810 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001811}
1812
Reid Kleckner852361d2014-07-26 00:12:26 +00001813static bool isArgInAlloca(const ABIArgInfo &Info) {
1814 // Leave ignored and inreg arguments alone.
1815 switch (Info.getKind()) {
1816 case ABIArgInfo::InAlloca:
1817 return true;
1818 case ABIArgInfo::Indirect:
1819 assert(Info.getIndirectByVal());
1820 return true;
1821 case ABIArgInfo::Ignore:
1822 return false;
1823 case ABIArgInfo::Direct:
1824 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001825 if (Info.getInReg())
1826 return false;
1827 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001828 case ABIArgInfo::Expand:
1829 case ABIArgInfo::CoerceAndExpand:
1830 // These are aggregate types which are never passed in registers when
1831 // inalloca is involved.
1832 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001833 }
1834 llvm_unreachable("invalid enum");
1835}
1836
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001837void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1838 assert(IsWin32StructABI && "inalloca only supported on win32");
1839
1840 // Build a packed struct type for all of the arguments in memory.
1841 SmallVector<llvm::Type *, 6> FrameFields;
1842
John McCall7f416cc2015-09-08 08:05:57 +00001843 // The stack alignment is always 4.
1844 CharUnits StackAlign = CharUnits::fromQuantity(4);
1845
1846 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001847 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1848
1849 // Put 'this' into the struct before 'sret', if necessary.
1850 bool IsThisCall =
1851 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1852 ABIArgInfo &Ret = FI.getReturnInfo();
1853 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1854 isArgInAlloca(I->info)) {
1855 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1856 ++I;
1857 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001858
1859 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 if (Ret.isIndirect() && !Ret.getInReg()) {
1861 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1862 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001863 // On Windows, the hidden sret parameter is always returned in eax.
1864 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865 }
1866
1867 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001868 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869 ++I;
1870
1871 // Put arguments passed in memory into the struct.
1872 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001873 if (isArgInAlloca(I->info))
1874 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001875 }
1876
1877 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001878 /*isPacked=*/true),
1879 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001880}
1881
John McCall7f416cc2015-09-08 08:05:57 +00001882Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1883 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884
John McCall7f416cc2015-09-08 08:05:57 +00001885 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 // x86-32 changes the alignment of certain arguments on the stack.
1888 //
1889 // Just messing with TypeInfo like this works because we never pass
1890 // anything indirectly.
1891 TypeInfo.second = CharUnits::fromQuantity(
1892 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1895 TypeInfo, CharUnits::fromQuantity(4),
1896 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897}
1898
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001899bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1900 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1901 assert(Triple.getArch() == llvm::Triple::x86);
1902
1903 switch (Opts.getStructReturnConvention()) {
1904 case CodeGenOptions::SRCK_Default:
1905 break;
1906 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1907 return false;
1908 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1909 return true;
1910 }
1911
Michael Kupersteind749f232015-10-27 07:46:22 +00001912 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001913 return true;
1914
1915 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001916 case llvm::Triple::DragonFly:
1917 case llvm::Triple::FreeBSD:
1918 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001919 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001920 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001921 default:
1922 return false;
1923 }
1924}
1925
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001926void X86_32TargetCodeGenInfo::setTargetAttributes(
1927 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1928 ForDefinition_t IsForDefinition) const {
1929 if (!IsForDefinition)
1930 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001931 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001932 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1933 // Get the LLVM function.
1934 llvm::Function *Fn = cast<llvm::Function>(GV);
1935
1936 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001937 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001938 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001939 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001940 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001941 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1942 llvm::Function *Fn = cast<llvm::Function>(GV);
1943 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1944 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001945 }
1946}
1947
John McCallbeec5a02010-03-06 00:35:14 +00001948bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1949 CodeGen::CodeGenFunction &CGF,
1950 llvm::Value *Address) const {
1951 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001952
Chris Lattnerece04092012-02-07 00:39:47 +00001953 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001954
John McCallbeec5a02010-03-06 00:35:14 +00001955 // 0-7 are the eight integer registers; the order is different
1956 // on Darwin (for EH), but the range is the same.
1957 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001958 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001959
John McCallc8e01702013-04-16 22:48:15 +00001960 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001961 // 12-16 are st(0..4). Not sure why we stop at 4.
1962 // These have size 16, which is sizeof(long double) on
1963 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001965 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001966
John McCallbeec5a02010-03-06 00:35:14 +00001967 } else {
1968 // 9 is %eflags, which doesn't get a size on Darwin for some
1969 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001970 Builder.CreateAlignedStore(
1971 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1972 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001973
1974 // 11-16 are st(0..5). Not sure why we stop at 5.
1975 // These have size 12, which is sizeof(long double) on
1976 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001977 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001978 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1979 }
John McCallbeec5a02010-03-06 00:35:14 +00001980
1981 return false;
1982}
1983
Chris Lattner0cf24192010-06-28 20:05:43 +00001984//===----------------------------------------------------------------------===//
1985// X86-64 ABI Implementation
1986//===----------------------------------------------------------------------===//
1987
1988
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001989namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001990/// The AVX ABI level for X86 targets.
1991enum class X86AVXABILevel {
1992 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001993 AVX,
1994 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001995};
1996
1997/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1998static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1999 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002000 case X86AVXABILevel::AVX512:
2001 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002002 case X86AVXABILevel::AVX:
2003 return 256;
2004 case X86AVXABILevel::None:
2005 return 128;
2006 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002007 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002008}
2009
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002011class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002012 enum Class {
2013 Integer = 0,
2014 SSE,
2015 SSEUp,
2016 X87,
2017 X87Up,
2018 ComplexX87,
2019 NoClass,
2020 Memory
2021 };
2022
2023 /// merge - Implement the X86_64 ABI merging algorithm.
2024 ///
2025 /// Merge an accumulating classification \arg Accum with a field
2026 /// classification \arg Field.
2027 ///
2028 /// \param Accum - The accumulating classification. This should
2029 /// always be either NoClass or the result of a previous merge
2030 /// call. In addition, this should never be Memory (the caller
2031 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002032 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002033
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002034 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2035 ///
2036 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2037 /// final MEMORY or SSE classes when necessary.
2038 ///
2039 /// \param AggregateSize - The size of the current aggregate in
2040 /// the classification process.
2041 ///
2042 /// \param Lo - The classification for the parts of the type
2043 /// residing in the low word of the containing object.
2044 ///
2045 /// \param Hi - The classification for the parts of the type
2046 /// residing in the higher words of the containing object.
2047 ///
2048 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2049
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002050 /// classify - Determine the x86_64 register classes in which the
2051 /// given type T should be passed.
2052 ///
2053 /// \param Lo - The classification for the parts of the type
2054 /// residing in the low word of the containing object.
2055 ///
2056 /// \param Hi - The classification for the parts of the type
2057 /// residing in the high word of the containing object.
2058 ///
2059 /// \param OffsetBase - The bit offset of this type in the
2060 /// containing object. Some parameters are classified different
2061 /// depending on whether they straddle an eightbyte boundary.
2062 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002063 /// \param isNamedArg - Whether the argument in question is a "named"
2064 /// argument, as used in AMD64-ABI 3.5.7.
2065 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002066 /// If a word is unused its result will be NoClass; if a type should
2067 /// be passed in Memory then at least the classification of \arg Lo
2068 /// will be Memory.
2069 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002070 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002071 ///
2072 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2073 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002074 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2075 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002077 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002078 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2079 unsigned IROffset, QualType SourceTy,
2080 unsigned SourceOffset) const;
2081 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2082 unsigned IROffset, QualType SourceTy,
2083 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002084
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002086 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002087 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002088
2089 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002091 ///
2092 /// \param freeIntRegs - The number of free integer registers remaining
2093 /// available.
2094 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002095
Chris Lattner458b2aa2010-07-29 02:16:43 +00002096 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097
Erich Keane757d3172016-11-02 18:29:35 +00002098 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2099 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002100 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101
Erich Keane757d3172016-11-02 18:29:35 +00002102 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2103 unsigned &NeededSSE) const;
2104
2105 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2106 unsigned &NeededSSE) const;
2107
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002108 bool IsIllegalVectorType(QualType Ty) const;
2109
John McCalle0fda732011-04-21 01:20:55 +00002110 /// The 0.98 ABI revision clarified a lot of ambiguities,
2111 /// unfortunately in ways that were not always consistent with
2112 /// certain previous compilers. In particular, platforms which
2113 /// required strict binary compatibility with older versions of GCC
2114 /// may need to exempt themselves.
2115 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002116 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002117 }
2118
Richard Smithf667ad52017-08-26 01:04:35 +00002119 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2120 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002121 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002122 // Clang <= 3.8 did not do this.
2123 if (getCodeGenOpts().getClangABICompat() <=
2124 CodeGenOptions::ClangABI::Ver3_8)
2125 return false;
2126
David Majnemere2ae2282016-03-04 05:26:16 +00002127 const llvm::Triple &Triple = getTarget().getTriple();
2128 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2129 return false;
2130 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2131 return false;
2132 return true;
2133 }
2134
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002135 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002136 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2137 // 64-bit hardware.
2138 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002139
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002140public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002141 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002142 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002143 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002144 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002145
John McCalla729c622012-02-17 03:33:10 +00002146 bool isPassedUsingAVXType(QualType type) const {
2147 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002148 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002149 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2150 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002151 if (info.isDirect()) {
2152 llvm::Type *ty = info.getCoerceToType();
2153 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2154 return (vectorTy->getBitWidth() > 128);
2155 }
2156 return false;
2157 }
2158
Craig Topper4f12f102014-03-12 06:41:41 +00002159 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002160
John McCall7f416cc2015-09-08 08:05:57 +00002161 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2162 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002163 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2164 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002165
2166 bool has64BitPointers() const {
2167 return Has64BitPointers;
2168 }
John McCall12f23522016-04-04 18:33:08 +00002169
2170 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2171 ArrayRef<llvm::Type*> scalars,
2172 bool asReturnValue) const override {
2173 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2174 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002175 bool isSwiftErrorInRegister() const override {
2176 return true;
2177 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002178};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002179
Chris Lattner04dc9572010-08-31 16:44:54 +00002180/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002181class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002182public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002183 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002184 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002185 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002186
Craig Topper4f12f102014-03-12 06:41:41 +00002187 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002188
John McCall7f416cc2015-09-08 08:05:57 +00002189 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2190 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002191
2192 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2193 // FIXME: Assumes vectorcall is in use.
2194 return isX86VectorTypeForVectorCall(getContext(), Ty);
2195 }
2196
2197 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2198 uint64_t NumMembers) const override {
2199 // FIXME: Assumes vectorcall is in use.
2200 return isX86VectorCallAggregateSmallEnough(NumMembers);
2201 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002202
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002203 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2204 ArrayRef<llvm::Type *> scalars,
2205 bool asReturnValue) const override {
2206 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2207 }
2208
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002209 bool isSwiftErrorInRegister() const override {
2210 return true;
2211 }
2212
Reid Kleckner11a17192015-10-28 22:29:52 +00002213private:
Erich Keane521ed962017-01-05 00:20:51 +00002214 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2215 bool IsVectorCall, bool IsRegCall) const;
2216 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2217 const ABIArgInfo &current) const;
2218 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2219 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002220
Erich Keane521ed962017-01-05 00:20:51 +00002221 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002222};
2223
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002224class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2225public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002226 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002227 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002228
John McCalla729c622012-02-17 03:33:10 +00002229 const X86_64ABIInfo &getABIInfo() const {
2230 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2231 }
2232
Craig Topper4f12f102014-03-12 06:41:41 +00002233 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002234 return 7;
2235 }
2236
2237 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002238 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002239 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002240
John McCall943fae92010-05-27 06:19:26 +00002241 // 0-15 are the 16 integer registers.
2242 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002243 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002244 return false;
2245 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002246
Jay Foad7c57be32011-07-11 09:56:20 +00002247 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002248 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002249 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002250 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2251 }
2252
John McCalla729c622012-02-17 03:33:10 +00002253 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002254 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002255 // The default CC on x86-64 sets %al to the number of SSA
2256 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002257 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002258 // that when AVX types are involved: the ABI explicitly states it is
2259 // undefined, and it doesn't work in practice because of how the ABI
2260 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002261 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002262 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002263 for (CallArgList::const_iterator
2264 it = args.begin(), ie = args.end(); it != ie; ++it) {
2265 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2266 HasAVXType = true;
2267 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002268 }
2269 }
John McCalla729c622012-02-17 03:33:10 +00002270
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002271 if (!HasAVXType)
2272 return true;
2273 }
John McCallcbc038a2011-09-21 08:08:30 +00002274
John McCalla729c622012-02-17 03:33:10 +00002275 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002276 }
2277
Craig Topper4f12f102014-03-12 06:41:41 +00002278 llvm::Constant *
2279 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002280 unsigned Sig = (0xeb << 0) | // jmp rel8
2281 (0x06 << 8) | // .+0x08
2282 ('v' << 16) |
2283 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002284 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2285 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002286
2287 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002288 CodeGen::CodeGenModule &CGM,
2289 ForDefinition_t IsForDefinition) const override {
2290 if (!IsForDefinition)
2291 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002292 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002293 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2294 // Get the LLVM function.
2295 auto *Fn = cast<llvm::Function>(GV);
2296
2297 // Now add the 'alignstack' attribute with a value of 16.
2298 llvm::AttrBuilder B;
2299 B.addStackAlignmentAttr(16);
2300 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2301 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002302 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2303 llvm::Function *Fn = cast<llvm::Function>(GV);
2304 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2305 }
2306 }
2307 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002308};
2309
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002310class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2311public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002312 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2313 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002314
2315 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002316 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002317 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002318 // If the argument contains a space, enclose it in quotes.
2319 if (Lib.find(" ") != StringRef::npos)
2320 Opt += "\"" + Lib.str() + "\"";
2321 else
2322 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002323 }
2324};
2325
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002326static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002327 // If the argument does not end in .lib, automatically add the suffix.
2328 // If the argument contains a space, enclose it in quotes.
2329 // This matches the behavior of MSVC.
2330 bool Quote = (Lib.find(" ") != StringRef::npos);
2331 std::string ArgStr = Quote ? "\"" : "";
2332 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002333 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002334 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002335 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002336 return ArgStr;
2337}
2338
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002339class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2340public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002341 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002342 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2343 unsigned NumRegisterParameters)
2344 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002345 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002346
Eric Christopher162c91c2015-06-05 22:03:00 +00002347 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002348 CodeGen::CodeGenModule &CGM,
2349 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002350
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002351 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002352 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002353 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002354 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002355 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002356
2357 void getDetectMismatchOption(llvm::StringRef Name,
2358 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002359 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002360 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002361 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002362};
2363
Hans Wennborg77dc2362015-01-20 19:45:50 +00002364static void addStackProbeSizeTargetAttribute(const Decl *D,
2365 llvm::GlobalValue *GV,
2366 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002367 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002368 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2369 llvm::Function *Fn = cast<llvm::Function>(GV);
2370
Eric Christopher7565e0d2015-05-29 23:09:49 +00002371 Fn->addFnAttr("stack-probe-size",
2372 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002373 }
2374 }
2375}
2376
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002377void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2378 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2379 ForDefinition_t IsForDefinition) const {
2380 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2381 if (!IsForDefinition)
2382 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002383 addStackProbeSizeTargetAttribute(D, GV, CGM);
2384}
2385
Chris Lattner04dc9572010-08-31 16:44:54 +00002386class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2387public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002388 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2389 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002390 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002391
Eric Christopher162c91c2015-06-05 22:03:00 +00002392 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002393 CodeGen::CodeGenModule &CGM,
2394 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002395
Craig Topper4f12f102014-03-12 06:41:41 +00002396 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002397 return 7;
2398 }
2399
2400 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002401 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002402 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002403
Chris Lattner04dc9572010-08-31 16:44:54 +00002404 // 0-15 are the 16 integer registers.
2405 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002406 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002407 return false;
2408 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002409
2410 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002411 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002412 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002413 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002414 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002415
2416 void getDetectMismatchOption(llvm::StringRef Name,
2417 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002418 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002419 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002420 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002421};
2422
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002423void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2424 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2425 ForDefinition_t IsForDefinition) const {
2426 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2427 if (!IsForDefinition)
2428 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002429 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002430 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2431 // Get the LLVM function.
2432 auto *Fn = cast<llvm::Function>(GV);
2433
2434 // Now add the 'alignstack' attribute with a value of 16.
2435 llvm::AttrBuilder B;
2436 B.addStackAlignmentAttr(16);
2437 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2438 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002439 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2440 llvm::Function *Fn = cast<llvm::Function>(GV);
2441 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2442 }
2443 }
2444
Hans Wennborg77dc2362015-01-20 19:45:50 +00002445 addStackProbeSizeTargetAttribute(D, GV, CGM);
2446}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002447}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002449void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2450 Class &Hi) const {
2451 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2452 //
2453 // (a) If one of the classes is Memory, the whole argument is passed in
2454 // memory.
2455 //
2456 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2457 // memory.
2458 //
2459 // (c) If the size of the aggregate exceeds two eightbytes and the first
2460 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2461 // argument is passed in memory. NOTE: This is necessary to keep the
2462 // ABI working for processors that don't support the __m256 type.
2463 //
2464 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2465 //
2466 // Some of these are enforced by the merging logic. Others can arise
2467 // only with unions; for example:
2468 // union { _Complex double; unsigned; }
2469 //
2470 // Note that clauses (b) and (c) were added in 0.98.
2471 //
2472 if (Hi == Memory)
2473 Lo = Memory;
2474 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2475 Lo = Memory;
2476 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2477 Lo = Memory;
2478 if (Hi == SSEUp && Lo != SSE)
2479 Hi = SSE;
2480}
2481
Chris Lattnerd776fb12010-06-28 21:43:59 +00002482X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002483 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2484 // classified recursively so that always two fields are
2485 // considered. The resulting class is calculated according to
2486 // the classes of the fields in the eightbyte:
2487 //
2488 // (a) If both classes are equal, this is the resulting class.
2489 //
2490 // (b) If one of the classes is NO_CLASS, the resulting class is
2491 // the other class.
2492 //
2493 // (c) If one of the classes is MEMORY, the result is the MEMORY
2494 // class.
2495 //
2496 // (d) If one of the classes is INTEGER, the result is the
2497 // INTEGER.
2498 //
2499 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2500 // MEMORY is used as class.
2501 //
2502 // (f) Otherwise class SSE is used.
2503
2504 // Accum should never be memory (we should have returned) or
2505 // ComplexX87 (because this cannot be passed in a structure).
2506 assert((Accum != Memory && Accum != ComplexX87) &&
2507 "Invalid accumulated classification during merge.");
2508 if (Accum == Field || Field == NoClass)
2509 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002510 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002511 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002512 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002514 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002515 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002516 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2517 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002519 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520}
2521
Chris Lattner5c740f12010-06-30 19:14:05 +00002522void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002523 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524 // FIXME: This code can be simplified by introducing a simple value class for
2525 // Class pairs with appropriate constructor methods for the various
2526 // situations.
2527
2528 // FIXME: Some of the split computations are wrong; unaligned vectors
2529 // shouldn't be passed in registers for example, so there is no chance they
2530 // can straddle an eightbyte. Verify & simplify.
2531
2532 Lo = Hi = NoClass;
2533
2534 Class &Current = OffsetBase < 64 ? Lo : Hi;
2535 Current = Memory;
2536
John McCall9dd450b2009-09-21 23:43:11 +00002537 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002538 BuiltinType::Kind k = BT->getKind();
2539
2540 if (k == BuiltinType::Void) {
2541 Current = NoClass;
2542 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2543 Lo = Integer;
2544 Hi = Integer;
2545 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2546 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002547 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 Current = SSE;
2549 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002550 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002551 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002552 Lo = SSE;
2553 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002554 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002555 Lo = X87;
2556 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002557 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002558 Current = SSE;
2559 } else
2560 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002561 }
2562 // FIXME: _Decimal32 and _Decimal64 are SSE.
2563 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002564 return;
2565 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Chris Lattnerd776fb12010-06-28 21:43:59 +00002567 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002568 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002569 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002570 return;
2571 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002572
Chris Lattnerd776fb12010-06-28 21:43:59 +00002573 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002574 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002575 return;
2576 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002577
Chris Lattnerd776fb12010-06-28 21:43:59 +00002578 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002579 if (Ty->isMemberFunctionPointerType()) {
2580 if (Has64BitPointers) {
2581 // If Has64BitPointers, this is an {i64, i64}, so classify both
2582 // Lo and Hi now.
2583 Lo = Hi = Integer;
2584 } else {
2585 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2586 // straddles an eightbyte boundary, Hi should be classified as well.
2587 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2588 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2589 if (EB_FuncPtr != EB_ThisAdj) {
2590 Lo = Hi = Integer;
2591 } else {
2592 Current = Integer;
2593 }
2594 }
2595 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002596 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002597 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002598 return;
2599 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002600
Chris Lattnerd776fb12010-06-28 21:43:59 +00002601 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002602 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002603 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2604 // gcc passes the following as integer:
2605 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2606 // 2 bytes - <2 x char>, <1 x short>
2607 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608 Current = Integer;
2609
2610 // If this type crosses an eightbyte boundary, it should be
2611 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002612 uint64_t EB_Lo = (OffsetBase) / 64;
2613 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2614 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615 Hi = Lo;
2616 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002617 QualType ElementType = VT->getElementType();
2618
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002620 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 return;
2622
David Majnemere2ae2282016-03-04 05:26:16 +00002623 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2624 // pass them as integer. For platforms where clang is the de facto
2625 // platform compiler, we must continue to use integer.
2626 if (!classifyIntegerMMXAsSSE() &&
2627 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2628 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2629 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2630 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 Current = Integer;
2632 else
2633 Current = SSE;
2634
2635 // If this type crosses an eightbyte boundary, it should be
2636 // split.
2637 if (OffsetBase && OffsetBase != 64)
2638 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002639 } else if (Size == 128 ||
2640 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002641 // Arguments of 256-bits are split into four eightbyte chunks. The
2642 // least significant one belongs to class SSE and all the others to class
2643 // SSEUP. The original Lo and Hi design considers that types can't be
2644 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2645 // This design isn't correct for 256-bits, but since there're no cases
2646 // where the upper parts would need to be inspected, avoid adding
2647 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002648 //
2649 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2650 // registers if they are "named", i.e. not part of the "..." of a
2651 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002652 //
2653 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2654 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 Lo = SSE;
2656 Hi = SSEUp;
2657 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002658 return;
2659 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002660
Chris Lattnerd776fb12010-06-28 21:43:59 +00002661 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002662 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663
Chris Lattner2b037972010-07-29 02:01:43 +00002664 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002665 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666 if (Size <= 64)
2667 Current = Integer;
2668 else if (Size <= 128)
2669 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002670 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002672 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002673 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002674 } else if (ET == getContext().LongDoubleTy) {
2675 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002676 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002677 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002678 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002679 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002680 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002681 Lo = Hi = SSE;
2682 else
2683 llvm_unreachable("unexpected long double representation!");
2684 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685
2686 // If this complex type crosses an eightbyte boundary then it
2687 // should be split.
2688 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002689 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 if (Hi == NoClass && EB_Real != EB_Imag)
2691 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002692
Chris Lattnerd776fb12010-06-28 21:43:59 +00002693 return;
2694 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002695
Chris Lattner2b037972010-07-29 02:01:43 +00002696 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697 // Arrays are treated like structures.
2698
Chris Lattner2b037972010-07-29 02:01:43 +00002699 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700
2701 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002702 // than eight eightbytes, ..., it has class MEMORY.
2703 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704 return;
2705
2706 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2707 // fields, it has class MEMORY.
2708 //
2709 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002710 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 return;
2712
2713 // Otherwise implement simplified merge. We could be smarter about
2714 // this, but it isn't worth it and would be harder to verify.
2715 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002716 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002718
2719 // The only case a 256-bit wide vector could be used is when the array
2720 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2721 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002722 //
2723 if (Size > 128 &&
2724 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002725 return;
2726
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2728 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002729 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730 Lo = merge(Lo, FieldLo);
2731 Hi = merge(Hi, FieldHi);
2732 if (Lo == Memory || Hi == Memory)
2733 break;
2734 }
2735
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002736 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002737 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002738 return;
2739 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002740
Chris Lattnerd776fb12010-06-28 21:43:59 +00002741 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002742 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002743
2744 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002745 // than eight eightbytes, ..., it has class MEMORY.
2746 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747 return;
2748
Anders Carlsson20759ad2009-09-16 15:53:40 +00002749 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2750 // copy constructor or a non-trivial destructor, it is passed by invisible
2751 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002752 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002753 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002754
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002755 const RecordDecl *RD = RT->getDecl();
2756
2757 // Assume variable sized types are passed in memory.
2758 if (RD->hasFlexibleArrayMember())
2759 return;
2760
Chris Lattner2b037972010-07-29 02:01:43 +00002761 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002762
2763 // Reset Lo class, this will be recomputed.
2764 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002765
2766 // If this is a C++ record, classify the bases first.
2767 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002768 for (const auto &I : CXXRD->bases()) {
2769 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002770 "Unexpected base class!");
2771 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002772 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002773
2774 // Classify this field.
2775 //
2776 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2777 // single eightbyte, each is classified separately. Each eightbyte gets
2778 // initialized to class NO_CLASS.
2779 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002780 uint64_t Offset =
2781 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002782 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002783 Lo = merge(Lo, FieldLo);
2784 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002785 if (Lo == Memory || Hi == Memory) {
2786 postMerge(Size, Lo, Hi);
2787 return;
2788 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002789 }
2790 }
2791
2792 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002793 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002794 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002795 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002796 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2797 bool BitField = i->isBitField();
2798
David Majnemerb439dfe2016-08-15 07:20:40 +00002799 // Ignore padding bit-fields.
2800 if (BitField && i->isUnnamedBitfield())
2801 continue;
2802
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002803 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2804 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002805 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002806 // The only case a 256-bit wide vector could be used is when the struct
2807 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2808 // to work for sizes wider than 128, early check and fallback to memory.
2809 //
David Majnemerb229cb02016-08-15 06:39:18 +00002810 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2811 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002812 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002813 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002814 return;
2815 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002816 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002817 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002819 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002820 return;
2821 }
2822
2823 // Classify this field.
2824 //
2825 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2826 // exceeds a single eightbyte, each is classified
2827 // separately. Each eightbyte gets initialized to class
2828 // NO_CLASS.
2829 Class FieldLo, FieldHi;
2830
2831 // Bit-fields require special handling, they do not force the
2832 // structure to be passed in memory even if unaligned, and
2833 // therefore they can straddle an eightbyte.
2834 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002835 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002836 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002837 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002838
2839 uint64_t EB_Lo = Offset / 64;
2840 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002841
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002842 if (EB_Lo) {
2843 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2844 FieldLo = NoClass;
2845 FieldHi = Integer;
2846 } else {
2847 FieldLo = Integer;
2848 FieldHi = EB_Hi ? Integer : NoClass;
2849 }
2850 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002851 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002852 Lo = merge(Lo, FieldLo);
2853 Hi = merge(Hi, FieldHi);
2854 if (Lo == Memory || Hi == Memory)
2855 break;
2856 }
2857
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002858 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002859 }
2860}
2861
Chris Lattner22a931e2010-06-29 06:01:59 +00002862ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002863 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2864 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002865 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002866 // Treat an enum type as its underlying type.
2867 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2868 Ty = EnumTy->getDecl()->getIntegerType();
2869
2870 return (Ty->isPromotableIntegerType() ?
2871 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2872 }
2873
John McCall7f416cc2015-09-08 08:05:57 +00002874 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002875}
2876
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002877bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2878 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2879 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002880 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002881 if (Size <= 64 || Size > LargestVector)
2882 return true;
2883 }
2884
2885 return false;
2886}
2887
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002888ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2889 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002890 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2891 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002892 //
2893 // This assumption is optimistic, as there could be free registers available
2894 // when we need to pass this argument in memory, and LLVM could try to pass
2895 // the argument in the free register. This does not seem to happen currently,
2896 // but this code would be much safer if we could mark the argument with
2897 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002898 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002899 // Treat an enum type as its underlying type.
2900 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2901 Ty = EnumTy->getDecl()->getIntegerType();
2902
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002903 return (Ty->isPromotableIntegerType() ?
2904 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002905 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002906
Mark Lacey3825e832013-10-06 01:33:34 +00002907 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002908 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002909
Chris Lattner44c2b902011-05-22 23:21:23 +00002910 // Compute the byval alignment. We specify the alignment of the byval in all
2911 // cases so that the mid-level optimizer knows the alignment of the byval.
2912 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002913
2914 // Attempt to avoid passing indirect results using byval when possible. This
2915 // is important for good codegen.
2916 //
2917 // We do this by coercing the value into a scalar type which the backend can
2918 // handle naturally (i.e., without using byval).
2919 //
2920 // For simplicity, we currently only do this when we have exhausted all of the
2921 // free integer registers. Doing this when there are free integer registers
2922 // would require more care, as we would have to ensure that the coerced value
2923 // did not claim the unused register. That would require either reording the
2924 // arguments to the function (so that any subsequent inreg values came first),
2925 // or only doing this optimization when there were no following arguments that
2926 // might be inreg.
2927 //
2928 // We currently expect it to be rare (particularly in well written code) for
2929 // arguments to be passed on the stack when there are still free integer
2930 // registers available (this would typically imply large structs being passed
2931 // by value), so this seems like a fair tradeoff for now.
2932 //
2933 // We can revisit this if the backend grows support for 'onstack' parameter
2934 // attributes. See PR12193.
2935 if (freeIntRegs == 0) {
2936 uint64_t Size = getContext().getTypeSize(Ty);
2937
2938 // If this type fits in an eightbyte, coerce it into the matching integral
2939 // type, which will end up on the stack (with alignment 8).
2940 if (Align == 8 && Size <= 64)
2941 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2942 Size));
2943 }
2944
John McCall7f416cc2015-09-08 08:05:57 +00002945 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002946}
2947
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002948/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2949/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002950llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002951 // Wrapper structs/arrays that only contain vectors are passed just like
2952 // vectors; strip them off if present.
2953 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2954 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002955
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002956 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002957 if (isa<llvm::VectorType>(IRType) ||
2958 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002959 return IRType;
2960
2961 // We couldn't find the preferred IR vector type for 'Ty'.
2962 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002963 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002964
2965 // Return a LLVM IR vector type based on the size of 'Ty'.
2966 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2967 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002968}
2969
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002970/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2971/// is known to either be off the end of the specified type or being in
2972/// alignment padding. The user type specified is known to be at most 128 bits
2973/// in size, and have passed through X86_64ABIInfo::classify with a successful
2974/// classification that put one of the two halves in the INTEGER class.
2975///
2976/// It is conservatively correct to return false.
2977static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2978 unsigned EndBit, ASTContext &Context) {
2979 // If the bytes being queried are off the end of the type, there is no user
2980 // data hiding here. This handles analysis of builtins, vectors and other
2981 // types that don't contain interesting padding.
2982 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2983 if (TySize <= StartBit)
2984 return true;
2985
Chris Lattner98076a22010-07-29 07:43:55 +00002986 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2987 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2988 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2989
2990 // Check each element to see if the element overlaps with the queried range.
2991 for (unsigned i = 0; i != NumElts; ++i) {
2992 // If the element is after the span we care about, then we're done..
2993 unsigned EltOffset = i*EltSize;
2994 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002995
Chris Lattner98076a22010-07-29 07:43:55 +00002996 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2997 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2998 EndBit-EltOffset, Context))
2999 return false;
3000 }
3001 // If it overlaps no elements, then it is safe to process as padding.
3002 return true;
3003 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003004
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003005 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3006 const RecordDecl *RD = RT->getDecl();
3007 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003008
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003009 // If this is a C++ record, check the bases first.
3010 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003011 for (const auto &I : CXXRD->bases()) {
3012 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003013 "Unexpected base class!");
3014 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003015 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003016
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003018 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003019 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003020
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003021 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003022 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003023 EndBit-BaseOffset, Context))
3024 return false;
3025 }
3026 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003028 // Verify that no field has data that overlaps the region of interest. Yes
3029 // this could be sped up a lot by being smarter about queried fields,
3030 // however we're only looking at structs up to 16 bytes, so we don't care
3031 // much.
3032 unsigned idx = 0;
3033 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3034 i != e; ++i, ++idx) {
3035 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003036
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003037 // If we found a field after the region we care about, then we're done.
3038 if (FieldOffset >= EndBit) break;
3039
3040 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3041 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3042 Context))
3043 return false;
3044 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003045
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003046 // If nothing in this record overlapped the area of interest, then we're
3047 // clean.
3048 return true;
3049 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003050
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003051 return false;
3052}
3053
Chris Lattnere556a712010-07-29 18:39:32 +00003054/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3055/// float member at the specified offset. For example, {int,{float}} has a
3056/// float at offset 4. It is conservatively correct for this routine to return
3057/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003058static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003059 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003060 // Base case if we find a float.
3061 if (IROffset == 0 && IRType->isFloatTy())
3062 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003063
Chris Lattnere556a712010-07-29 18:39:32 +00003064 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003065 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003066 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3067 unsigned Elt = SL->getElementContainingOffset(IROffset);
3068 IROffset -= SL->getElementOffset(Elt);
3069 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3070 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003071
Chris Lattnere556a712010-07-29 18:39:32 +00003072 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003073 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3074 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003075 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3076 IROffset -= IROffset/EltSize*EltSize;
3077 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3078 }
3079
3080 return false;
3081}
3082
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003083
3084/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3085/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003086llvm::Type *X86_64ABIInfo::
3087GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003088 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003089 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003090 // pass as float if the last 4 bytes is just padding. This happens for
3091 // structs that contain 3 floats.
3092 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3093 SourceOffset*8+64, getContext()))
3094 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003095
Chris Lattnere556a712010-07-29 18:39:32 +00003096 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3097 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3098 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003099 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3100 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003101 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003102
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003103 return llvm::Type::getDoubleTy(getVMContext());
3104}
3105
3106
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003107/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3108/// an 8-byte GPR. This means that we either have a scalar or we are talking
3109/// about the high or low part of an up-to-16-byte struct. This routine picks
3110/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003111/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3112/// etc).
3113///
3114/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3115/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3116/// the 8-byte value references. PrefType may be null.
3117///
Alp Toker9907f082014-07-09 14:06:35 +00003118/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003119/// an offset into this that we're processing (which is always either 0 or 8).
3120///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003121llvm::Type *X86_64ABIInfo::
3122GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003123 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003124 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3125 // returning an 8-byte unit starting with it. See if we can safely use it.
3126 if (IROffset == 0) {
3127 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003128 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3129 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003130 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003131
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003132 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3133 // goodness in the source type is just tail padding. This is allowed to
3134 // kick in for struct {double,int} on the int, but not on
3135 // struct{double,int,int} because we wouldn't return the second int. We
3136 // have to do this analysis on the source type because we can't depend on
3137 // unions being lowered a specific way etc.
3138 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003139 IRType->isIntegerTy(32) ||
3140 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3141 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3142 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003143
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003144 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3145 SourceOffset*8+64, getContext()))
3146 return IRType;
3147 }
3148 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003149
Chris Lattner2192fe52011-07-18 04:24:23 +00003150 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003151 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003152 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003153 if (IROffset < SL->getSizeInBytes()) {
3154 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3155 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003156
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003157 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3158 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003159 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003160 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003161
Chris Lattner2192fe52011-07-18 04:24:23 +00003162 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003163 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003164 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003165 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003166 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3167 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003168 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003169
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003170 // Okay, we don't have any better idea of what to pass, so we pass this in an
3171 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003172 unsigned TySizeInBytes =
3173 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003174
Chris Lattner3f763422010-07-29 17:34:39 +00003175 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003176
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003177 // It is always safe to classify this as an integer type up to i64 that
3178 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003179 return llvm::IntegerType::get(getVMContext(),
3180 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003181}
3182
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003183
3184/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3185/// be used as elements of a two register pair to pass or return, return a
3186/// first class aggregate to represent them. For example, if the low part of
3187/// a by-value argument should be passed as i32* and the high part as float,
3188/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003189static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003190GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003191 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003192 // In order to correctly satisfy the ABI, we need to the high part to start
3193 // at offset 8. If the high and low parts we inferred are both 4-byte types
3194 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3195 // the second element at offset 8. Check for this:
3196 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3197 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003198 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003199 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003200
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003201 // To handle this, we have to increase the size of the low part so that the
3202 // second element will start at an 8 byte offset. We can't increase the size
3203 // of the second element because it might make us access off the end of the
3204 // struct.
3205 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003206 // There are usually two sorts of types the ABI generation code can produce
3207 // for the low part of a pair that aren't 8 bytes in size: float or
3208 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3209 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003210 // Promote these to a larger type.
3211 if (Lo->isFloatTy())
3212 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3213 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003214 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3215 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003216 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3217 }
3218 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003219
Serge Guelton1d993272017-05-09 19:31:30 +00003220 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003221
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003222 // Verify that the second element is at an 8-byte offset.
3223 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3224 "Invalid x86-64 argument pair!");
3225 return Result;
3226}
3227
Chris Lattner31faff52010-07-28 23:06:14 +00003228ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003229classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003230 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3231 // classification algorithm.
3232 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003233 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003234
3235 // Check some invariants.
3236 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003237 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3238
Craig Topper8a13c412014-05-21 05:09:00 +00003239 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003240 switch (Lo) {
3241 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003242 if (Hi == NoClass)
3243 return ABIArgInfo::getIgnore();
3244 // If the low part is just padding, it takes no register, leave ResType
3245 // null.
3246 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3247 "Unknown missing lo part");
3248 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003249
3250 case SSEUp:
3251 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003252 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003253
3254 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3255 // hidden argument.
3256 case Memory:
3257 return getIndirectReturnResult(RetTy);
3258
3259 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3260 // available register of the sequence %rax, %rdx is used.
3261 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003262 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003263
Chris Lattner1f3a0632010-07-29 21:42:50 +00003264 // If we have a sign or zero extended integer, make sure to return Extend
3265 // so that the parameter gets the right LLVM IR attributes.
3266 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3267 // Treat an enum type as its underlying type.
3268 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3269 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003270
Chris Lattner1f3a0632010-07-29 21:42:50 +00003271 if (RetTy->isIntegralOrEnumerationType() &&
3272 RetTy->isPromotableIntegerType())
3273 return ABIArgInfo::getExtend();
3274 }
Chris Lattner31faff52010-07-28 23:06:14 +00003275 break;
3276
3277 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3278 // available SSE register of the sequence %xmm0, %xmm1 is used.
3279 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003280 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003281 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003282
3283 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3284 // returned on the X87 stack in %st0 as 80-bit x87 number.
3285 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003286 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003287 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003288
3289 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3290 // part of the value is returned in %st0 and the imaginary part in
3291 // %st1.
3292 case ComplexX87:
3293 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003294 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003295 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003296 break;
3297 }
3298
Craig Topper8a13c412014-05-21 05:09:00 +00003299 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003300 switch (Hi) {
3301 // Memory was handled previously and X87 should
3302 // never occur as a hi class.
3303 case Memory:
3304 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003305 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003306
3307 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003308 case NoClass:
3309 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003310
Chris Lattner52b3c132010-09-01 00:20:33 +00003311 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003312 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003313 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3314 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003315 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003316 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003317 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003318 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3319 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003320 break;
3321
3322 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003323 // is passed in the next available eightbyte chunk if the last used
3324 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003325 //
Chris Lattner57540c52011-04-15 05:22:18 +00003326 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003327 case SSEUp:
3328 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003329 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003330 break;
3331
3332 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3333 // returned together with the previous X87 value in %st0.
3334 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003335 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003336 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003337 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003338 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003339 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003340 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003341 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3342 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003343 }
Chris Lattner31faff52010-07-28 23:06:14 +00003344 break;
3345 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003346
Chris Lattner52b3c132010-09-01 00:20:33 +00003347 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003348 // known to pass in the high eightbyte of the result. We do this by forming a
3349 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003350 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003351 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003352
Chris Lattner1f3a0632010-07-29 21:42:50 +00003353 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003354}
3355
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003356ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003357 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3358 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003359 const
3360{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003361 Ty = useFirstFieldIfTransparentUnion(Ty);
3362
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003363 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003364 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003365
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366 // Check some invariants.
3367 // FIXME: Enforce these by construction.
3368 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003369 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3370
3371 neededInt = 0;
3372 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003373 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374 switch (Lo) {
3375 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003376 if (Hi == NoClass)
3377 return ABIArgInfo::getIgnore();
3378 // If the low part is just padding, it takes no register, leave ResType
3379 // null.
3380 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3381 "Unknown missing lo part");
3382 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003383
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003384 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3385 // on the stack.
3386 case Memory:
3387
3388 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3389 // COMPLEX_X87, it is passed in memory.
3390 case X87:
3391 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003392 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003393 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003394 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003395
3396 case SSEUp:
3397 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003398 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003399
3400 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3401 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3402 // and %r9 is used.
3403 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003404 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003405
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003406 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003407 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003408
3409 // If we have a sign or zero extended integer, make sure to return Extend
3410 // so that the parameter gets the right LLVM IR attributes.
3411 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3412 // Treat an enum type as its underlying type.
3413 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3414 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003415
Chris Lattner1f3a0632010-07-29 21:42:50 +00003416 if (Ty->isIntegralOrEnumerationType() &&
3417 Ty->isPromotableIntegerType())
3418 return ABIArgInfo::getExtend();
3419 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003420
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003421 break;
3422
3423 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3424 // available SSE register is used, the registers are taken in the
3425 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003426 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003427 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003428 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003429 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003430 break;
3431 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003432 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003433
Craig Topper8a13c412014-05-21 05:09:00 +00003434 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003435 switch (Hi) {
3436 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003437 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003438 // which is passed in memory.
3439 case Memory:
3440 case X87:
3441 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003442 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003443
3444 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003445
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003446 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003447 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003448 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003449 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003450
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003451 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3452 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003453 break;
3454
3455 // X87Up generally doesn't occur here (long double is passed in
3456 // memory), except in situations involving unions.
3457 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003458 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003459 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003460
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003461 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3462 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003463
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003464 ++neededSSE;
3465 break;
3466
3467 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3468 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003469 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003470 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003471 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003472 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003473 break;
3474 }
3475
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003476 // If a high part was specified, merge it together with the low part. It is
3477 // known to pass in the high eightbyte of the result. We do this by forming a
3478 // first class struct aggregate with the high and low part: {low, high}
3479 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003480 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003481
Chris Lattner1f3a0632010-07-29 21:42:50 +00003482 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003483}
3484
Erich Keane757d3172016-11-02 18:29:35 +00003485ABIArgInfo
3486X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3487 unsigned &NeededSSE) const {
3488 auto RT = Ty->getAs<RecordType>();
3489 assert(RT && "classifyRegCallStructType only valid with struct types");
3490
3491 if (RT->getDecl()->hasFlexibleArrayMember())
3492 return getIndirectReturnResult(Ty);
3493
3494 // Sum up bases
3495 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3496 if (CXXRD->isDynamicClass()) {
3497 NeededInt = NeededSSE = 0;
3498 return getIndirectReturnResult(Ty);
3499 }
3500
3501 for (const auto &I : CXXRD->bases())
3502 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3503 .isIndirect()) {
3504 NeededInt = NeededSSE = 0;
3505 return getIndirectReturnResult(Ty);
3506 }
3507 }
3508
3509 // Sum up members
3510 for (const auto *FD : RT->getDecl()->fields()) {
3511 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3512 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3513 .isIndirect()) {
3514 NeededInt = NeededSSE = 0;
3515 return getIndirectReturnResult(Ty);
3516 }
3517 } else {
3518 unsigned LocalNeededInt, LocalNeededSSE;
3519 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3520 LocalNeededSSE, true)
3521 .isIndirect()) {
3522 NeededInt = NeededSSE = 0;
3523 return getIndirectReturnResult(Ty);
3524 }
3525 NeededInt += LocalNeededInt;
3526 NeededSSE += LocalNeededSSE;
3527 }
3528 }
3529
3530 return ABIArgInfo::getDirect();
3531}
3532
3533ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3534 unsigned &NeededInt,
3535 unsigned &NeededSSE) const {
3536
3537 NeededInt = 0;
3538 NeededSSE = 0;
3539
3540 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3541}
3542
Chris Lattner22326a12010-07-29 02:31:05 +00003543void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003544
Erich Keane757d3172016-11-02 18:29:35 +00003545 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003546
3547 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003548 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3549 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3550 unsigned NeededInt, NeededSSE;
3551
Erich Keanede1b2a92017-07-21 18:50:36 +00003552 if (!getCXXABI().classifyReturnType(FI)) {
3553 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3554 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3555 FI.getReturnInfo() =
3556 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3557 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3558 FreeIntRegs -= NeededInt;
3559 FreeSSERegs -= NeededSSE;
3560 } else {
3561 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3562 }
3563 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3564 // Complex Long Double Type is passed in Memory when Regcall
3565 // calling convention is used.
3566 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3567 if (getContext().getCanonicalType(CT->getElementType()) ==
3568 getContext().LongDoubleTy)
3569 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3570 } else
3571 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3572 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003573
3574 // If the return value is indirect, then the hidden argument is consuming one
3575 // integer register.
3576 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003577 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003578
Peter Collingbournef7706832014-12-12 23:41:25 +00003579 // The chain argument effectively gives us another free register.
3580 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003581 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003582
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003583 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003584 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3585 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003586 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003587 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003588 it != ie; ++it, ++ArgNo) {
3589 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003590
Erich Keane757d3172016-11-02 18:29:35 +00003591 if (IsRegCall && it->type->isStructureOrClassType())
3592 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3593 else
3594 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3595 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003596
3597 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3598 // eightbyte of an argument, the whole argument is passed on the
3599 // stack. If registers have already been assigned for some
3600 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003601 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3602 FreeIntRegs -= NeededInt;
3603 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003604 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003605 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003606 }
3607 }
3608}
3609
John McCall7f416cc2015-09-08 08:05:57 +00003610static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3611 Address VAListAddr, QualType Ty) {
3612 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3613 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003614 llvm::Value *overflow_arg_area =
3615 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3616
3617 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3618 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003619 // It isn't stated explicitly in the standard, but in practice we use
3620 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003621 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3622 if (Align > CharUnits::fromQuantity(8)) {
3623 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3624 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003625 }
3626
3627 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003628 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003629 llvm::Value *Res =
3630 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003631 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003632
3633 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3634 // l->overflow_arg_area + sizeof(type).
3635 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3636 // an 8 byte boundary.
3637
3638 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003639 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003640 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003641 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3642 "overflow_arg_area.next");
3643 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3644
3645 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003646 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003647}
3648
John McCall7f416cc2015-09-08 08:05:57 +00003649Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3650 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003651 // Assume that va_list type is correct; should be pointer to LLVM type:
3652 // struct {
3653 // i32 gp_offset;
3654 // i32 fp_offset;
3655 // i8* overflow_arg_area;
3656 // i8* reg_save_area;
3657 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003658 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003659
John McCall7f416cc2015-09-08 08:05:57 +00003660 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003661 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003662 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003663
3664 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3665 // in the registers. If not go to step 7.
3666 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003667 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003668
3669 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3670 // general purpose registers needed to pass type and num_fp to hold
3671 // the number of floating point registers needed.
3672
3673 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3674 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3675 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3676 //
3677 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3678 // register save space).
3679
Craig Topper8a13c412014-05-21 05:09:00 +00003680 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003681 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3682 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003683 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003684 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003685 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3686 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003687 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003688 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3689 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003690 }
3691
3692 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003693 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003694 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3695 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003696 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3697 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003698 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3699 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003700 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3701 }
3702
3703 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3704 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3705 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3706 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3707
3708 // Emit code to load the value if it was passed in registers.
3709
3710 CGF.EmitBlock(InRegBlock);
3711
3712 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3713 // an offset of l->gp_offset and/or l->fp_offset. This may require
3714 // copying to a temporary location in case the parameter is passed
3715 // in different register classes or requires an alignment greater
3716 // than 8 for general purpose registers and 16 for XMM registers.
3717 //
3718 // FIXME: This really results in shameful code when we end up needing to
3719 // collect arguments from different places; often what should result in a
3720 // simple assembling of a structure from scattered addresses has many more
3721 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003722 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003723 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3724 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3725 "reg_save_area");
3726
3727 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003728 if (neededInt && neededSSE) {
3729 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003730 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003731 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003732 Address Tmp = CGF.CreateMemTemp(Ty);
3733 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003734 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003735 llvm::Type *TyLo = ST->getElementType(0);
3736 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003737 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003738 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003739 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3740 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003741 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3742 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003743 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3744 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003745
John McCall7f416cc2015-09-08 08:05:57 +00003746 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003747 // FIXME: Our choice of alignment here and below is probably pessimistic.
3748 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3749 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3750 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003751 CGF.Builder.CreateStore(V,
3752 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3753
3754 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003755 V = CGF.Builder.CreateAlignedLoad(
3756 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3757 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003758 CharUnits Offset = CharUnits::fromQuantity(
3759 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3760 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3761
3762 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003763 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003764 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3765 CharUnits::fromQuantity(8));
3766 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003767
3768 // Copy to a temporary if necessary to ensure the appropriate alignment.
3769 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003770 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003771 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003772 CharUnits TyAlign = SizeAlign.second;
3773
3774 // Copy into a temporary if the type is more aligned than the
3775 // register save area.
3776 if (TyAlign.getQuantity() > 8) {
3777 Address Tmp = CGF.CreateMemTemp(Ty);
3778 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003779 RegAddr = Tmp;
3780 }
John McCall7f416cc2015-09-08 08:05:57 +00003781
Chris Lattner0cf24192010-06-28 20:05:43 +00003782 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003783 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3784 CharUnits::fromQuantity(16));
3785 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003786 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003787 assert(neededSSE == 2 && "Invalid number of needed registers!");
3788 // SSE registers are spaced 16 bytes apart in the register save
3789 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003790 // The ABI isn't explicit about this, but it seems reasonable
3791 // to assume that the slots are 16-byte aligned, since the stack is
3792 // naturally 16-byte aligned and the prologue is expected to store
3793 // all the SSE registers to the RSA.
3794 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3795 CharUnits::fromQuantity(16));
3796 Address RegAddrHi =
3797 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3798 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003799 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003800 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003801 llvm::Value *V;
3802 Address Tmp = CGF.CreateMemTemp(Ty);
3803 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3804 V = CGF.Builder.CreateLoad(
3805 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3806 CGF.Builder.CreateStore(V,
3807 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3808 V = CGF.Builder.CreateLoad(
3809 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3810 CGF.Builder.CreateStore(V,
3811 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3812
3813 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003814 }
3815
3816 // AMD64-ABI 3.5.7p5: Step 5. Set:
3817 // l->gp_offset = l->gp_offset + num_gp * 8
3818 // l->fp_offset = l->fp_offset + num_fp * 16.
3819 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003820 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003821 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3822 gp_offset_p);
3823 }
3824 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003825 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003826 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3827 fp_offset_p);
3828 }
3829 CGF.EmitBranch(ContBlock);
3830
3831 // Emit code to load the value if it was passed in memory.
3832
3833 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003834 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003835
3836 // Return the appropriate result.
3837
3838 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003839 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3840 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003841 return ResAddr;
3842}
3843
Charles Davisc7d5c942015-09-17 20:55:33 +00003844Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3845 QualType Ty) const {
3846 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3847 CGF.getContext().getTypeInfoInChars(Ty),
3848 CharUnits::fromQuantity(8),
3849 /*allowHigherAlign*/ false);
3850}
3851
Erich Keane521ed962017-01-05 00:20:51 +00003852ABIArgInfo
3853WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3854 const ABIArgInfo &current) const {
3855 // Assumes vectorCall calling convention.
3856 const Type *Base = nullptr;
3857 uint64_t NumElts = 0;
3858
3859 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3860 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3861 FreeSSERegs -= NumElts;
3862 return getDirectX86Hva();
3863 }
3864 return current;
3865}
3866
Reid Kleckner80944df2014-10-31 22:00:51 +00003867ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003868 bool IsReturnType, bool IsVectorCall,
3869 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003870
3871 if (Ty->isVoidType())
3872 return ABIArgInfo::getIgnore();
3873
3874 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3875 Ty = EnumTy->getDecl()->getIntegerType();
3876
Reid Kleckner80944df2014-10-31 22:00:51 +00003877 TypeInfo Info = getContext().getTypeInfo(Ty);
3878 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003879 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003880
Reid Kleckner9005f412014-05-02 00:51:20 +00003881 const RecordType *RT = Ty->getAs<RecordType>();
3882 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003883 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003884 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003885 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003886 }
3887
3888 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003889 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003890
Reid Kleckner9005f412014-05-02 00:51:20 +00003891 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003892
Reid Kleckner80944df2014-10-31 22:00:51 +00003893 const Type *Base = nullptr;
3894 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003895 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3896 // other targets.
3897 if ((IsVectorCall || IsRegCall) &&
3898 isHomogeneousAggregate(Ty, Base, NumElts)) {
3899 if (IsRegCall) {
3900 if (FreeSSERegs >= NumElts) {
3901 FreeSSERegs -= NumElts;
3902 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3903 return ABIArgInfo::getDirect();
3904 return ABIArgInfo::getExpand();
3905 }
3906 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3907 } else if (IsVectorCall) {
3908 if (FreeSSERegs >= NumElts &&
3909 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3910 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003911 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003912 } else if (IsReturnType) {
3913 return ABIArgInfo::getExpand();
3914 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3915 // HVAs are delayed and reclassified in the 2nd step.
3916 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3917 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003918 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003919 }
3920
Reid Klecknerec87fec2014-05-02 01:17:12 +00003921 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003922 // If the member pointer is represented by an LLVM int or ptr, pass it
3923 // directly.
3924 llvm::Type *LLTy = CGT.ConvertType(Ty);
3925 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3926 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003927 }
3928
Michael Kuperstein4f818702015-02-24 09:35:58 +00003929 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003930 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3931 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003932 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003933 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003934
Reid Kleckner9005f412014-05-02 00:51:20 +00003935 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003936 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003937 }
3938
Julien Lerouge10dcff82014-08-27 00:36:55 +00003939 // Bool type is always extended to the ABI, other builtin types are not
3940 // extended.
3941 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3942 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003943 return ABIArgInfo::getExtend();
3944
Reid Kleckner11a17192015-10-28 22:29:52 +00003945 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3946 // passes them indirectly through memory.
3947 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3948 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003949 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003950 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3951 }
3952
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003953 return ABIArgInfo::getDirect();
3954}
3955
Erich Keane521ed962017-01-05 00:20:51 +00003956void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3957 unsigned FreeSSERegs,
3958 bool IsVectorCall,
3959 bool IsRegCall) const {
3960 unsigned Count = 0;
3961 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003962 // Vectorcall in x64 only permits the first 6 arguments to be passed
3963 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003964 if (Count < VectorcallMaxParamNumAsReg)
3965 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3966 else {
3967 // Since these cannot be passed in registers, pretend no registers
3968 // are left.
3969 unsigned ZeroSSERegsAvail = 0;
3970 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3971 IsVectorCall, IsRegCall);
3972 }
3973 ++Count;
3974 }
3975
Erich Keane521ed962017-01-05 00:20:51 +00003976 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003977 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003978 }
3979}
3980
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003981void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003982 bool IsVectorCall =
3983 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003984 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003985
Erich Keane757d3172016-11-02 18:29:35 +00003986 unsigned FreeSSERegs = 0;
3987 if (IsVectorCall) {
3988 // We can use up to 4 SSE return registers with vectorcall.
3989 FreeSSERegs = 4;
3990 } else if (IsRegCall) {
3991 // RegCall gives us 16 SSE registers.
3992 FreeSSERegs = 16;
3993 }
3994
Reid Kleckner80944df2014-10-31 22:00:51 +00003995 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003996 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3997 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003998
Erich Keane757d3172016-11-02 18:29:35 +00003999 if (IsVectorCall) {
4000 // We can use up to 6 SSE register parameters with vectorcall.
4001 FreeSSERegs = 6;
4002 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004003 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004004 FreeSSERegs = 16;
4005 }
4006
Erich Keane521ed962017-01-05 00:20:51 +00004007 if (IsVectorCall) {
4008 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4009 } else {
4010 for (auto &I : FI.arguments())
4011 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4012 }
4013
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004014}
4015
John McCall7f416cc2015-09-08 08:05:57 +00004016Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4017 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004018
4019 bool IsIndirect = false;
4020
4021 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4022 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4023 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4024 uint64_t Width = getContext().getTypeSize(Ty);
4025 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4026 }
4027
4028 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004029 CGF.getContext().getTypeInfoInChars(Ty),
4030 CharUnits::fromQuantity(8),
4031 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004032}
Chris Lattner0cf24192010-06-28 20:05:43 +00004033
John McCallea8d8bb2010-03-11 00:10:12 +00004034// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004035namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004036/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4037class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004038bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004039public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004040 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4041 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004042
John McCall7f416cc2015-09-08 08:05:57 +00004043 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4044 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004045};
4046
4047class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4048public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004049 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4050 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004051
Craig Topper4f12f102014-03-12 06:41:41 +00004052 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004053 // This is recovered from gcc output.
4054 return 1; // r1 is the dedicated stack pointer
4055 }
4056
4057 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004058 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004059};
4060
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004061}
John McCallea8d8bb2010-03-11 00:10:12 +00004062
James Y Knight29b5f082016-02-24 02:59:33 +00004063// TODO: this implementation is now likely redundant with
4064// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004065Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4066 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004067 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004068 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4069 // TODO: Implement this. For now ignore.
4070 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004071 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004072 }
4073
John McCall7f416cc2015-09-08 08:05:57 +00004074 // struct __va_list_tag {
4075 // unsigned char gpr;
4076 // unsigned char fpr;
4077 // unsigned short reserved;
4078 // void *overflow_arg_area;
4079 // void *reg_save_area;
4080 // };
4081
Roman Divacky8a12d842014-11-03 18:32:54 +00004082 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004083 bool isInt =
4084 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004085 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004086
4087 // All aggregates are passed indirectly? That doesn't seem consistent
4088 // with the argument-lowering code.
4089 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004090
4091 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004092
4093 // The calling convention either uses 1-2 GPRs or 1 FPR.
4094 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004095 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004096 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4097 } else {
4098 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004099 }
John McCall7f416cc2015-09-08 08:05:57 +00004100
4101 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4102
4103 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004104 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004105 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4106 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4107 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004108
Eric Christopher7565e0d2015-05-29 23:09:49 +00004109 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004110 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004111
4112 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4113 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4114 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4115
4116 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4117
John McCall7f416cc2015-09-08 08:05:57 +00004118 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4119 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004120
John McCall7f416cc2015-09-08 08:05:57 +00004121 // Case 1: consume registers.
4122 Address RegAddr = Address::invalid();
4123 {
4124 CGF.EmitBlock(UsingRegs);
4125
4126 Address RegSaveAreaPtr =
4127 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4128 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4129 CharUnits::fromQuantity(8));
4130 assert(RegAddr.getElementType() == CGF.Int8Ty);
4131
4132 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004133 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004134 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4135 CharUnits::fromQuantity(32));
4136 }
4137
4138 // Get the address of the saved value by scaling the number of
4139 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004140 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004141 llvm::Value *RegOffset =
4142 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4143 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4144 RegAddr.getPointer(), RegOffset),
4145 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4146 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4147
4148 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004149 NumRegs =
4150 Builder.CreateAdd(NumRegs,
4151 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004152 Builder.CreateStore(NumRegs, NumRegsAddr);
4153
4154 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004155 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004156
John McCall7f416cc2015-09-08 08:05:57 +00004157 // Case 2: consume space in the overflow area.
4158 Address MemAddr = Address::invalid();
4159 {
4160 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004161
Roman Divacky039b9702016-02-20 08:31:24 +00004162 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4163
John McCall7f416cc2015-09-08 08:05:57 +00004164 // Everything in the overflow area is rounded up to a size of at least 4.
4165 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4166
4167 CharUnits Size;
4168 if (!isIndirect) {
4169 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004170 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004171 } else {
4172 Size = CGF.getPointerSize();
4173 }
4174
4175 Address OverflowAreaAddr =
4176 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004177 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004178 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004179 // Round up address of argument to alignment
4180 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4181 if (Align > OverflowAreaAlign) {
4182 llvm::Value *Ptr = OverflowArea.getPointer();
4183 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4184 Align);
4185 }
4186
John McCall7f416cc2015-09-08 08:05:57 +00004187 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4188
4189 // Increase the overflow area.
4190 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4191 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4192 CGF.EmitBranch(Cont);
4193 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004194
4195 CGF.EmitBlock(Cont);
4196
John McCall7f416cc2015-09-08 08:05:57 +00004197 // Merge the cases with a phi.
4198 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4199 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004200
John McCall7f416cc2015-09-08 08:05:57 +00004201 // Load the pointer if the argument was passed indirectly.
4202 if (isIndirect) {
4203 Result = Address(Builder.CreateLoad(Result, "aggr"),
4204 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004205 }
4206
4207 return Result;
4208}
4209
John McCallea8d8bb2010-03-11 00:10:12 +00004210bool
4211PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4212 llvm::Value *Address) const {
4213 // This is calculated from the LLVM and GCC tables and verified
4214 // against gcc output. AFAIK all ABIs use the same encoding.
4215
4216 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004217
Chris Lattnerece04092012-02-07 00:39:47 +00004218 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004219 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4220 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4221 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4222
4223 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004224 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004225
4226 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004227 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004228
4229 // 64-76 are various 4-byte special-purpose registers:
4230 // 64: mq
4231 // 65: lr
4232 // 66: ctr
4233 // 67: ap
4234 // 68-75 cr0-7
4235 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004236 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004237
4238 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004239 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004240
4241 // 109: vrsave
4242 // 110: vscr
4243 // 111: spe_acc
4244 // 112: spefscr
4245 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004246 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004247
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004248 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004249}
4250
Roman Divackyd966e722012-05-09 18:22:46 +00004251// PowerPC-64
4252
4253namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004254/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004255class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004256public:
4257 enum ABIKind {
4258 ELFv1 = 0,
4259 ELFv2
4260 };
4261
4262private:
4263 static const unsigned GPRBits = 64;
4264 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004265 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004266 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004267
4268 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4269 // will be passed in a QPX register.
4270 bool IsQPXVectorTy(const Type *Ty) const {
4271 if (!HasQPX)
4272 return false;
4273
4274 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4275 unsigned NumElements = VT->getNumElements();
4276 if (NumElements == 1)
4277 return false;
4278
4279 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4280 if (getContext().getTypeSize(Ty) <= 256)
4281 return true;
4282 } else if (VT->getElementType()->
4283 isSpecificBuiltinType(BuiltinType::Float)) {
4284 if (getContext().getTypeSize(Ty) <= 128)
4285 return true;
4286 }
4287 }
4288
4289 return false;
4290 }
4291
4292 bool IsQPXVectorTy(QualType Ty) const {
4293 return IsQPXVectorTy(Ty.getTypePtr());
4294 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004295
4296public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004297 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4298 bool SoftFloatABI)
4299 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4300 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004301
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004302 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004303 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004304
4305 ABIArgInfo classifyReturnType(QualType RetTy) const;
4306 ABIArgInfo classifyArgumentType(QualType Ty) const;
4307
Reid Klecknere9f6a712014-10-31 17:10:41 +00004308 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4309 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4310 uint64_t Members) const override;
4311
Bill Schmidt84d37792012-10-12 19:26:17 +00004312 // TODO: We can add more logic to computeInfo to improve performance.
4313 // Example: For aggregate arguments that fit in a register, we could
4314 // use getDirectInReg (as is done below for structs containing a single
4315 // floating-point value) to avoid pushing them to memory on function
4316 // entry. This would require changing the logic in PPCISelLowering
4317 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004318 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004319 if (!getCXXABI().classifyReturnType(FI))
4320 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004321 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004322 // We rely on the default argument classification for the most part.
4323 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004324 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004325 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004326 if (T) {
4327 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004328 if (IsQPXVectorTy(T) ||
4329 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004330 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004331 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004332 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004333 continue;
4334 }
4335 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004336 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004337 }
4338 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004339
John McCall7f416cc2015-09-08 08:05:57 +00004340 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4341 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004342};
4343
4344class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004345
Bill Schmidt25cb3492012-10-03 19:18:57 +00004346public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004347 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004348 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4349 bool SoftFloatABI)
4350 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4351 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004352
Craig Topper4f12f102014-03-12 06:41:41 +00004353 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004354 // This is recovered from gcc output.
4355 return 1; // r1 is the dedicated stack pointer
4356 }
4357
4358 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004359 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004360};
4361
Roman Divackyd966e722012-05-09 18:22:46 +00004362class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4363public:
4364 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4365
Craig Topper4f12f102014-03-12 06:41:41 +00004366 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004367 // This is recovered from gcc output.
4368 return 1; // r1 is the dedicated stack pointer
4369 }
4370
4371 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004372 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004373};
4374
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004375}
Roman Divackyd966e722012-05-09 18:22:46 +00004376
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004377// Return true if the ABI requires Ty to be passed sign- or zero-
4378// extended to 64 bits.
4379bool
4380PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4381 // Treat an enum type as its underlying type.
4382 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4383 Ty = EnumTy->getDecl()->getIntegerType();
4384
4385 // Promotable integer types are required to be promoted by the ABI.
4386 if (Ty->isPromotableIntegerType())
4387 return true;
4388
4389 // In addition to the usual promotable integer types, we also need to
4390 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4391 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4392 switch (BT->getKind()) {
4393 case BuiltinType::Int:
4394 case BuiltinType::UInt:
4395 return true;
4396 default:
4397 break;
4398 }
4399
4400 return false;
4401}
4402
John McCall7f416cc2015-09-08 08:05:57 +00004403/// isAlignedParamType - Determine whether a type requires 16-byte or
4404/// higher alignment in the parameter area. Always returns at least 8.
4405CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004406 // Complex types are passed just like their elements.
4407 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4408 Ty = CTy->getElementType();
4409
4410 // Only vector types of size 16 bytes need alignment (larger types are
4411 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004412 if (IsQPXVectorTy(Ty)) {
4413 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004414 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004415
John McCall7f416cc2015-09-08 08:05:57 +00004416 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004417 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004418 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004419 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004420
4421 // For single-element float/vector structs, we consider the whole type
4422 // to have the same alignment requirements as its single element.
4423 const Type *AlignAsType = nullptr;
4424 const Type *EltType = isSingleElementStruct(Ty, getContext());
4425 if (EltType) {
4426 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004427 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004428 getContext().getTypeSize(EltType) == 128) ||
4429 (BT && BT->isFloatingPoint()))
4430 AlignAsType = EltType;
4431 }
4432
Ulrich Weigandb7122372014-07-21 00:48:09 +00004433 // Likewise for ELFv2 homogeneous aggregates.
4434 const Type *Base = nullptr;
4435 uint64_t Members = 0;
4436 if (!AlignAsType && Kind == ELFv2 &&
4437 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4438 AlignAsType = Base;
4439
Ulrich Weigand581badc2014-07-10 17:20:07 +00004440 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004441 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4442 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004443 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004444
John McCall7f416cc2015-09-08 08:05:57 +00004445 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004446 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004447 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004448 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004449
4450 // Otherwise, we only need alignment for any aggregate type that
4451 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004452 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4453 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004454 return CharUnits::fromQuantity(32);
4455 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004456 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004457
John McCall7f416cc2015-09-08 08:05:57 +00004458 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004459}
4460
Ulrich Weigandb7122372014-07-21 00:48:09 +00004461/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4462/// aggregate. Base is set to the base element type, and Members is set
4463/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004464bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4465 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004466 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4467 uint64_t NElements = AT->getSize().getZExtValue();
4468 if (NElements == 0)
4469 return false;
4470 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4471 return false;
4472 Members *= NElements;
4473 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4474 const RecordDecl *RD = RT->getDecl();
4475 if (RD->hasFlexibleArrayMember())
4476 return false;
4477
4478 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004479
4480 // If this is a C++ record, check the bases first.
4481 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4482 for (const auto &I : CXXRD->bases()) {
4483 // Ignore empty records.
4484 if (isEmptyRecord(getContext(), I.getType(), true))
4485 continue;
4486
4487 uint64_t FldMembers;
4488 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4489 return false;
4490
4491 Members += FldMembers;
4492 }
4493 }
4494
Ulrich Weigandb7122372014-07-21 00:48:09 +00004495 for (const auto *FD : RD->fields()) {
4496 // Ignore (non-zero arrays of) empty records.
4497 QualType FT = FD->getType();
4498 while (const ConstantArrayType *AT =
4499 getContext().getAsConstantArrayType(FT)) {
4500 if (AT->getSize().getZExtValue() == 0)
4501 return false;
4502 FT = AT->getElementType();
4503 }
4504 if (isEmptyRecord(getContext(), FT, true))
4505 continue;
4506
4507 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4508 if (getContext().getLangOpts().CPlusPlus &&
4509 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4510 continue;
4511
4512 uint64_t FldMembers;
4513 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4514 return false;
4515
4516 Members = (RD->isUnion() ?
4517 std::max(Members, FldMembers) : Members + FldMembers);
4518 }
4519
4520 if (!Base)
4521 return false;
4522
4523 // Ensure there is no padding.
4524 if (getContext().getTypeSize(Base) * Members !=
4525 getContext().getTypeSize(Ty))
4526 return false;
4527 } else {
4528 Members = 1;
4529 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4530 Members = 2;
4531 Ty = CT->getElementType();
4532 }
4533
Reid Klecknere9f6a712014-10-31 17:10:41 +00004534 // Most ABIs only support float, double, and some vector type widths.
4535 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004536 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004537
4538 // The base type must be the same for all members. Types that
4539 // agree in both total size and mode (float vs. vector) are
4540 // treated as being equivalent here.
4541 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004542 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004543 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004544 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4545 // so make sure to widen it explicitly.
4546 if (const VectorType *VT = Base->getAs<VectorType>()) {
4547 QualType EltTy = VT->getElementType();
4548 unsigned NumElements =
4549 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4550 Base = getContext()
4551 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4552 .getTypePtr();
4553 }
4554 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004555
4556 if (Base->isVectorType() != TyPtr->isVectorType() ||
4557 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4558 return false;
4559 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004560 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4561}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004562
Reid Klecknere9f6a712014-10-31 17:10:41 +00004563bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4564 // Homogeneous aggregates for ELFv2 must have base types of float,
4565 // double, long double, or 128-bit vectors.
4566 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4567 if (BT->getKind() == BuiltinType::Float ||
4568 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004569 BT->getKind() == BuiltinType::LongDouble) {
4570 if (IsSoftFloatABI)
4571 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004572 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004573 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004574 }
4575 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004576 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004577 return true;
4578 }
4579 return false;
4580}
4581
4582bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4583 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004584 // Vector types require one register, floating point types require one
4585 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004586 uint32_t NumRegs =
4587 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004588
4589 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004590 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004591}
4592
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004593ABIArgInfo
4594PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004595 Ty = useFirstFieldIfTransparentUnion(Ty);
4596
Bill Schmidt90b22c92012-11-27 02:46:43 +00004597 if (Ty->isAnyComplexType())
4598 return ABIArgInfo::getDirect();
4599
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004600 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4601 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004602 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004603 uint64_t Size = getContext().getTypeSize(Ty);
4604 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004605 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004606 else if (Size < 128) {
4607 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4608 return ABIArgInfo::getDirect(CoerceTy);
4609 }
4610 }
4611
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004612 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004613 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004614 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004615
John McCall7f416cc2015-09-08 08:05:57 +00004616 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4617 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004618
4619 // ELFv2 homogeneous aggregates are passed as array types.
4620 const Type *Base = nullptr;
4621 uint64_t Members = 0;
4622 if (Kind == ELFv2 &&
4623 isHomogeneousAggregate(Ty, Base, Members)) {
4624 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4625 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4626 return ABIArgInfo::getDirect(CoerceTy);
4627 }
4628
Ulrich Weigand601957f2014-07-21 00:56:36 +00004629 // If an aggregate may end up fully in registers, we do not
4630 // use the ByVal method, but pass the aggregate as array.
4631 // This is usually beneficial since we avoid forcing the
4632 // back-end to store the argument to memory.
4633 uint64_t Bits = getContext().getTypeSize(Ty);
4634 if (Bits > 0 && Bits <= 8 * GPRBits) {
4635 llvm::Type *CoerceTy;
4636
4637 // Types up to 8 bytes are passed as integer type (which will be
4638 // properly aligned in the argument save area doubleword).
4639 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004640 CoerceTy =
4641 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004642 // Larger types are passed as arrays, with the base type selected
4643 // according to the required alignment in the save area.
4644 else {
4645 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004646 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004647 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4648 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4649 }
4650
4651 return ABIArgInfo::getDirect(CoerceTy);
4652 }
4653
Ulrich Weigandb7122372014-07-21 00:48:09 +00004654 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004655 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4656 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004657 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004658 }
4659
4660 return (isPromotableTypeForABI(Ty) ?
4661 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4662}
4663
4664ABIArgInfo
4665PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4666 if (RetTy->isVoidType())
4667 return ABIArgInfo::getIgnore();
4668
Bill Schmidta3d121c2012-12-17 04:20:17 +00004669 if (RetTy->isAnyComplexType())
4670 return ABIArgInfo::getDirect();
4671
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004672 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4673 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004674 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004675 uint64_t Size = getContext().getTypeSize(RetTy);
4676 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004677 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004678 else if (Size < 128) {
4679 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4680 return ABIArgInfo::getDirect(CoerceTy);
4681 }
4682 }
4683
Ulrich Weigandb7122372014-07-21 00:48:09 +00004684 if (isAggregateTypeForABI(RetTy)) {
4685 // ELFv2 homogeneous aggregates are returned as array types.
4686 const Type *Base = nullptr;
4687 uint64_t Members = 0;
4688 if (Kind == ELFv2 &&
4689 isHomogeneousAggregate(RetTy, Base, Members)) {
4690 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4691 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4692 return ABIArgInfo::getDirect(CoerceTy);
4693 }
4694
4695 // ELFv2 small aggregates are returned in up to two registers.
4696 uint64_t Bits = getContext().getTypeSize(RetTy);
4697 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4698 if (Bits == 0)
4699 return ABIArgInfo::getIgnore();
4700
4701 llvm::Type *CoerceTy;
4702 if (Bits > GPRBits) {
4703 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004704 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004705 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004706 CoerceTy =
4707 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004708 return ABIArgInfo::getDirect(CoerceTy);
4709 }
4710
4711 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004712 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004713 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004714
4715 return (isPromotableTypeForABI(RetTy) ?
4716 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4717}
4718
Bill Schmidt25cb3492012-10-03 19:18:57 +00004719// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004720Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4721 QualType Ty) const {
4722 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4723 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004724
John McCall7f416cc2015-09-08 08:05:57 +00004725 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004726
Bill Schmidt924c4782013-01-14 17:45:36 +00004727 // If we have a complex type and the base type is smaller than 8 bytes,
4728 // the ABI calls for the real and imaginary parts to be right-adjusted
4729 // in separate doublewords. However, Clang expects us to produce a
4730 // pointer to a structure with the two parts packed tightly. So generate
4731 // loads of the real and imaginary parts relative to the va_list pointer,
4732 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004733 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4734 CharUnits EltSize = TypeInfo.first / 2;
4735 if (EltSize < SlotSize) {
4736 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4737 SlotSize * 2, SlotSize,
4738 SlotSize, /*AllowHigher*/ true);
4739
4740 Address RealAddr = Addr;
4741 Address ImagAddr = RealAddr;
4742 if (CGF.CGM.getDataLayout().isBigEndian()) {
4743 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4744 SlotSize - EltSize);
4745 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4746 2 * SlotSize - EltSize);
4747 } else {
4748 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4749 }
4750
4751 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4752 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4753 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4754 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4755 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4756
4757 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4758 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4759 /*init*/ true);
4760 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004761 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004762 }
4763
John McCall7f416cc2015-09-08 08:05:57 +00004764 // Otherwise, just use the general rule.
4765 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4766 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004767}
4768
4769static bool
4770PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4771 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004772 // This is calculated from the LLVM and GCC tables and verified
4773 // against gcc output. AFAIK all ABIs use the same encoding.
4774
4775 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4776
4777 llvm::IntegerType *i8 = CGF.Int8Ty;
4778 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4779 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4780 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4781
4782 // 0-31: r0-31, the 8-byte general-purpose registers
4783 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4784
4785 // 32-63: fp0-31, the 8-byte floating-point registers
4786 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4787
Hal Finkel84832a72016-08-30 02:38:34 +00004788 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004789 // 64: mq
4790 // 65: lr
4791 // 66: ctr
4792 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004793 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4794
4795 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004796 // 68-75 cr0-7
4797 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004798 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004799
4800 // 77-108: v0-31, the 16-byte vector registers
4801 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4802
4803 // 109: vrsave
4804 // 110: vscr
4805 // 111: spe_acc
4806 // 112: spefscr
4807 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004808 // 114: tfhar
4809 // 115: tfiar
4810 // 116: texasr
4811 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004812
4813 return false;
4814}
John McCallea8d8bb2010-03-11 00:10:12 +00004815
Bill Schmidt25cb3492012-10-03 19:18:57 +00004816bool
4817PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4818 CodeGen::CodeGenFunction &CGF,
4819 llvm::Value *Address) const {
4820
4821 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4822}
4823
4824bool
4825PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4826 llvm::Value *Address) const {
4827
4828 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4829}
4830
Chris Lattner0cf24192010-06-28 20:05:43 +00004831//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004832// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004833//===----------------------------------------------------------------------===//
4834
4835namespace {
4836
John McCall12f23522016-04-04 18:33:08 +00004837class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004838public:
4839 enum ABIKind {
4840 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004841 DarwinPCS,
4842 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004843 };
4844
4845private:
4846 ABIKind Kind;
4847
4848public:
John McCall12f23522016-04-04 18:33:08 +00004849 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4850 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004851
4852private:
4853 ABIKind getABIKind() const { return Kind; }
4854 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4855
4856 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004857 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004858 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4859 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4860 uint64_t Members) const override;
4861
Tim Northovera2ee4332014-03-29 15:09:45 +00004862 bool isIllegalVectorType(QualType Ty) const;
4863
David Blaikie1cbb9712014-11-14 19:09:44 +00004864 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004865 if (!getCXXABI().classifyReturnType(FI))
4866 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004867
Tim Northoverb047bfa2014-11-27 21:02:49 +00004868 for (auto &it : FI.arguments())
4869 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004870 }
4871
John McCall7f416cc2015-09-08 08:05:57 +00004872 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4873 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004874
John McCall7f416cc2015-09-08 08:05:57 +00004875 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4876 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004877
John McCall7f416cc2015-09-08 08:05:57 +00004878 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4879 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004880 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4881 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4882 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004883 }
John McCall12f23522016-04-04 18:33:08 +00004884
Martin Storsjo502de222017-07-13 17:59:14 +00004885 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4886 QualType Ty) const override;
4887
John McCall12f23522016-04-04 18:33:08 +00004888 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4889 ArrayRef<llvm::Type*> scalars,
4890 bool asReturnValue) const override {
4891 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4892 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004893 bool isSwiftErrorInRegister() const override {
4894 return true;
4895 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004896
4897 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4898 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004899};
4900
Tim Northover573cbee2014-05-24 12:52:07 +00004901class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004902public:
Tim Northover573cbee2014-05-24 12:52:07 +00004903 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4904 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004905
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004906 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004907 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004908 }
4909
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004910 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4911 return 31;
4912 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004913
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004914 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004915};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004916
4917class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4918public:
4919 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4920 : AArch64TargetCodeGenInfo(CGT, K) {}
4921
4922 void getDependentLibraryOption(llvm::StringRef Lib,
4923 llvm::SmallString<24> &Opt) const override {
4924 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4925 }
4926
4927 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4928 llvm::SmallString<32> &Opt) const override {
4929 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4930 }
4931};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004932}
Tim Northovera2ee4332014-03-29 15:09:45 +00004933
Tim Northoverb047bfa2014-11-27 21:02:49 +00004934ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004935 Ty = useFirstFieldIfTransparentUnion(Ty);
4936
Tim Northovera2ee4332014-03-29 15:09:45 +00004937 // Handle illegal vector types here.
4938 if (isIllegalVectorType(Ty)) {
4939 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004940 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004941 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004942 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4943 return ABIArgInfo::getDirect(ResType);
4944 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004945 if (Size <= 32) {
4946 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004947 return ABIArgInfo::getDirect(ResType);
4948 }
4949 if (Size == 64) {
4950 llvm::Type *ResType =
4951 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004952 return ABIArgInfo::getDirect(ResType);
4953 }
4954 if (Size == 128) {
4955 llvm::Type *ResType =
4956 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004957 return ABIArgInfo::getDirect(ResType);
4958 }
John McCall7f416cc2015-09-08 08:05:57 +00004959 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004960 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004961
4962 if (!isAggregateTypeForABI(Ty)) {
4963 // Treat an enum type as its underlying type.
4964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4965 Ty = EnumTy->getDecl()->getIntegerType();
4966
Tim Northovera2ee4332014-03-29 15:09:45 +00004967 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4968 ? ABIArgInfo::getExtend()
4969 : ABIArgInfo::getDirect());
4970 }
4971
4972 // Structures with either a non-trivial destructor or a non-trivial
4973 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004974 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004975 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4976 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004977 }
4978
4979 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4980 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004981 uint64_t Size = getContext().getTypeSize(Ty);
4982 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4983 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004984 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4985 return ABIArgInfo::getIgnore();
4986
Tim Northover23bcad22017-05-05 22:36:06 +00004987 // GNU C mode. The only argument that gets ignored is an empty one with size
4988 // 0.
4989 if (IsEmpty && Size == 0)
4990 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004991 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4992 }
4993
4994 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004995 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004996 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004997 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004998 return ABIArgInfo::getDirect(
4999 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005000 }
5001
5002 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005003 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005004 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5005 // same size and alignment.
5006 if (getTarget().isRenderScriptTarget()) {
5007 return coerceToIntArray(Ty, getContext(), getVMContext());
5008 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005009 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005010 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005011
Tim Northovera2ee4332014-03-29 15:09:45 +00005012 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5013 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005014 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005015 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5016 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5017 }
5018 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5019 }
5020
John McCall7f416cc2015-09-08 08:05:57 +00005021 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005022}
5023
Tim Northover573cbee2014-05-24 12:52:07 +00005024ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005025 if (RetTy->isVoidType())
5026 return ABIArgInfo::getIgnore();
5027
5028 // Large vector types should be returned via memory.
5029 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005030 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005031
5032 if (!isAggregateTypeForABI(RetTy)) {
5033 // Treat an enum type as its underlying type.
5034 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5035 RetTy = EnumTy->getDecl()->getIntegerType();
5036
Tim Northover4dab6982014-04-18 13:46:08 +00005037 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5038 ? ABIArgInfo::getExtend()
5039 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005040 }
5041
Tim Northover23bcad22017-05-05 22:36:06 +00005042 uint64_t Size = getContext().getTypeSize(RetTy);
5043 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005044 return ABIArgInfo::getIgnore();
5045
Craig Topper8a13c412014-05-21 05:09:00 +00005046 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005047 uint64_t Members = 0;
5048 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005049 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5050 return ABIArgInfo::getDirect();
5051
5052 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005053 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005054 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5055 // same size and alignment.
5056 if (getTarget().isRenderScriptTarget()) {
5057 return coerceToIntArray(RetTy, getContext(), getVMContext());
5058 }
Pete Cooper635b5092015-04-17 22:16:24 +00005059 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005060 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005061
5062 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5063 // For aggregates with 16-byte alignment, we use i128.
5064 if (Alignment < 128 && Size == 128) {
5065 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5066 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5067 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005068 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5069 }
5070
John McCall7f416cc2015-09-08 08:05:57 +00005071 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005072}
5073
Tim Northover573cbee2014-05-24 12:52:07 +00005074/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5075bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005076 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5077 // Check whether VT is legal.
5078 unsigned NumElements = VT->getNumElements();
5079 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005080 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005081 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 return true;
5083 return Size != 64 && (Size != 128 || NumElements == 1);
5084 }
5085 return false;
5086}
5087
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005088bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5089 llvm::Type *eltTy,
5090 unsigned elts) const {
5091 if (!llvm::isPowerOf2_32(elts))
5092 return false;
5093 if (totalSize.getQuantity() != 8 &&
5094 (totalSize.getQuantity() != 16 || elts == 1))
5095 return false;
5096 return true;
5097}
5098
Reid Klecknere9f6a712014-10-31 17:10:41 +00005099bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5100 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5101 // point type or a short-vector type. This is the same as the 32-bit ABI,
5102 // but with the difference that any floating-point type is allowed,
5103 // including __fp16.
5104 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5105 if (BT->isFloatingPoint())
5106 return true;
5107 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5108 unsigned VecSize = getContext().getTypeSize(VT);
5109 if (VecSize == 64 || VecSize == 128)
5110 return true;
5111 }
5112 return false;
5113}
5114
5115bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5116 uint64_t Members) const {
5117 return Members <= 4;
5118}
5119
John McCall7f416cc2015-09-08 08:05:57 +00005120Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005121 QualType Ty,
5122 CodeGenFunction &CGF) const {
5123 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005124 bool IsIndirect = AI.isIndirect();
5125
Tim Northoverb047bfa2014-11-27 21:02:49 +00005126 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5127 if (IsIndirect)
5128 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5129 else if (AI.getCoerceToType())
5130 BaseTy = AI.getCoerceToType();
5131
5132 unsigned NumRegs = 1;
5133 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5134 BaseTy = ArrTy->getElementType();
5135 NumRegs = ArrTy->getNumElements();
5136 }
5137 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5138
Tim Northovera2ee4332014-03-29 15:09:45 +00005139 // The AArch64 va_list type and handling is specified in the Procedure Call
5140 // Standard, section B.4:
5141 //
5142 // struct {
5143 // void *__stack;
5144 // void *__gr_top;
5145 // void *__vr_top;
5146 // int __gr_offs;
5147 // int __vr_offs;
5148 // };
5149
5150 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5151 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5152 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5153 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005154
John McCall7f416cc2015-09-08 08:05:57 +00005155 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5156 CharUnits TyAlign = TyInfo.second;
5157
5158 Address reg_offs_p = Address::invalid();
5159 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005160 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005161 CharUnits reg_top_offset;
5162 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005163 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005164 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005165 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005166 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5167 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005168 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5169 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005170 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005171 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005172 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005173 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005174 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005175 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5176 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005177 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5178 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005179 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005180 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005181 }
5182
5183 //=======================================
5184 // Find out where argument was passed
5185 //=======================================
5186
5187 // If reg_offs >= 0 we're already using the stack for this type of
5188 // argument. We don't want to keep updating reg_offs (in case it overflows,
5189 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5190 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005191 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005192 UsingStack = CGF.Builder.CreateICmpSGE(
5193 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5194
5195 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5196
5197 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005198 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005199 CGF.EmitBlock(MaybeRegBlock);
5200
5201 // Integer arguments may need to correct register alignment (for example a
5202 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5203 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005204 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5205 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005206
5207 reg_offs = CGF.Builder.CreateAdd(
5208 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5209 "align_regoffs");
5210 reg_offs = CGF.Builder.CreateAnd(
5211 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5212 "aligned_regoffs");
5213 }
5214
5215 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005216 // The fact that this is done unconditionally reflects the fact that
5217 // allocating an argument to the stack also uses up all the remaining
5218 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005219 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005220 NewOffset = CGF.Builder.CreateAdd(
5221 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5222 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5223
5224 // Now we're in a position to decide whether this argument really was in
5225 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005226 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005227 InRegs = CGF.Builder.CreateICmpSLE(
5228 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5229
5230 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5231
5232 //=======================================
5233 // Argument was in registers
5234 //=======================================
5235
5236 // Now we emit the code for if the argument was originally passed in
5237 // registers. First start the appropriate block:
5238 CGF.EmitBlock(InRegBlock);
5239
John McCall7f416cc2015-09-08 08:05:57 +00005240 llvm::Value *reg_top = nullptr;
5241 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5242 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005243 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005244 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5245 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5246 Address RegAddr = Address::invalid();
5247 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005248
5249 if (IsIndirect) {
5250 // If it's been passed indirectly (actually a struct), whatever we find from
5251 // stored registers or on the stack will actually be a struct **.
5252 MemTy = llvm::PointerType::getUnqual(MemTy);
5253 }
5254
Craig Topper8a13c412014-05-21 05:09:00 +00005255 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005256 uint64_t NumMembers = 0;
5257 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005258 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005259 // Homogeneous aggregates passed in registers will have their elements split
5260 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5261 // qN+1, ...). We reload and store into a temporary local variable
5262 // contiguously.
5263 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005264 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005265 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5266 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005267 Address Tmp = CGF.CreateTempAlloca(HFATy,
5268 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005269
John McCall7f416cc2015-09-08 08:05:57 +00005270 // On big-endian platforms, the value will be right-aligned in its slot.
5271 int Offset = 0;
5272 if (CGF.CGM.getDataLayout().isBigEndian() &&
5273 BaseTyInfo.first.getQuantity() < 16)
5274 Offset = 16 - BaseTyInfo.first.getQuantity();
5275
Tim Northovera2ee4332014-03-29 15:09:45 +00005276 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005277 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5278 Address LoadAddr =
5279 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5280 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5281
5282 Address StoreAddr =
5283 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005284
5285 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5286 CGF.Builder.CreateStore(Elem, StoreAddr);
5287 }
5288
John McCall7f416cc2015-09-08 08:05:57 +00005289 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005290 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005291 // Otherwise the object is contiguous in memory.
5292
5293 // It might be right-aligned in its slot.
5294 CharUnits SlotSize = BaseAddr.getAlignment();
5295 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005296 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005297 TyInfo.first < SlotSize) {
5298 CharUnits Offset = SlotSize - TyInfo.first;
5299 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005300 }
5301
John McCall7f416cc2015-09-08 08:05:57 +00005302 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005303 }
5304
5305 CGF.EmitBranch(ContBlock);
5306
5307 //=======================================
5308 // Argument was on the stack
5309 //=======================================
5310 CGF.EmitBlock(OnStackBlock);
5311
John McCall7f416cc2015-09-08 08:05:57 +00005312 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5313 CharUnits::Zero(), "stack_p");
5314 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005315
John McCall7f416cc2015-09-08 08:05:57 +00005316 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005317 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005318 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5319 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005320
John McCall7f416cc2015-09-08 08:05:57 +00005321 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005322
John McCall7f416cc2015-09-08 08:05:57 +00005323 OnStackPtr = CGF.Builder.CreateAdd(
5324 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005325 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005326 OnStackPtr = CGF.Builder.CreateAnd(
5327 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005328 "align_stack");
5329
John McCall7f416cc2015-09-08 08:05:57 +00005330 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005331 }
John McCall7f416cc2015-09-08 08:05:57 +00005332 Address OnStackAddr(OnStackPtr,
5333 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005334
John McCall7f416cc2015-09-08 08:05:57 +00005335 // All stack slots are multiples of 8 bytes.
5336 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5337 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005338 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005339 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005340 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005341 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005342
John McCall7f416cc2015-09-08 08:05:57 +00005343 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005344 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005345 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005346
5347 // Write the new value of __stack for the next call to va_arg
5348 CGF.Builder.CreateStore(NewStack, stack_p);
5349
5350 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005351 TyInfo.first < StackSlotSize) {
5352 CharUnits Offset = StackSlotSize - TyInfo.first;
5353 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005354 }
5355
John McCall7f416cc2015-09-08 08:05:57 +00005356 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005357
5358 CGF.EmitBranch(ContBlock);
5359
5360 //=======================================
5361 // Tidy up
5362 //=======================================
5363 CGF.EmitBlock(ContBlock);
5364
John McCall7f416cc2015-09-08 08:05:57 +00005365 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5366 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005367
5368 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005369 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5370 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005371
5372 return ResAddr;
5373}
5374
John McCall7f416cc2015-09-08 08:05:57 +00005375Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5376 CodeGenFunction &CGF) const {
5377 // The backend's lowering doesn't support va_arg for aggregates or
5378 // illegal vector types. Lower VAArg here for these cases and use
5379 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005380 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005381 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005382
John McCall7f416cc2015-09-08 08:05:57 +00005383 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005384
John McCall7f416cc2015-09-08 08:05:57 +00005385 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005386 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005387 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5388 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5389 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005390 }
5391
John McCall7f416cc2015-09-08 08:05:57 +00005392 // The size of the actual thing passed, which might end up just
5393 // being a pointer for indirect types.
5394 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5395
5396 // Arguments bigger than 16 bytes which aren't homogeneous
5397 // aggregates should be passed indirectly.
5398 bool IsIndirect = false;
5399 if (TyInfo.first.getQuantity() > 16) {
5400 const Type *Base = nullptr;
5401 uint64_t Members = 0;
5402 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005403 }
5404
John McCall7f416cc2015-09-08 08:05:57 +00005405 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5406 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005407}
5408
Martin Storsjo502de222017-07-13 17:59:14 +00005409Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5410 QualType Ty) const {
5411 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5412 CGF.getContext().getTypeInfoInChars(Ty),
5413 CharUnits::fromQuantity(8),
5414 /*allowHigherAlign*/ false);
5415}
5416
Tim Northovera2ee4332014-03-29 15:09:45 +00005417//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005418// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005419//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005420
5421namespace {
5422
John McCall12f23522016-04-04 18:33:08 +00005423class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005424public:
5425 enum ABIKind {
5426 APCS = 0,
5427 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005428 AAPCS_VFP = 2,
5429 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005430 };
5431
5432private:
5433 ABIKind Kind;
5434
5435public:
John McCall12f23522016-04-04 18:33:08 +00005436 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5437 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005438 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005439 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005440
John McCall3480ef22011-08-30 01:42:09 +00005441 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005442 switch (getTarget().getTriple().getEnvironment()) {
5443 case llvm::Triple::Android:
5444 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005445 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005446 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005447 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005448 case llvm::Triple::MuslEABI:
5449 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005450 return true;
5451 default:
5452 return false;
5453 }
John McCall3480ef22011-08-30 01:42:09 +00005454 }
5455
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005456 bool isEABIHF() const {
5457 switch (getTarget().getTriple().getEnvironment()) {
5458 case llvm::Triple::EABIHF:
5459 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005460 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005461 return true;
5462 default:
5463 return false;
5464 }
5465 }
5466
Daniel Dunbar020daa92009-09-12 01:00:39 +00005467 ABIKind getABIKind() const { return Kind; }
5468
Tim Northovera484bc02013-10-01 14:34:25 +00005469private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005470 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005471 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005472 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005473
Reid Klecknere9f6a712014-10-31 17:10:41 +00005474 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5475 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5476 uint64_t Members) const override;
5477
Craig Topper4f12f102014-03-12 06:41:41 +00005478 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005479
John McCall7f416cc2015-09-08 08:05:57 +00005480 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5481 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005482
5483 llvm::CallingConv::ID getLLVMDefaultCC() const;
5484 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005485 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005486
5487 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5488 ArrayRef<llvm::Type*> scalars,
5489 bool asReturnValue) const override {
5490 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5491 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005492 bool isSwiftErrorInRegister() const override {
5493 return true;
5494 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005495 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5496 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005497};
5498
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005499class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5500public:
Chris Lattner2b037972010-07-29 02:01:43 +00005501 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5502 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005503
John McCall3480ef22011-08-30 01:42:09 +00005504 const ARMABIInfo &getABIInfo() const {
5505 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5506 }
5507
Craig Topper4f12f102014-03-12 06:41:41 +00005508 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005509 return 13;
5510 }
Roman Divackyc1617352011-05-18 19:36:54 +00005511
Craig Topper4f12f102014-03-12 06:41:41 +00005512 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005513 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005514 }
5515
Roman Divackyc1617352011-05-18 19:36:54 +00005516 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005517 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005518 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005519
5520 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005521 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005522 return false;
5523 }
John McCall3480ef22011-08-30 01:42:09 +00005524
Craig Topper4f12f102014-03-12 06:41:41 +00005525 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005526 if (getABIInfo().isEABI()) return 88;
5527 return TargetCodeGenInfo::getSizeOfUnwindException();
5528 }
Tim Northovera484bc02013-10-01 14:34:25 +00005529
Eric Christopher162c91c2015-06-05 22:03:00 +00005530 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005531 CodeGen::CodeGenModule &CGM,
5532 ForDefinition_t IsForDefinition) const override {
5533 if (!IsForDefinition)
5534 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005535 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005536 if (!FD)
5537 return;
5538
5539 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5540 if (!Attr)
5541 return;
5542
5543 const char *Kind;
5544 switch (Attr->getInterrupt()) {
5545 case ARMInterruptAttr::Generic: Kind = ""; break;
5546 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5547 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5548 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5549 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5550 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5551 }
5552
5553 llvm::Function *Fn = cast<llvm::Function>(GV);
5554
5555 Fn->addFnAttr("interrupt", Kind);
5556
Tim Northover5627d392015-10-30 16:30:45 +00005557 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5558 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005559 return;
5560
5561 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5562 // however this is not necessarily true on taking any interrupt. Instruct
5563 // the backend to perform a realignment as part of the function prologue.
5564 llvm::AttrBuilder B;
5565 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005566 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005567 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005568};
5569
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005570class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005571public:
5572 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5573 : ARMTargetCodeGenInfo(CGT, K) {}
5574
Eric Christopher162c91c2015-06-05 22:03:00 +00005575 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005576 CodeGen::CodeGenModule &CGM,
5577 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005578
5579 void getDependentLibraryOption(llvm::StringRef Lib,
5580 llvm::SmallString<24> &Opt) const override {
5581 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5582 }
5583
5584 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5585 llvm::SmallString<32> &Opt) const override {
5586 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5587 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005588};
5589
Eric Christopher162c91c2015-06-05 22:03:00 +00005590void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005591 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5592 ForDefinition_t IsForDefinition) const {
5593 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5594 if (!IsForDefinition)
5595 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005596 addStackProbeSizeTargetAttribute(D, GV, CGM);
5597}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005598}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005599
Chris Lattner22326a12010-07-29 02:31:05 +00005600void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005601 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005602 FI.getReturnInfo() =
5603 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005604
Tim Northoverbc784d12015-02-24 17:22:40 +00005605 for (auto &I : FI.arguments())
5606 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005607
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005608 // Always honor user-specified calling convention.
5609 if (FI.getCallingConvention() != llvm::CallingConv::C)
5610 return;
5611
John McCall882987f2013-02-28 19:01:20 +00005612 llvm::CallingConv::ID cc = getRuntimeCC();
5613 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005614 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005615}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005616
John McCall882987f2013-02-28 19:01:20 +00005617/// Return the default calling convention that LLVM will use.
5618llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5619 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005620 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005621 return llvm::CallingConv::ARM_AAPCS_VFP;
5622 else if (isEABI())
5623 return llvm::CallingConv::ARM_AAPCS;
5624 else
5625 return llvm::CallingConv::ARM_APCS;
5626}
5627
5628/// Return the calling convention that our ABI would like us to use
5629/// as the C calling convention.
5630llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005631 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005632 case APCS: return llvm::CallingConv::ARM_APCS;
5633 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5634 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005635 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005636 }
John McCall882987f2013-02-28 19:01:20 +00005637 llvm_unreachable("bad ABI kind");
5638}
5639
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005640void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005641 assert(getRuntimeCC() == llvm::CallingConv::C);
5642
5643 // Don't muddy up the IR with a ton of explicit annotations if
5644 // they'd just match what LLVM will infer from the triple.
5645 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5646 if (abiCC != getLLVMDefaultCC())
5647 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005648
Tim Northover5627d392015-10-30 16:30:45 +00005649 // AAPCS apparently requires runtime support functions to be soft-float, but
5650 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5651 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005652
5653 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5654 // AEABI-complying FP helper functions to use the base AAPCS.
5655 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5656 // support functions emitted by clang such as the _Complex helpers follow the
5657 // abiCC.
5658 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005659 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005660}
5661
Tim Northoverbc784d12015-02-24 17:22:40 +00005662ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5663 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005664 // 6.1.2.1 The following argument types are VFP CPRCs:
5665 // A single-precision floating-point type (including promoted
5666 // half-precision types); A double-precision floating-point type;
5667 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5668 // with a Base Type of a single- or double-precision floating-point type,
5669 // 64-bit containerized vectors or 128-bit containerized vectors with one
5670 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005671 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005672
Reid Klecknerb1be6832014-11-15 01:41:41 +00005673 Ty = useFirstFieldIfTransparentUnion(Ty);
5674
Manman Renfef9e312012-10-16 19:18:39 +00005675 // Handle illegal vector types here.
5676 if (isIllegalVectorType(Ty)) {
5677 uint64_t Size = getContext().getTypeSize(Ty);
5678 if (Size <= 32) {
5679 llvm::Type *ResType =
5680 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005681 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005682 }
5683 if (Size == 64) {
5684 llvm::Type *ResType = llvm::VectorType::get(
5685 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005686 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005687 }
5688 if (Size == 128) {
5689 llvm::Type *ResType = llvm::VectorType::get(
5690 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005691 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005692 }
John McCall7f416cc2015-09-08 08:05:57 +00005693 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005694 }
5695
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005696 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5697 // unspecified. This is not done for OpenCL as it handles the half type
5698 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005699 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005700 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5701 llvm::Type::getFloatTy(getVMContext()) :
5702 llvm::Type::getInt32Ty(getVMContext());
5703 return ABIArgInfo::getDirect(ResType);
5704 }
5705
John McCalla1dee5302010-08-22 10:59:02 +00005706 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005707 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005708 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005709 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005710 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005711
Tim Northover5a1558e2014-11-07 22:30:50 +00005712 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5713 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005714 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005715
Oliver Stannard405bded2014-02-11 09:25:50 +00005716 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005717 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005718 }
Tim Northover1060eae2013-06-21 22:49:34 +00005719
Daniel Dunbar09d33622009-09-14 21:54:03 +00005720 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005721 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005722 return ABIArgInfo::getIgnore();
5723
Tim Northover5a1558e2014-11-07 22:30:50 +00005724 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005725 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5726 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005727 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005728 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005729 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005730 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005731 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005732 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005733 }
Tim Northover5627d392015-10-30 16:30:45 +00005734 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5735 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5736 // this convention even for a variadic function: the backend will use GPRs
5737 // if needed.
5738 const Type *Base = nullptr;
5739 uint64_t Members = 0;
5740 if (isHomogeneousAggregate(Ty, Base, Members)) {
5741 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5742 llvm::Type *Ty =
5743 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5744 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5745 }
5746 }
5747
5748 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5749 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5750 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5751 // bigger than 128-bits, they get placed in space allocated by the caller,
5752 // and a pointer is passed.
5753 return ABIArgInfo::getIndirect(
5754 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005755 }
5756
Manman Ren6c30e132012-08-13 21:23:55 +00005757 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005758 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5759 // most 8-byte. We realign the indirect argument if type alignment is bigger
5760 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005761 uint64_t ABIAlign = 4;
5762 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5763 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005764 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005765 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005766
Manman Ren8cd99812012-11-06 04:58:01 +00005767 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005768 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005769 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5770 /*ByVal=*/true,
5771 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005772 }
5773
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005774 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5775 // same size and alignment.
5776 if (getTarget().isRenderScriptTarget()) {
5777 return coerceToIntArray(Ty, getContext(), getVMContext());
5778 }
5779
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005780 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005781 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005782 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005783 // FIXME: Try to match the types of the arguments more accurately where
5784 // we can.
5785 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005786 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5787 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005788 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005789 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5790 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005791 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005792
Tim Northover5a1558e2014-11-07 22:30:50 +00005793 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005794}
5795
Chris Lattner458b2aa2010-07-29 02:16:43 +00005796static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005797 llvm::LLVMContext &VMContext) {
5798 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5799 // is called integer-like if its size is less than or equal to one word, and
5800 // the offset of each of its addressable sub-fields is zero.
5801
5802 uint64_t Size = Context.getTypeSize(Ty);
5803
5804 // Check that the type fits in a word.
5805 if (Size > 32)
5806 return false;
5807
5808 // FIXME: Handle vector types!
5809 if (Ty->isVectorType())
5810 return false;
5811
Daniel Dunbard53bac72009-09-14 02:20:34 +00005812 // Float types are never treated as "integer like".
5813 if (Ty->isRealFloatingType())
5814 return false;
5815
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005816 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005817 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005818 return true;
5819
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005820 // Small complex integer types are "integer like".
5821 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5822 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005823
5824 // Single element and zero sized arrays should be allowed, by the definition
5825 // above, but they are not.
5826
5827 // Otherwise, it must be a record type.
5828 const RecordType *RT = Ty->getAs<RecordType>();
5829 if (!RT) return false;
5830
5831 // Ignore records with flexible arrays.
5832 const RecordDecl *RD = RT->getDecl();
5833 if (RD->hasFlexibleArrayMember())
5834 return false;
5835
5836 // Check that all sub-fields are at offset 0, and are themselves "integer
5837 // like".
5838 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5839
5840 bool HadField = false;
5841 unsigned idx = 0;
5842 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5843 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005844 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005845
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005846 // Bit-fields are not addressable, we only need to verify they are "integer
5847 // like". We still have to disallow a subsequent non-bitfield, for example:
5848 // struct { int : 0; int x }
5849 // is non-integer like according to gcc.
5850 if (FD->isBitField()) {
5851 if (!RD->isUnion())
5852 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005853
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005854 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5855 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005856
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005857 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005858 }
5859
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005860 // Check if this field is at offset 0.
5861 if (Layout.getFieldOffset(idx) != 0)
5862 return false;
5863
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005864 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5865 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005866
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005867 // Only allow at most one field in a structure. This doesn't match the
5868 // wording above, but follows gcc in situations with a field following an
5869 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005870 if (!RD->isUnion()) {
5871 if (HadField)
5872 return false;
5873
5874 HadField = true;
5875 }
5876 }
5877
5878 return true;
5879}
5880
Oliver Stannard405bded2014-02-11 09:25:50 +00005881ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5882 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005883 bool IsEffectivelyAAPCS_VFP =
5884 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005885
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005886 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005887 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005888
Daniel Dunbar19964db2010-09-23 01:54:32 +00005889 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005890 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005891 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005892 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005893
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005894 // __fp16 gets returned as if it were an int or float, but with the top 16
5895 // bits unspecified. This is not done for OpenCL as it handles the half type
5896 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005897 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005898 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5899 llvm::Type::getFloatTy(getVMContext()) :
5900 llvm::Type::getInt32Ty(getVMContext());
5901 return ABIArgInfo::getDirect(ResType);
5902 }
5903
John McCalla1dee5302010-08-22 10:59:02 +00005904 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005905 // Treat an enum type as its underlying type.
5906 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5907 RetTy = EnumTy->getDecl()->getIntegerType();
5908
Tim Northover5a1558e2014-11-07 22:30:50 +00005909 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5910 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005911 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005912
5913 // Are we following APCS?
5914 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005915 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005916 return ABIArgInfo::getIgnore();
5917
Daniel Dunbareedf1512010-02-01 23:31:19 +00005918 // Complex types are all returned as packed integers.
5919 //
5920 // FIXME: Consider using 2 x vector types if the back end handles them
5921 // correctly.
5922 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005923 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5924 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005925
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005926 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005927 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005928 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005929 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005930 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005931 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005932 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005933 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5934 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005935 }
5936
5937 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005938 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005939 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005940
5941 // Otherwise this is an AAPCS variant.
5942
Chris Lattner458b2aa2010-07-29 02:16:43 +00005943 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005944 return ABIArgInfo::getIgnore();
5945
Bob Wilson1d9269a2011-11-02 04:51:36 +00005946 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005947 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005948 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005949 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005950 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005951 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005952 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005953 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005954 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005955 }
5956
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005957 // Aggregates <= 4 bytes are returned in r0; other aggregates
5958 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005959 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005960 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005961 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5962 // same size and alignment.
5963 if (getTarget().isRenderScriptTarget()) {
5964 return coerceToIntArray(RetTy, getContext(), getVMContext());
5965 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005966 if (getDataLayout().isBigEndian())
5967 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005968 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005969
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005970 // Return in the smallest viable integer type.
5971 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005972 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005973 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005974 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5975 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005976 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5977 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5978 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005979 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005980 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005981 }
5982
John McCall7f416cc2015-09-08 08:05:57 +00005983 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005984}
5985
Manman Renfef9e312012-10-16 19:18:39 +00005986/// isIllegalVector - check whether Ty is an illegal vector type.
5987bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005988 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5989 if (isAndroid()) {
5990 // Android shipped using Clang 3.1, which supported a slightly different
5991 // vector ABI. The primary differences were that 3-element vector types
5992 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5993 // accepts that legacy behavior for Android only.
5994 // Check whether VT is legal.
5995 unsigned NumElements = VT->getNumElements();
5996 // NumElements should be power of 2 or equal to 3.
5997 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5998 return true;
5999 } else {
6000 // Check whether VT is legal.
6001 unsigned NumElements = VT->getNumElements();
6002 uint64_t Size = getContext().getTypeSize(VT);
6003 // NumElements should be power of 2.
6004 if (!llvm::isPowerOf2_32(NumElements))
6005 return true;
6006 // Size should be greater than 32 bits.
6007 return Size <= 32;
6008 }
Manman Renfef9e312012-10-16 19:18:39 +00006009 }
6010 return false;
6011}
6012
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006013bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6014 llvm::Type *eltTy,
6015 unsigned numElts) const {
6016 if (!llvm::isPowerOf2_32(numElts))
6017 return false;
6018 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6019 if (size > 64)
6020 return false;
6021 if (vectorSize.getQuantity() != 8 &&
6022 (vectorSize.getQuantity() != 16 || numElts == 1))
6023 return false;
6024 return true;
6025}
6026
Reid Klecknere9f6a712014-10-31 17:10:41 +00006027bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6028 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6029 // double, or 64-bit or 128-bit vectors.
6030 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6031 if (BT->getKind() == BuiltinType::Float ||
6032 BT->getKind() == BuiltinType::Double ||
6033 BT->getKind() == BuiltinType::LongDouble)
6034 return true;
6035 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6036 unsigned VecSize = getContext().getTypeSize(VT);
6037 if (VecSize == 64 || VecSize == 128)
6038 return true;
6039 }
6040 return false;
6041}
6042
6043bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6044 uint64_t Members) const {
6045 return Members <= 4;
6046}
6047
John McCall7f416cc2015-09-08 08:05:57 +00006048Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6049 QualType Ty) const {
6050 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006051
John McCall7f416cc2015-09-08 08:05:57 +00006052 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006053 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006054 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6055 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6056 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006057 }
6058
John McCall7f416cc2015-09-08 08:05:57 +00006059 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6060 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006061
John McCall7f416cc2015-09-08 08:05:57 +00006062 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6063 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006064 const Type *Base = nullptr;
6065 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006066 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6067 IsIndirect = true;
6068
Tim Northover5627d392015-10-30 16:30:45 +00006069 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6070 // allocated by the caller.
6071 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6072 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6073 !isHomogeneousAggregate(Ty, Base, Members)) {
6074 IsIndirect = true;
6075
John McCall7f416cc2015-09-08 08:05:57 +00006076 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006077 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6078 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006079 // Our callers should be prepared to handle an under-aligned address.
6080 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6081 getABIKind() == ARMABIInfo::AAPCS) {
6082 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6083 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006084 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6085 // ARMv7k allows type alignment up to 16 bytes.
6086 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6087 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006088 } else {
6089 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006090 }
John McCall7f416cc2015-09-08 08:05:57 +00006091 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006092
John McCall7f416cc2015-09-08 08:05:57 +00006093 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6094 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006095}
6096
Chris Lattner0cf24192010-06-28 20:05:43 +00006097//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006098// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006099//===----------------------------------------------------------------------===//
6100
6101namespace {
6102
Justin Holewinski83e96682012-05-24 17:43:12 +00006103class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006104public:
Justin Holewinski36837432013-03-30 14:38:24 +00006105 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006106
6107 ABIArgInfo classifyReturnType(QualType RetTy) const;
6108 ABIArgInfo classifyArgumentType(QualType Ty) const;
6109
Craig Topper4f12f102014-03-12 06:41:41 +00006110 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006111 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6112 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006113};
6114
Justin Holewinski83e96682012-05-24 17:43:12 +00006115class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006116public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006117 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6118 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006119
Eric Christopher162c91c2015-06-05 22:03:00 +00006120 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006121 CodeGen::CodeGenModule &M,
6122 ForDefinition_t IsForDefinition) const override;
6123
Justin Holewinski36837432013-03-30 14:38:24 +00006124private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006125 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6126 // resulting MDNode to the nvvm.annotations MDNode.
6127 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006128};
6129
Justin Holewinski83e96682012-05-24 17:43:12 +00006130ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006131 if (RetTy->isVoidType())
6132 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006133
6134 // note: this is different from default ABI
6135 if (!RetTy->isScalarType())
6136 return ABIArgInfo::getDirect();
6137
6138 // Treat an enum type as its underlying type.
6139 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6140 RetTy = EnumTy->getDecl()->getIntegerType();
6141
6142 return (RetTy->isPromotableIntegerType() ?
6143 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006144}
6145
Justin Holewinski83e96682012-05-24 17:43:12 +00006146ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006147 // Treat an enum type as its underlying type.
6148 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6149 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006150
Eli Bendersky95338a02014-10-29 13:43:21 +00006151 // Return aggregates type as indirect by value
6152 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006153 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006154
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006155 return (Ty->isPromotableIntegerType() ?
6156 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006157}
6158
Justin Holewinski83e96682012-05-24 17:43:12 +00006159void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006160 if (!getCXXABI().classifyReturnType(FI))
6161 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006162 for (auto &I : FI.arguments())
6163 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006164
6165 // Always honor user-specified calling convention.
6166 if (FI.getCallingConvention() != llvm::CallingConv::C)
6167 return;
6168
John McCall882987f2013-02-28 19:01:20 +00006169 FI.setEffectiveCallingConvention(getRuntimeCC());
6170}
6171
John McCall7f416cc2015-09-08 08:05:57 +00006172Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6173 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006174 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006175}
6176
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006177void NVPTXTargetCodeGenInfo::setTargetAttributes(
6178 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6179 ForDefinition_t IsForDefinition) const {
6180 if (!IsForDefinition)
6181 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006182 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006183 if (!FD) return;
6184
6185 llvm::Function *F = cast<llvm::Function>(GV);
6186
6187 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006188 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006189 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006190 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006191 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006192 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006193 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6194 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006195 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006196 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006197 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006198 }
Justin Holewinski38031972011-10-05 17:58:44 +00006199
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006200 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006201 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006202 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006203 // __global__ functions cannot be called from the device, we do not
6204 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006205 if (FD->hasAttr<CUDAGlobalAttr>()) {
6206 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6207 addNVVMMetadata(F, "kernel", 1);
6208 }
Artem Belevich7093e402015-04-21 22:55:54 +00006209 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006210 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006211 llvm::APSInt MaxThreads(32);
6212 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6213 if (MaxThreads > 0)
6214 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6215
6216 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6217 // not specified in __launch_bounds__ or if the user specified a 0 value,
6218 // we don't have to add a PTX directive.
6219 if (Attr->getMinBlocks()) {
6220 llvm::APSInt MinBlocks(32);
6221 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6222 if (MinBlocks > 0)
6223 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6224 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006225 }
6226 }
Justin Holewinski38031972011-10-05 17:58:44 +00006227 }
6228}
6229
Eli Benderskye06a2c42014-04-15 16:57:05 +00006230void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6231 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006232 llvm::Module *M = F->getParent();
6233 llvm::LLVMContext &Ctx = M->getContext();
6234
6235 // Get "nvvm.annotations" metadata node
6236 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6237
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006238 llvm::Metadata *MDVals[] = {
6239 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6240 llvm::ConstantAsMetadata::get(
6241 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006242 // Append metadata to nvvm.annotations
6243 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6244}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006245}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006246
6247//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006248// SystemZ ABI Implementation
6249//===----------------------------------------------------------------------===//
6250
6251namespace {
6252
Bryan Chane3f1ed52016-04-28 13:56:43 +00006253class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006254 bool HasVector;
6255
Ulrich Weigand47445072013-05-06 16:26:41 +00006256public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006257 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006258 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006259
6260 bool isPromotableIntegerType(QualType Ty) const;
6261 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006262 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006263 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006264 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006265
6266 ABIArgInfo classifyReturnType(QualType RetTy) const;
6267 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6268
Craig Topper4f12f102014-03-12 06:41:41 +00006269 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006270 if (!getCXXABI().classifyReturnType(FI))
6271 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006272 for (auto &I : FI.arguments())
6273 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006274 }
6275
John McCall7f416cc2015-09-08 08:05:57 +00006276 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6277 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006278
6279 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6280 ArrayRef<llvm::Type*> scalars,
6281 bool asReturnValue) const override {
6282 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6283 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006284 bool isSwiftErrorInRegister() const override {
6285 return true;
6286 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006287};
6288
6289class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6290public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006291 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6292 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006293};
6294
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006295}
Ulrich Weigand47445072013-05-06 16:26:41 +00006296
6297bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6298 // Treat an enum type as its underlying type.
6299 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6300 Ty = EnumTy->getDecl()->getIntegerType();
6301
6302 // Promotable integer types are required to be promoted by the ABI.
6303 if (Ty->isPromotableIntegerType())
6304 return true;
6305
6306 // 32-bit values must also be promoted.
6307 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6308 switch (BT->getKind()) {
6309 case BuiltinType::Int:
6310 case BuiltinType::UInt:
6311 return true;
6312 default:
6313 return false;
6314 }
6315 return false;
6316}
6317
6318bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006319 return (Ty->isAnyComplexType() ||
6320 Ty->isVectorType() ||
6321 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006322}
6323
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006324bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6325 return (HasVector &&
6326 Ty->isVectorType() &&
6327 getContext().getTypeSize(Ty) <= 128);
6328}
6329
Ulrich Weigand47445072013-05-06 16:26:41 +00006330bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6331 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6332 switch (BT->getKind()) {
6333 case BuiltinType::Float:
6334 case BuiltinType::Double:
6335 return true;
6336 default:
6337 return false;
6338 }
6339
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006340 return false;
6341}
6342
6343QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006344 if (const RecordType *RT = Ty->getAsStructureType()) {
6345 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006346 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006347
6348 // If this is a C++ record, check the bases first.
6349 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006350 for (const auto &I : CXXRD->bases()) {
6351 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006352
6353 // Empty bases don't affect things either way.
6354 if (isEmptyRecord(getContext(), Base, true))
6355 continue;
6356
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006357 if (!Found.isNull())
6358 return Ty;
6359 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006360 }
6361
6362 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006363 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006364 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006365 // Unlike isSingleElementStruct(), empty structure and array fields
6366 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006367 if (getContext().getLangOpts().CPlusPlus &&
6368 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6369 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006370
6371 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006372 // Nested structures still do though.
6373 if (!Found.isNull())
6374 return Ty;
6375 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006376 }
6377
6378 // Unlike isSingleElementStruct(), trailing padding is allowed.
6379 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006380 if (!Found.isNull())
6381 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006382 }
6383
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006384 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006385}
6386
John McCall7f416cc2015-09-08 08:05:57 +00006387Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6388 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006389 // Assume that va_list type is correct; should be pointer to LLVM type:
6390 // struct {
6391 // i64 __gpr;
6392 // i64 __fpr;
6393 // i8 *__overflow_arg_area;
6394 // i8 *__reg_save_area;
6395 // };
6396
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006397 // Every non-vector argument occupies 8 bytes and is passed by preference
6398 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6399 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006400 Ty = getContext().getCanonicalType(Ty);
6401 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006402 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006403 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006404 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006405 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006406 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006407 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006408 CharUnits UnpaddedSize;
6409 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006410 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006411 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6412 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006413 } else {
6414 if (AI.getCoerceToType())
6415 ArgTy = AI.getCoerceToType();
6416 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006417 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006418 UnpaddedSize = TyInfo.first;
6419 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006420 }
John McCall7f416cc2015-09-08 08:05:57 +00006421 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6422 if (IsVector && UnpaddedSize > PaddedSize)
6423 PaddedSize = CharUnits::fromQuantity(16);
6424 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006425
John McCall7f416cc2015-09-08 08:05:57 +00006426 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006427
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006428 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006429 llvm::Value *PaddedSizeV =
6430 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006431
6432 if (IsVector) {
6433 // Work out the address of a vector argument on the stack.
6434 // Vector arguments are always passed in the high bits of a
6435 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006436 Address OverflowArgAreaPtr =
6437 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006438 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006439 Address OverflowArgArea =
6440 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6441 TyInfo.second);
6442 Address MemAddr =
6443 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006444
6445 // Update overflow_arg_area_ptr pointer
6446 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006447 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6448 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006449 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6450
6451 return MemAddr;
6452 }
6453
John McCall7f416cc2015-09-08 08:05:57 +00006454 assert(PaddedSize.getQuantity() == 8);
6455
6456 unsigned MaxRegs, RegCountField, RegSaveIndex;
6457 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006458 if (InFPRs) {
6459 MaxRegs = 4; // Maximum of 4 FPR arguments
6460 RegCountField = 1; // __fpr
6461 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006462 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006463 } else {
6464 MaxRegs = 5; // Maximum of 5 GPR arguments
6465 RegCountField = 0; // __gpr
6466 RegSaveIndex = 2; // save offset for r2
6467 RegPadding = Padding; // values are passed in the low bits of a GPR
6468 }
6469
John McCall7f416cc2015-09-08 08:05:57 +00006470 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6471 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6472 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006473 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006474 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6475 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006476 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006477
6478 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6479 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6480 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6481 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6482
6483 // Emit code to load the value if it was passed in registers.
6484 CGF.EmitBlock(InRegBlock);
6485
6486 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006487 llvm::Value *ScaledRegCount =
6488 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6489 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006490 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6491 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006492 llvm::Value *RegOffset =
6493 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006494 Address RegSaveAreaPtr =
6495 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6496 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006497 llvm::Value *RegSaveArea =
6498 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006499 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6500 "raw_reg_addr"),
6501 PaddedSize);
6502 Address RegAddr =
6503 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006504
6505 // Update the register count
6506 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6507 llvm::Value *NewRegCount =
6508 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6509 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6510 CGF.EmitBranch(ContBlock);
6511
6512 // Emit code to load the value if it was passed in memory.
6513 CGF.EmitBlock(InMemBlock);
6514
6515 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006516 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6517 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6518 Address OverflowArgArea =
6519 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6520 PaddedSize);
6521 Address RawMemAddr =
6522 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6523 Address MemAddr =
6524 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006525
6526 // Update overflow_arg_area_ptr pointer
6527 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006528 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6529 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006530 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6531 CGF.EmitBranch(ContBlock);
6532
6533 // Return the appropriate result.
6534 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006535 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6536 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006537
6538 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006539 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6540 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006541
6542 return ResAddr;
6543}
6544
Ulrich Weigand47445072013-05-06 16:26:41 +00006545ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6546 if (RetTy->isVoidType())
6547 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006548 if (isVectorArgumentType(RetTy))
6549 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006550 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006551 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006552 return (isPromotableIntegerType(RetTy) ?
6553 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6554}
6555
6556ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6557 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006558 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006559 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006560
6561 // Integers and enums are extended to full register width.
6562 if (isPromotableIntegerType(Ty))
6563 return ABIArgInfo::getExtend();
6564
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006565 // Handle vector types and vector-like structure types. Note that
6566 // as opposed to float-like structure types, we do not allow any
6567 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006568 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006569 QualType SingleElementTy = GetSingleElementType(Ty);
6570 if (isVectorArgumentType(SingleElementTy) &&
6571 getContext().getTypeSize(SingleElementTy) == Size)
6572 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6573
6574 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006575 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006576 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006577
6578 // Handle small structures.
6579 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6580 // Structures with flexible arrays have variable length, so really
6581 // fail the size test above.
6582 const RecordDecl *RD = RT->getDecl();
6583 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006584 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006585
6586 // The structure is passed as an unextended integer, a float, or a double.
6587 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006588 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006589 assert(Size == 32 || Size == 64);
6590 if (Size == 32)
6591 PassTy = llvm::Type::getFloatTy(getVMContext());
6592 else
6593 PassTy = llvm::Type::getDoubleTy(getVMContext());
6594 } else
6595 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6596 return ABIArgInfo::getDirect(PassTy);
6597 }
6598
6599 // Non-structure compounds are passed indirectly.
6600 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006601 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006602
Craig Topper8a13c412014-05-21 05:09:00 +00006603 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006604}
6605
6606//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006607// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006608//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006609
6610namespace {
6611
6612class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6613public:
Chris Lattner2b037972010-07-29 02:01:43 +00006614 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6615 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006616 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006617 CodeGen::CodeGenModule &M,
6618 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006619};
6620
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006621}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006622
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006623void MSP430TargetCodeGenInfo::setTargetAttributes(
6624 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6625 ForDefinition_t IsForDefinition) const {
6626 if (!IsForDefinition)
6627 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006628 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006629 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6630 // Handle 'interrupt' attribute:
6631 llvm::Function *F = cast<llvm::Function>(GV);
6632
6633 // Step 1: Set ISR calling convention.
6634 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6635
6636 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006637 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006638
6639 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006640 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006641 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6642 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006643 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006644 }
6645}
6646
Chris Lattner0cf24192010-06-28 20:05:43 +00006647//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006648// MIPS ABI Implementation. This works for both little-endian and
6649// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006650//===----------------------------------------------------------------------===//
6651
John McCall943fae92010-05-27 06:19:26 +00006652namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006653class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006654 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006655 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6656 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006657 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006658 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006659 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006660 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006661public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006662 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006663 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006664 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006665
6666 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006667 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006668 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006669 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6670 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006671 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006672};
6673
John McCall943fae92010-05-27 06:19:26 +00006674class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006675 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006676public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006677 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6678 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006679 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006680
Craig Topper4f12f102014-03-12 06:41:41 +00006681 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006682 return 29;
6683 }
6684
Eric Christopher162c91c2015-06-05 22:03:00 +00006685 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006686 CodeGen::CodeGenModule &CGM,
6687 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006688 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006689 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006690 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006691
6692 if (FD->hasAttr<MipsLongCallAttr>())
6693 Fn->addFnAttr("long-call");
6694 else if (FD->hasAttr<MipsShortCallAttr>())
6695 Fn->addFnAttr("short-call");
6696
6697 // Other attributes do not have a meaning for declarations.
6698 if (!IsForDefinition)
6699 return;
6700
Reed Kotler3d5966f2013-03-13 20:40:30 +00006701 if (FD->hasAttr<Mips16Attr>()) {
6702 Fn->addFnAttr("mips16");
6703 }
6704 else if (FD->hasAttr<NoMips16Attr>()) {
6705 Fn->addFnAttr("nomips16");
6706 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006707
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006708 if (FD->hasAttr<MicroMipsAttr>())
6709 Fn->addFnAttr("micromips");
6710 else if (FD->hasAttr<NoMicroMipsAttr>())
6711 Fn->addFnAttr("nomicromips");
6712
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006713 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6714 if (!Attr)
6715 return;
6716
6717 const char *Kind;
6718 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006719 case MipsInterruptAttr::eic: Kind = "eic"; break;
6720 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6721 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6722 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6723 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6724 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6725 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6726 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6727 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6728 }
6729
6730 Fn->addFnAttr("interrupt", Kind);
6731
Reed Kotler373feca2013-01-16 17:10:28 +00006732 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006733
John McCall943fae92010-05-27 06:19:26 +00006734 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006735 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006736
Craig Topper4f12f102014-03-12 06:41:41 +00006737 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006738 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006739 }
John McCall943fae92010-05-27 06:19:26 +00006740};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006741}
John McCall943fae92010-05-27 06:19:26 +00006742
Eric Christopher7565e0d2015-05-29 23:09:49 +00006743void MipsABIInfo::CoerceToIntArgs(
6744 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006745 llvm::IntegerType *IntTy =
6746 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006747
6748 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6749 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6750 ArgList.push_back(IntTy);
6751
6752 // If necessary, add one more integer type to ArgList.
6753 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6754
6755 if (R)
6756 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006757}
6758
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006759// In N32/64, an aligned double precision floating point field is passed in
6760// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006761llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006762 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6763
6764 if (IsO32) {
6765 CoerceToIntArgs(TySize, ArgList);
6766 return llvm::StructType::get(getVMContext(), ArgList);
6767 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006768
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006769 if (Ty->isComplexType())
6770 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006771
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006772 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006773
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006774 // Unions/vectors are passed in integer registers.
6775 if (!RT || !RT->isStructureOrClassType()) {
6776 CoerceToIntArgs(TySize, ArgList);
6777 return llvm::StructType::get(getVMContext(), ArgList);
6778 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006779
6780 const RecordDecl *RD = RT->getDecl();
6781 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006782 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006783
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006784 uint64_t LastOffset = 0;
6785 unsigned idx = 0;
6786 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6787
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006788 // Iterate over fields in the struct/class and check if there are any aligned
6789 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006790 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6791 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006792 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006793 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6794
6795 if (!BT || BT->getKind() != BuiltinType::Double)
6796 continue;
6797
6798 uint64_t Offset = Layout.getFieldOffset(idx);
6799 if (Offset % 64) // Ignore doubles that are not aligned.
6800 continue;
6801
6802 // Add ((Offset - LastOffset) / 64) args of type i64.
6803 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6804 ArgList.push_back(I64);
6805
6806 // Add double type.
6807 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6808 LastOffset = Offset + 64;
6809 }
6810
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006811 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6812 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006813
6814 return llvm::StructType::get(getVMContext(), ArgList);
6815}
6816
Akira Hatanakaddd66342013-10-29 18:41:15 +00006817llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6818 uint64_t Offset) const {
6819 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006820 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006821
Akira Hatanakaddd66342013-10-29 18:41:15 +00006822 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006823}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006824
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006825ABIArgInfo
6826MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006827 Ty = useFirstFieldIfTransparentUnion(Ty);
6828
Akira Hatanaka1632af62012-01-09 19:31:25 +00006829 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006830 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006831 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006832
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006833 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6834 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006835 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6836 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006837
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006838 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006839 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006840 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006841 return ABIArgInfo::getIgnore();
6842
Mark Lacey3825e832013-10-06 01:33:34 +00006843 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006844 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006845 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006846 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006847
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006848 // If we have reached here, aggregates are passed directly by coercing to
6849 // another structure type. Padding is inserted if the offset of the
6850 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006851 ABIArgInfo ArgInfo =
6852 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6853 getPaddingType(OrigOffset, CurrOffset));
6854 ArgInfo.setInReg(true);
6855 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006856 }
6857
6858 // Treat an enum type as its underlying type.
6859 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6860 Ty = EnumTy->getDecl()->getIntegerType();
6861
Daniel Sanders5b445b32014-10-24 14:42:42 +00006862 // All integral types are promoted to the GPR width.
6863 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006864 return ABIArgInfo::getExtend();
6865
Akira Hatanakaddd66342013-10-29 18:41:15 +00006866 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006867 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006868}
6869
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006870llvm::Type*
6871MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006872 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006873 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006874
Akira Hatanakab6f74432012-02-09 18:49:26 +00006875 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006876 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006877 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6878 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006879
Akira Hatanakab6f74432012-02-09 18:49:26 +00006880 // N32/64 returns struct/classes in floating point registers if the
6881 // following conditions are met:
6882 // 1. The size of the struct/class is no larger than 128-bit.
6883 // 2. The struct/class has one or two fields all of which are floating
6884 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006885 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006886 //
6887 // Any other composite results are returned in integer registers.
6888 //
6889 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6890 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6891 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006892 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006893
Akira Hatanakab6f74432012-02-09 18:49:26 +00006894 if (!BT || !BT->isFloatingPoint())
6895 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006896
David Blaikie2d7c57e2012-04-30 02:36:29 +00006897 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006898 }
6899
6900 if (b == e)
6901 return llvm::StructType::get(getVMContext(), RTList,
6902 RD->hasAttr<PackedAttr>());
6903
6904 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006905 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006906 }
6907
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006908 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006909 return llvm::StructType::get(getVMContext(), RTList);
6910}
6911
Akira Hatanakab579fe52011-06-02 00:09:17 +00006912ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006913 uint64_t Size = getContext().getTypeSize(RetTy);
6914
Daniel Sandersed39f582014-09-04 13:28:14 +00006915 if (RetTy->isVoidType())
6916 return ABIArgInfo::getIgnore();
6917
6918 // O32 doesn't treat zero-sized structs differently from other structs.
6919 // However, N32/N64 ignores zero sized return values.
6920 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006921 return ABIArgInfo::getIgnore();
6922
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006923 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006924 if (Size <= 128) {
6925 if (RetTy->isAnyComplexType())
6926 return ABIArgInfo::getDirect();
6927
Daniel Sanderse5018b62014-09-04 15:05:39 +00006928 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006929 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006930 if (!IsO32 ||
6931 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6932 ABIArgInfo ArgInfo =
6933 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6934 ArgInfo.setInReg(true);
6935 return ArgInfo;
6936 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006937 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006938
John McCall7f416cc2015-09-08 08:05:57 +00006939 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006940 }
6941
6942 // Treat an enum type as its underlying type.
6943 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6944 RetTy = EnumTy->getDecl()->getIntegerType();
6945
6946 return (RetTy->isPromotableIntegerType() ?
6947 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6948}
6949
6950void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006951 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006952 if (!getCXXABI().classifyReturnType(FI))
6953 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006954
Eric Christopher7565e0d2015-05-29 23:09:49 +00006955 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006956 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006957
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006958 for (auto &I : FI.arguments())
6959 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006960}
6961
John McCall7f416cc2015-09-08 08:05:57 +00006962Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6963 QualType OrigTy) const {
6964 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006965
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006966 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6967 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006968 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006969 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006970 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006971 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006972 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006973 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006974 DidPromote = true;
6975 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6976 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006977 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006978
John McCall7f416cc2015-09-08 08:05:57 +00006979 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006980
John McCall7f416cc2015-09-08 08:05:57 +00006981 // The alignment of things in the argument area is never larger than
6982 // StackAlignInBytes.
6983 TyInfo.second =
6984 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6985
6986 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6987 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6988
6989 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6990 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6991
6992
6993 // If there was a promotion, "unpromote" into a temporary.
6994 // TODO: can we just use a pointer into a subset of the original slot?
6995 if (DidPromote) {
6996 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6997 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6998
6999 // Truncate down to the right width.
7000 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7001 : CGF.IntPtrTy);
7002 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7003 if (OrigTy->isPointerType())
7004 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7005
7006 CGF.Builder.CreateStore(V, Temp);
7007 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007008 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007009
John McCall7f416cc2015-09-08 08:05:57 +00007010 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007011}
7012
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007013bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
7014 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007015
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007016 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7017 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7018 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007019
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007020 return false;
7021}
7022
John McCall943fae92010-05-27 06:19:26 +00007023bool
7024MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7025 llvm::Value *Address) const {
7026 // This information comes from gcc's implementation, which seems to
7027 // as canonical as it gets.
7028
John McCall943fae92010-05-27 06:19:26 +00007029 // Everything on MIPS is 4 bytes. Double-precision FP registers
7030 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007031 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007032
7033 // 0-31 are the general purpose registers, $0 - $31.
7034 // 32-63 are the floating-point registers, $f0 - $f31.
7035 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7036 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007037 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007038
7039 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7040 // They are one bit wide and ignored here.
7041
7042 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7043 // (coprocessor 1 is the FP unit)
7044 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7045 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7046 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007047 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007048 return false;
7049}
7050
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007051//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007052// AVR ABI Implementation.
7053//===----------------------------------------------------------------------===//
7054
7055namespace {
7056class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7057public:
7058 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7059 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7060
7061 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007062 CodeGen::CodeGenModule &CGM,
7063 ForDefinition_t IsForDefinition) const override {
7064 if (!IsForDefinition)
7065 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007066 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7067 if (!FD) return;
7068 auto *Fn = cast<llvm::Function>(GV);
7069
7070 if (FD->getAttr<AVRInterruptAttr>())
7071 Fn->addFnAttr("interrupt");
7072
7073 if (FD->getAttr<AVRSignalAttr>())
7074 Fn->addFnAttr("signal");
7075 }
7076};
7077}
7078
7079//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007080// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007081// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007082// handling.
7083//===----------------------------------------------------------------------===//
7084
7085namespace {
7086
7087class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7088public:
7089 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7090 : DefaultTargetCodeGenInfo(CGT) {}
7091
Eric Christopher162c91c2015-06-05 22:03:00 +00007092 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007093 CodeGen::CodeGenModule &M,
7094 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007095};
7096
Eric Christopher162c91c2015-06-05 22:03:00 +00007097void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007098 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7099 ForDefinition_t IsForDefinition) const {
7100 if (!IsForDefinition)
7101 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007102 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007103 if (!FD) return;
7104
7105 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007106
David Blaikiebbafb8a2012-03-11 07:00:24 +00007107 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007108 if (FD->hasAttr<OpenCLKernelAttr>()) {
7109 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007110 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007111 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7112 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007113 // Convert the reqd_work_group_size() attributes to metadata.
7114 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007115 llvm::NamedMDNode *OpenCLMetadata =
7116 M.getModule().getOrInsertNamedMetadata(
7117 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007118
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007119 SmallVector<llvm::Metadata *, 5> Operands;
7120 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007121
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007122 Operands.push_back(
7123 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7124 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7125 Operands.push_back(
7126 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7127 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7128 Operands.push_back(
7129 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7130 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007131
Eric Christopher7565e0d2015-05-29 23:09:49 +00007132 // Add a boolean constant operand for "required" (true) or "hint"
7133 // (false) for implementing the work_group_size_hint attr later.
7134 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007135 Operands.push_back(
7136 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007137 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7138 }
7139 }
7140 }
7141}
7142
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007143}
John McCall943fae92010-05-27 06:19:26 +00007144
Tony Linthicum76329bf2011-12-12 21:14:55 +00007145//===----------------------------------------------------------------------===//
7146// Hexagon ABI Implementation
7147//===----------------------------------------------------------------------===//
7148
7149namespace {
7150
7151class HexagonABIInfo : public ABIInfo {
7152
7153
7154public:
7155 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7156
7157private:
7158
7159 ABIArgInfo classifyReturnType(QualType RetTy) const;
7160 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7161
Craig Topper4f12f102014-03-12 06:41:41 +00007162 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007163
John McCall7f416cc2015-09-08 08:05:57 +00007164 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7165 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007166};
7167
7168class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7169public:
7170 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7171 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7172
Craig Topper4f12f102014-03-12 06:41:41 +00007173 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007174 return 29;
7175 }
7176};
7177
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007178}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007179
7180void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007181 if (!getCXXABI().classifyReturnType(FI))
7182 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007183 for (auto &I : FI.arguments())
7184 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007185}
7186
7187ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7188 if (!isAggregateTypeForABI(Ty)) {
7189 // Treat an enum type as its underlying type.
7190 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7191 Ty = EnumTy->getDecl()->getIntegerType();
7192
7193 return (Ty->isPromotableIntegerType() ?
7194 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7195 }
7196
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007197 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7198 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7199
Tony Linthicum76329bf2011-12-12 21:14:55 +00007200 // Ignore empty records.
7201 if (isEmptyRecord(getContext(), Ty, true))
7202 return ABIArgInfo::getIgnore();
7203
Tony Linthicum76329bf2011-12-12 21:14:55 +00007204 uint64_t Size = getContext().getTypeSize(Ty);
7205 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007206 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007207 // Pass in the smallest viable integer type.
7208 else if (Size > 32)
7209 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7210 else if (Size > 16)
7211 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7212 else if (Size > 8)
7213 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7214 else
7215 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7216}
7217
7218ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7219 if (RetTy->isVoidType())
7220 return ABIArgInfo::getIgnore();
7221
7222 // Large vector types should be returned via memory.
7223 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007224 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007225
7226 if (!isAggregateTypeForABI(RetTy)) {
7227 // Treat an enum type as its underlying type.
7228 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7229 RetTy = EnumTy->getDecl()->getIntegerType();
7230
7231 return (RetTy->isPromotableIntegerType() ?
7232 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7233 }
7234
Tony Linthicum76329bf2011-12-12 21:14:55 +00007235 if (isEmptyRecord(getContext(), RetTy, true))
7236 return ABIArgInfo::getIgnore();
7237
7238 // Aggregates <= 8 bytes are returned in r0; other aggregates
7239 // are returned indirectly.
7240 uint64_t Size = getContext().getTypeSize(RetTy);
7241 if (Size <= 64) {
7242 // Return in the smallest viable integer type.
7243 if (Size <= 8)
7244 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7245 if (Size <= 16)
7246 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7247 if (Size <= 32)
7248 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7249 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7250 }
7251
John McCall7f416cc2015-09-08 08:05:57 +00007252 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007253}
7254
John McCall7f416cc2015-09-08 08:05:57 +00007255Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7256 QualType Ty) const {
7257 // FIXME: Someone needs to audit that this handle alignment correctly.
7258 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7259 getContext().getTypeInfoInChars(Ty),
7260 CharUnits::fromQuantity(4),
7261 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007262}
7263
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007264//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007265// Lanai ABI Implementation
7266//===----------------------------------------------------------------------===//
7267
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007268namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007269class LanaiABIInfo : public DefaultABIInfo {
7270public:
7271 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7272
7273 bool shouldUseInReg(QualType Ty, CCState &State) const;
7274
7275 void computeInfo(CGFunctionInfo &FI) const override {
7276 CCState State(FI.getCallingConvention());
7277 // Lanai uses 4 registers to pass arguments unless the function has the
7278 // regparm attribute set.
7279 if (FI.getHasRegParm()) {
7280 State.FreeRegs = FI.getRegParm();
7281 } else {
7282 State.FreeRegs = 4;
7283 }
7284
7285 if (!getCXXABI().classifyReturnType(FI))
7286 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7287 for (auto &I : FI.arguments())
7288 I.info = classifyArgumentType(I.type, State);
7289 }
7290
Jacques Pienaare74d9132016-04-26 00:09:29 +00007291 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007292 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7293};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007294} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007295
7296bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7297 unsigned Size = getContext().getTypeSize(Ty);
7298 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7299
7300 if (SizeInRegs == 0)
7301 return false;
7302
7303 if (SizeInRegs > State.FreeRegs) {
7304 State.FreeRegs = 0;
7305 return false;
7306 }
7307
7308 State.FreeRegs -= SizeInRegs;
7309
7310 return true;
7311}
7312
Jacques Pienaare74d9132016-04-26 00:09:29 +00007313ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7314 CCState &State) const {
7315 if (!ByVal) {
7316 if (State.FreeRegs) {
7317 --State.FreeRegs; // Non-byval indirects just use one pointer.
7318 return getNaturalAlignIndirectInReg(Ty);
7319 }
7320 return getNaturalAlignIndirect(Ty, false);
7321 }
7322
7323 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007324 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007325 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7326 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7327 /*Realign=*/TypeAlign >
7328 MinABIStackAlignInBytes);
7329}
7330
Jacques Pienaard964cc22016-03-28 21:02:54 +00007331ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7332 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007333 // Check with the C++ ABI first.
7334 const RecordType *RT = Ty->getAs<RecordType>();
7335 if (RT) {
7336 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7337 if (RAA == CGCXXABI::RAA_Indirect) {
7338 return getIndirectResult(Ty, /*ByVal=*/false, State);
7339 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7340 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7341 }
7342 }
7343
7344 if (isAggregateTypeForABI(Ty)) {
7345 // Structures with flexible arrays are always indirect.
7346 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7347 return getIndirectResult(Ty, /*ByVal=*/true, State);
7348
7349 // Ignore empty structs/unions.
7350 if (isEmptyRecord(getContext(), Ty, true))
7351 return ABIArgInfo::getIgnore();
7352
7353 llvm::LLVMContext &LLVMContext = getVMContext();
7354 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7355 if (SizeInRegs <= State.FreeRegs) {
7356 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7357 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7358 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7359 State.FreeRegs -= SizeInRegs;
7360 return ABIArgInfo::getDirectInReg(Result);
7361 } else {
7362 State.FreeRegs = 0;
7363 }
7364 return getIndirectResult(Ty, true, State);
7365 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007366
7367 // Treat an enum type as its underlying type.
7368 if (const auto *EnumTy = Ty->getAs<EnumType>())
7369 Ty = EnumTy->getDecl()->getIntegerType();
7370
Jacques Pienaare74d9132016-04-26 00:09:29 +00007371 bool InReg = shouldUseInReg(Ty, State);
7372 if (Ty->isPromotableIntegerType()) {
7373 if (InReg)
7374 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007375 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007376 }
7377 if (InReg)
7378 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007379 return ABIArgInfo::getDirect();
7380}
7381
7382namespace {
7383class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7384public:
7385 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7386 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7387};
7388}
7389
7390//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007391// AMDGPU ABI Implementation
7392//===----------------------------------------------------------------------===//
7393
7394namespace {
7395
Matt Arsenault88d7da02016-08-22 19:25:59 +00007396class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007397private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007398 static const unsigned MaxNumRegsForArgsRet = 16;
7399
Matt Arsenault3fe73952017-08-09 21:44:58 +00007400 unsigned numRegsForType(QualType Ty) const;
7401
7402 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7403 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7404 uint64_t Members) const override;
7405
7406public:
7407 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7408 DefaultABIInfo(CGT) {}
7409
7410 ABIArgInfo classifyReturnType(QualType RetTy) const;
7411 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7412 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007413
7414 void computeInfo(CGFunctionInfo &FI) const override;
7415};
7416
Matt Arsenault3fe73952017-08-09 21:44:58 +00007417bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7418 return true;
7419}
7420
7421bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7422 const Type *Base, uint64_t Members) const {
7423 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7424
7425 // Homogeneous Aggregates may occupy at most 16 registers.
7426 return Members * NumRegs <= MaxNumRegsForArgsRet;
7427}
7428
Matt Arsenault3fe73952017-08-09 21:44:58 +00007429/// Estimate number of registers the type will use when passed in registers.
7430unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7431 unsigned NumRegs = 0;
7432
7433 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7434 // Compute from the number of elements. The reported size is based on the
7435 // in-memory size, which includes the padding 4th element for 3-vectors.
7436 QualType EltTy = VT->getElementType();
7437 unsigned EltSize = getContext().getTypeSize(EltTy);
7438
7439 // 16-bit element vectors should be passed as packed.
7440 if (EltSize == 16)
7441 return (VT->getNumElements() + 1) / 2;
7442
7443 unsigned EltNumRegs = (EltSize + 31) / 32;
7444 return EltNumRegs * VT->getNumElements();
7445 }
7446
7447 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7448 const RecordDecl *RD = RT->getDecl();
7449 assert(!RD->hasFlexibleArrayMember());
7450
7451 for (const FieldDecl *Field : RD->fields()) {
7452 QualType FieldTy = Field->getType();
7453 NumRegs += numRegsForType(FieldTy);
7454 }
7455
7456 return NumRegs;
7457 }
7458
7459 return (getContext().getTypeSize(Ty) + 31) / 32;
7460}
7461
Matt Arsenault88d7da02016-08-22 19:25:59 +00007462void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007463 llvm::CallingConv::ID CC = FI.getCallingConvention();
7464
Matt Arsenault88d7da02016-08-22 19:25:59 +00007465 if (!getCXXABI().classifyReturnType(FI))
7466 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7467
Matt Arsenault3fe73952017-08-09 21:44:58 +00007468 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7469 for (auto &Arg : FI.arguments()) {
7470 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7471 Arg.info = classifyKernelArgumentType(Arg.type);
7472 } else {
7473 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7474 }
7475 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007476}
7477
Matt Arsenault3fe73952017-08-09 21:44:58 +00007478ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7479 if (isAggregateTypeForABI(RetTy)) {
7480 // Records with non-trivial destructors/copy-constructors should not be
7481 // returned by value.
7482 if (!getRecordArgABI(RetTy, getCXXABI())) {
7483 // Ignore empty structs/unions.
7484 if (isEmptyRecord(getContext(), RetTy, true))
7485 return ABIArgInfo::getIgnore();
7486
7487 // Lower single-element structs to just return a regular value.
7488 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7489 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7490
7491 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7492 const RecordDecl *RD = RT->getDecl();
7493 if (RD->hasFlexibleArrayMember())
7494 return DefaultABIInfo::classifyReturnType(RetTy);
7495 }
7496
7497 // Pack aggregates <= 4 bytes into single VGPR or pair.
7498 uint64_t Size = getContext().getTypeSize(RetTy);
7499 if (Size <= 16)
7500 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7501
7502 if (Size <= 32)
7503 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7504
7505 if (Size <= 64) {
7506 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7507 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7508 }
7509
7510 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7511 return ABIArgInfo::getDirect();
7512 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007513 }
7514
Matt Arsenault3fe73952017-08-09 21:44:58 +00007515 // Otherwise just do the default thing.
7516 return DefaultABIInfo::classifyReturnType(RetTy);
7517}
7518
7519/// For kernels all parameters are really passed in a special buffer. It doesn't
7520/// make sense to pass anything byval, so everything must be direct.
7521ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7522 Ty = useFirstFieldIfTransparentUnion(Ty);
7523
7524 // TODO: Can we omit empty structs?
7525
Matt Arsenault88d7da02016-08-22 19:25:59 +00007526 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007527 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7528 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007529
7530 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7531 // individual elements, which confuses the Clover OpenCL backend; therefore we
7532 // have to set it to false here. Other args of getDirect() are just defaults.
7533 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7534}
7535
Matt Arsenault3fe73952017-08-09 21:44:58 +00007536ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7537 unsigned &NumRegsLeft) const {
7538 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7539
7540 Ty = useFirstFieldIfTransparentUnion(Ty);
7541
7542 if (isAggregateTypeForABI(Ty)) {
7543 // Records with non-trivial destructors/copy-constructors should not be
7544 // passed by value.
7545 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7546 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7547
7548 // Ignore empty structs/unions.
7549 if (isEmptyRecord(getContext(), Ty, true))
7550 return ABIArgInfo::getIgnore();
7551
7552 // Lower single-element structs to just pass a regular value. TODO: We
7553 // could do reasonable-size multiple-element structs too, using getExpand(),
7554 // though watch out for things like bitfields.
7555 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7556 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7557
7558 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7559 const RecordDecl *RD = RT->getDecl();
7560 if (RD->hasFlexibleArrayMember())
7561 return DefaultABIInfo::classifyArgumentType(Ty);
7562 }
7563
7564 // Pack aggregates <= 8 bytes into single VGPR or pair.
7565 uint64_t Size = getContext().getTypeSize(Ty);
7566 if (Size <= 64) {
7567 unsigned NumRegs = (Size + 31) / 32;
7568 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7569
7570 if (Size <= 16)
7571 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7572
7573 if (Size <= 32)
7574 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7575
7576 // XXX: Should this be i64 instead, and should the limit increase?
7577 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7578 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7579 }
7580
7581 if (NumRegsLeft > 0) {
7582 unsigned NumRegs = numRegsForType(Ty);
7583 if (NumRegsLeft >= NumRegs) {
7584 NumRegsLeft -= NumRegs;
7585 return ABIArgInfo::getDirect();
7586 }
7587 }
7588 }
7589
7590 // Otherwise just do the default thing.
7591 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7592 if (!ArgInfo.isIndirect()) {
7593 unsigned NumRegs = numRegsForType(Ty);
7594 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7595 }
7596
7597 return ArgInfo;
7598}
7599
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007600class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7601public:
7602 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007603 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007604 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007605 CodeGen::CodeGenModule &M,
7606 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007607 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007608
Yaxun Liu402804b2016-12-15 08:09:08 +00007609 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7610 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007611
7612 unsigned getASTAllocaAddressSpace() const override {
7613 return LangAS::FirstTargetAddressSpace +
7614 getABIInfo().getDataLayout().getAllocaAddrSpace();
7615 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007616 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7617 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007618 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7619 llvm::LLVMContext &C) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007620};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007621}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007622
Eric Christopher162c91c2015-06-05 22:03:00 +00007623void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007624 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7625 ForDefinition_t IsForDefinition) const {
7626 if (!IsForDefinition)
7627 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007628 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007629 if (!FD)
7630 return;
7631
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007632 llvm::Function *F = cast<llvm::Function>(GV);
7633
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007634 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7635 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7636 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7637 if (ReqdWGS || FlatWGS) {
7638 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7639 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7640 if (ReqdWGS && Min == 0 && Max == 0)
7641 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007642
7643 if (Min != 0) {
7644 assert(Min <= Max && "Min must be less than or equal Max");
7645
7646 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7647 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7648 } else
7649 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007650 }
7651
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007652 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7653 unsigned Min = Attr->getMin();
7654 unsigned Max = Attr->getMax();
7655
7656 if (Min != 0) {
7657 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7658
7659 std::string AttrVal = llvm::utostr(Min);
7660 if (Max != 0)
7661 AttrVal = AttrVal + "," + llvm::utostr(Max);
7662 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7663 } else
7664 assert(Max == 0 && "Max must be zero");
7665 }
7666
7667 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007668 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007669
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007670 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007671 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7672 }
7673
7674 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7675 uint32_t NumVGPR = Attr->getNumVGPR();
7676
7677 if (NumVGPR != 0)
7678 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007679 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007680}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007681
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007682unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7683 return llvm::CallingConv::AMDGPU_KERNEL;
7684}
7685
Yaxun Liu402804b2016-12-15 08:09:08 +00007686// Currently LLVM assumes null pointers always have value 0,
7687// which results in incorrectly transformed IR. Therefore, instead of
7688// emitting null pointers in private and local address spaces, a null
7689// pointer in generic address space is emitted which is casted to a
7690// pointer in local or private address space.
7691llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7692 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7693 QualType QT) const {
7694 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7695 return llvm::ConstantPointerNull::get(PT);
7696
7697 auto &Ctx = CGM.getContext();
7698 auto NPT = llvm::PointerType::get(PT->getElementType(),
7699 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7700 return llvm::ConstantExpr::getAddrSpaceCast(
7701 llvm::ConstantPointerNull::get(NPT), PT);
7702}
7703
Yaxun Liucbf647c2017-07-08 13:24:52 +00007704unsigned
7705AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7706 const VarDecl *D) const {
7707 assert(!CGM.getLangOpts().OpenCL &&
7708 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7709 "Address space agnostic languages only");
7710 unsigned DefaultGlobalAS =
7711 LangAS::FirstTargetAddressSpace +
7712 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7713 if (!D)
7714 return DefaultGlobalAS;
7715
7716 unsigned AddrSpace = D->getType().getAddressSpace();
7717 assert(AddrSpace == LangAS::Default ||
7718 AddrSpace >= LangAS::FirstTargetAddressSpace);
7719 if (AddrSpace != LangAS::Default)
7720 return AddrSpace;
7721
7722 if (CGM.isTypeConstant(D->getType(), false)) {
7723 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7724 return ConstAS.getValue();
7725 }
7726 return DefaultGlobalAS;
7727}
7728
Yaxun Liu39195062017-08-04 18:16:31 +00007729llvm::SyncScope::ID
7730AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7731 llvm::LLVMContext &C) const {
7732 StringRef Name;
7733 switch (S) {
7734 case SyncScope::OpenCLWorkGroup:
7735 Name = "workgroup";
7736 break;
7737 case SyncScope::OpenCLDevice:
7738 Name = "agent";
7739 break;
7740 case SyncScope::OpenCLAllSVMDevices:
7741 Name = "";
7742 break;
7743 case SyncScope::OpenCLSubGroup:
7744 Name = "subgroup";
7745 }
7746 return C.getOrInsertSyncScopeID(Name);
7747}
7748
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007749//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007750// SPARC v8 ABI Implementation.
7751// Based on the SPARC Compliance Definition version 2.4.1.
7752//
7753// Ensures that complex values are passed in registers.
7754//
7755namespace {
7756class SparcV8ABIInfo : public DefaultABIInfo {
7757public:
7758 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7759
7760private:
7761 ABIArgInfo classifyReturnType(QualType RetTy) const;
7762 void computeInfo(CGFunctionInfo &FI) const override;
7763};
7764} // end anonymous namespace
7765
7766
7767ABIArgInfo
7768SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7769 if (Ty->isAnyComplexType()) {
7770 return ABIArgInfo::getDirect();
7771 }
7772 else {
7773 return DefaultABIInfo::classifyReturnType(Ty);
7774 }
7775}
7776
7777void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7778
7779 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7780 for (auto &Arg : FI.arguments())
7781 Arg.info = classifyArgumentType(Arg.type);
7782}
7783
7784namespace {
7785class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7786public:
7787 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7788 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7789};
7790} // end anonymous namespace
7791
7792//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007793// SPARC v9 ABI Implementation.
7794// Based on the SPARC Compliance Definition version 2.4.1.
7795//
7796// Function arguments a mapped to a nominal "parameter array" and promoted to
7797// registers depending on their type. Each argument occupies 8 or 16 bytes in
7798// the array, structs larger than 16 bytes are passed indirectly.
7799//
7800// One case requires special care:
7801//
7802// struct mixed {
7803// int i;
7804// float f;
7805// };
7806//
7807// When a struct mixed is passed by value, it only occupies 8 bytes in the
7808// parameter array, but the int is passed in an integer register, and the float
7809// is passed in a floating point register. This is represented as two arguments
7810// with the LLVM IR inreg attribute:
7811//
7812// declare void f(i32 inreg %i, float inreg %f)
7813//
7814// The code generator will only allocate 4 bytes from the parameter array for
7815// the inreg arguments. All other arguments are allocated a multiple of 8
7816// bytes.
7817//
7818namespace {
7819class SparcV9ABIInfo : public ABIInfo {
7820public:
7821 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7822
7823private:
7824 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007825 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007826 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7827 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007828
7829 // Coercion type builder for structs passed in registers. The coercion type
7830 // serves two purposes:
7831 //
7832 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7833 // in registers.
7834 // 2. Expose aligned floating point elements as first-level elements, so the
7835 // code generator knows to pass them in floating point registers.
7836 //
7837 // We also compute the InReg flag which indicates that the struct contains
7838 // aligned 32-bit floats.
7839 //
7840 struct CoerceBuilder {
7841 llvm::LLVMContext &Context;
7842 const llvm::DataLayout &DL;
7843 SmallVector<llvm::Type*, 8> Elems;
7844 uint64_t Size;
7845 bool InReg;
7846
7847 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7848 : Context(c), DL(dl), Size(0), InReg(false) {}
7849
7850 // Pad Elems with integers until Size is ToSize.
7851 void pad(uint64_t ToSize) {
7852 assert(ToSize >= Size && "Cannot remove elements");
7853 if (ToSize == Size)
7854 return;
7855
7856 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007857 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007858 if (Aligned > Size && Aligned <= ToSize) {
7859 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7860 Size = Aligned;
7861 }
7862
7863 // Add whole 64-bit words.
7864 while (Size + 64 <= ToSize) {
7865 Elems.push_back(llvm::Type::getInt64Ty(Context));
7866 Size += 64;
7867 }
7868
7869 // Final in-word padding.
7870 if (Size < ToSize) {
7871 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7872 Size = ToSize;
7873 }
7874 }
7875
7876 // Add a floating point element at Offset.
7877 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7878 // Unaligned floats are treated as integers.
7879 if (Offset % Bits)
7880 return;
7881 // The InReg flag is only required if there are any floats < 64 bits.
7882 if (Bits < 64)
7883 InReg = true;
7884 pad(Offset);
7885 Elems.push_back(Ty);
7886 Size = Offset + Bits;
7887 }
7888
7889 // Add a struct type to the coercion type, starting at Offset (in bits).
7890 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7891 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7892 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7893 llvm::Type *ElemTy = StrTy->getElementType(i);
7894 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7895 switch (ElemTy->getTypeID()) {
7896 case llvm::Type::StructTyID:
7897 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7898 break;
7899 case llvm::Type::FloatTyID:
7900 addFloat(ElemOffset, ElemTy, 32);
7901 break;
7902 case llvm::Type::DoubleTyID:
7903 addFloat(ElemOffset, ElemTy, 64);
7904 break;
7905 case llvm::Type::FP128TyID:
7906 addFloat(ElemOffset, ElemTy, 128);
7907 break;
7908 case llvm::Type::PointerTyID:
7909 if (ElemOffset % 64 == 0) {
7910 pad(ElemOffset);
7911 Elems.push_back(ElemTy);
7912 Size += 64;
7913 }
7914 break;
7915 default:
7916 break;
7917 }
7918 }
7919 }
7920
7921 // Check if Ty is a usable substitute for the coercion type.
7922 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007923 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007924 }
7925
7926 // Get the coercion type as a literal struct type.
7927 llvm::Type *getType() const {
7928 if (Elems.size() == 1)
7929 return Elems.front();
7930 else
7931 return llvm::StructType::get(Context, Elems);
7932 }
7933 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007934};
7935} // end anonymous namespace
7936
7937ABIArgInfo
7938SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7939 if (Ty->isVoidType())
7940 return ABIArgInfo::getIgnore();
7941
7942 uint64_t Size = getContext().getTypeSize(Ty);
7943
7944 // Anything too big to fit in registers is passed with an explicit indirect
7945 // pointer / sret pointer.
7946 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007947 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007948
7949 // Treat an enum type as its underlying type.
7950 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7951 Ty = EnumTy->getDecl()->getIntegerType();
7952
7953 // Integer types smaller than a register are extended.
7954 if (Size < 64 && Ty->isIntegerType())
7955 return ABIArgInfo::getExtend();
7956
7957 // Other non-aggregates go in registers.
7958 if (!isAggregateTypeForABI(Ty))
7959 return ABIArgInfo::getDirect();
7960
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007961 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7962 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7963 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007964 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007965
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007966 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007967 // Build a coercion type from the LLVM struct type.
7968 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7969 if (!StrTy)
7970 return ABIArgInfo::getDirect();
7971
7972 CoerceBuilder CB(getVMContext(), getDataLayout());
7973 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007974 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007975
7976 // Try to use the original type for coercion.
7977 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7978
7979 if (CB.InReg)
7980 return ABIArgInfo::getDirectInReg(CoerceTy);
7981 else
7982 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007983}
7984
John McCall7f416cc2015-09-08 08:05:57 +00007985Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7986 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007987 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7988 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7989 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7990 AI.setCoerceToType(ArgTy);
7991
John McCall7f416cc2015-09-08 08:05:57 +00007992 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007993
John McCall7f416cc2015-09-08 08:05:57 +00007994 CGBuilderTy &Builder = CGF.Builder;
7995 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7996 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7997
7998 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7999
8000 Address ArgAddr = Address::invalid();
8001 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008002 switch (AI.getKind()) {
8003 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008004 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008005 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008006 llvm_unreachable("Unsupported ABI kind for va_arg");
8007
John McCall7f416cc2015-09-08 08:05:57 +00008008 case ABIArgInfo::Extend: {
8009 Stride = SlotSize;
8010 CharUnits Offset = SlotSize - TypeInfo.first;
8011 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008012 break;
John McCall7f416cc2015-09-08 08:05:57 +00008013 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008014
John McCall7f416cc2015-09-08 08:05:57 +00008015 case ABIArgInfo::Direct: {
8016 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008017 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008018 ArgAddr = Addr;
8019 break;
John McCall7f416cc2015-09-08 08:05:57 +00008020 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008021
8022 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008023 Stride = SlotSize;
8024 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8025 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8026 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008027 break;
8028
8029 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008030 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008031 }
8032
8033 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008034 llvm::Value *NextPtr =
8035 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8036 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008037
John McCall7f416cc2015-09-08 08:05:57 +00008038 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008039}
8040
8041void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8042 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008043 for (auto &I : FI.arguments())
8044 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008045}
8046
8047namespace {
8048class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8049public:
8050 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8051 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008052
Craig Topper4f12f102014-03-12 06:41:41 +00008053 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008054 return 14;
8055 }
8056
8057 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008058 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008059};
8060} // end anonymous namespace
8061
Roman Divackyf02c9942014-02-24 18:46:27 +00008062bool
8063SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8064 llvm::Value *Address) const {
8065 // This is calculated from the LLVM and GCC tables and verified
8066 // against gcc output. AFAIK all ABIs use the same encoding.
8067
8068 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8069
8070 llvm::IntegerType *i8 = CGF.Int8Ty;
8071 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8072 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8073
8074 // 0-31: the 8-byte general-purpose registers
8075 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8076
8077 // 32-63: f0-31, the 4-byte floating-point registers
8078 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8079
8080 // Y = 64
8081 // PSR = 65
8082 // WIM = 66
8083 // TBR = 67
8084 // PC = 68
8085 // NPC = 69
8086 // FSR = 70
8087 // CSR = 71
8088 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008089
Roman Divackyf02c9942014-02-24 18:46:27 +00008090 // 72-87: d0-15, the 8-byte floating-point registers
8091 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8092
8093 return false;
8094}
8095
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008096
Robert Lytton0e076492013-08-13 09:43:10 +00008097//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008098// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008099//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008100
Robert Lytton0e076492013-08-13 09:43:10 +00008101namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008102
8103/// A SmallStringEnc instance is used to build up the TypeString by passing
8104/// it by reference between functions that append to it.
8105typedef llvm::SmallString<128> SmallStringEnc;
8106
8107/// TypeStringCache caches the meta encodings of Types.
8108///
8109/// The reason for caching TypeStrings is two fold:
8110/// 1. To cache a type's encoding for later uses;
8111/// 2. As a means to break recursive member type inclusion.
8112///
8113/// A cache Entry can have a Status of:
8114/// NonRecursive: The type encoding is not recursive;
8115/// Recursive: The type encoding is recursive;
8116/// Incomplete: An incomplete TypeString;
8117/// IncompleteUsed: An incomplete TypeString that has been used in a
8118/// Recursive type encoding.
8119///
8120/// A NonRecursive entry will have all of its sub-members expanded as fully
8121/// as possible. Whilst it may contain types which are recursive, the type
8122/// itself is not recursive and thus its encoding may be safely used whenever
8123/// the type is encountered.
8124///
8125/// A Recursive entry will have all of its sub-members expanded as fully as
8126/// possible. The type itself is recursive and it may contain other types which
8127/// are recursive. The Recursive encoding must not be used during the expansion
8128/// of a recursive type's recursive branch. For simplicity the code uses
8129/// IncompleteCount to reject all usage of Recursive encodings for member types.
8130///
8131/// An Incomplete entry is always a RecordType and only encodes its
8132/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8133/// are placed into the cache during type expansion as a means to identify and
8134/// handle recursive inclusion of types as sub-members. If there is recursion
8135/// the entry becomes IncompleteUsed.
8136///
8137/// During the expansion of a RecordType's members:
8138///
8139/// If the cache contains a NonRecursive encoding for the member type, the
8140/// cached encoding is used;
8141///
8142/// If the cache contains a Recursive encoding for the member type, the
8143/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8144///
8145/// If the member is a RecordType, an Incomplete encoding is placed into the
8146/// cache to break potential recursive inclusion of itself as a sub-member;
8147///
8148/// Once a member RecordType has been expanded, its temporary incomplete
8149/// entry is removed from the cache. If a Recursive encoding was swapped out
8150/// it is swapped back in;
8151///
8152/// If an incomplete entry is used to expand a sub-member, the incomplete
8153/// entry is marked as IncompleteUsed. The cache keeps count of how many
8154/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8155///
8156/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8157/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8158/// Else the member is part of a recursive type and thus the recursion has
8159/// been exited too soon for the encoding to be correct for the member.
8160///
8161class TypeStringCache {
8162 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8163 struct Entry {
8164 std::string Str; // The encoded TypeString for the type.
8165 enum Status State; // Information about the encoding in 'Str'.
8166 std::string Swapped; // A temporary place holder for a Recursive encoding
8167 // during the expansion of RecordType's members.
8168 };
8169 std::map<const IdentifierInfo *, struct Entry> Map;
8170 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8171 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8172public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008173 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008174 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8175 bool removeIncomplete(const IdentifierInfo *ID);
8176 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8177 bool IsRecursive);
8178 StringRef lookupStr(const IdentifierInfo *ID);
8179};
8180
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008181/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008182/// FieldEncoding is a helper for this ordering process.
8183class FieldEncoding {
8184 bool HasName;
8185 std::string Enc;
8186public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008187 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008188 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008189 bool operator<(const FieldEncoding &rhs) const {
8190 if (HasName != rhs.HasName) return HasName;
8191 return Enc < rhs.Enc;
8192 }
8193};
8194
Robert Lytton7d1db152013-08-19 09:46:39 +00008195class XCoreABIInfo : public DefaultABIInfo {
8196public:
8197 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008198 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8199 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008200};
8201
Robert Lyttond21e2d72014-03-03 13:45:29 +00008202class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008203 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008204public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008205 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008206 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008207 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8208 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008209};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008210
Robert Lytton2d196952013-10-11 10:29:34 +00008211} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008212
James Y Knight29b5f082016-02-24 02:59:33 +00008213// TODO: this implementation is likely now redundant with the default
8214// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008215Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8216 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008217 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008218
Robert Lytton2d196952013-10-11 10:29:34 +00008219 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008220 CharUnits SlotSize = CharUnits::fromQuantity(4);
8221 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008222
Robert Lytton2d196952013-10-11 10:29:34 +00008223 // Handle the argument.
8224 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008225 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008226 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8227 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8228 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008229 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008230
8231 Address Val = Address::invalid();
8232 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008233 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008234 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008235 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008236 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008237 llvm_unreachable("Unsupported ABI kind for va_arg");
8238 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008239 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8240 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008241 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008242 case ABIArgInfo::Extend:
8243 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008244 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8245 ArgSize = CharUnits::fromQuantity(
8246 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008247 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008248 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008249 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008250 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8251 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8252 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008253 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008254 }
Robert Lytton2d196952013-10-11 10:29:34 +00008255
8256 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008257 if (!ArgSize.isZero()) {
8258 llvm::Value *APN =
8259 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8260 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008261 }
John McCall7f416cc2015-09-08 08:05:57 +00008262
Robert Lytton2d196952013-10-11 10:29:34 +00008263 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008264}
Robert Lytton0e076492013-08-13 09:43:10 +00008265
Robert Lytton844aeeb2014-05-02 09:33:20 +00008266/// During the expansion of a RecordType, an incomplete TypeString is placed
8267/// into the cache as a means to identify and break recursion.
8268/// If there is a Recursive encoding in the cache, it is swapped out and will
8269/// be reinserted by removeIncomplete().
8270/// All other types of encoding should have been used rather than arriving here.
8271void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8272 std::string StubEnc) {
8273 if (!ID)
8274 return;
8275 Entry &E = Map[ID];
8276 assert( (E.Str.empty() || E.State == Recursive) &&
8277 "Incorrectly use of addIncomplete");
8278 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8279 E.Swapped.swap(E.Str); // swap out the Recursive
8280 E.Str.swap(StubEnc);
8281 E.State = Incomplete;
8282 ++IncompleteCount;
8283}
8284
8285/// Once the RecordType has been expanded, the temporary incomplete TypeString
8286/// must be removed from the cache.
8287/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8288/// Returns true if the RecordType was defined recursively.
8289bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8290 if (!ID)
8291 return false;
8292 auto I = Map.find(ID);
8293 assert(I != Map.end() && "Entry not present");
8294 Entry &E = I->second;
8295 assert( (E.State == Incomplete ||
8296 E.State == IncompleteUsed) &&
8297 "Entry must be an incomplete type");
8298 bool IsRecursive = false;
8299 if (E.State == IncompleteUsed) {
8300 // We made use of our Incomplete encoding, thus we are recursive.
8301 IsRecursive = true;
8302 --IncompleteUsedCount;
8303 }
8304 if (E.Swapped.empty())
8305 Map.erase(I);
8306 else {
8307 // Swap the Recursive back.
8308 E.Swapped.swap(E.Str);
8309 E.Swapped.clear();
8310 E.State = Recursive;
8311 }
8312 --IncompleteCount;
8313 return IsRecursive;
8314}
8315
8316/// Add the encoded TypeString to the cache only if it is NonRecursive or
8317/// Recursive (viz: all sub-members were expanded as fully as possible).
8318void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8319 bool IsRecursive) {
8320 if (!ID || IncompleteUsedCount)
8321 return; // No key or it is is an incomplete sub-type so don't add.
8322 Entry &E = Map[ID];
8323 if (IsRecursive && !E.Str.empty()) {
8324 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8325 "This is not the same Recursive entry");
8326 // The parent container was not recursive after all, so we could have used
8327 // this Recursive sub-member entry after all, but we assumed the worse when
8328 // we started viz: IncompleteCount!=0.
8329 return;
8330 }
8331 assert(E.Str.empty() && "Entry already present");
8332 E.Str = Str.str();
8333 E.State = IsRecursive? Recursive : NonRecursive;
8334}
8335
8336/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8337/// are recursively expanding a type (IncompleteCount != 0) and the cached
8338/// encoding is Recursive, return an empty StringRef.
8339StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8340 if (!ID)
8341 return StringRef(); // We have no key.
8342 auto I = Map.find(ID);
8343 if (I == Map.end())
8344 return StringRef(); // We have no encoding.
8345 Entry &E = I->second;
8346 if (E.State == Recursive && IncompleteCount)
8347 return StringRef(); // We don't use Recursive encodings for member types.
8348
8349 if (E.State == Incomplete) {
8350 // The incomplete type is being used to break out of recursion.
8351 E.State = IncompleteUsed;
8352 ++IncompleteUsedCount;
8353 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008354 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008355}
8356
8357/// The XCore ABI includes a type information section that communicates symbol
8358/// type information to the linker. The linker uses this information to verify
8359/// safety/correctness of things such as array bound and pointers et al.
8360/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8361/// This type information (TypeString) is emitted into meta data for all global
8362/// symbols: definitions, declarations, functions & variables.
8363///
8364/// The TypeString carries type, qualifier, name, size & value details.
8365/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008366/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008367/// The output is tested by test/CodeGen/xcore-stringtype.c.
8368///
8369static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8370 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8371
8372/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8373void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8374 CodeGen::CodeGenModule &CGM) const {
8375 SmallStringEnc Enc;
8376 if (getTypeString(Enc, D, CGM, TSC)) {
8377 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008378 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8379 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008380 llvm::NamedMDNode *MD =
8381 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8382 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8383 }
8384}
8385
Xiuli Pan972bea82016-03-24 03:57:17 +00008386//===----------------------------------------------------------------------===//
8387// SPIR ABI Implementation
8388//===----------------------------------------------------------------------===//
8389
8390namespace {
8391class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8392public:
8393 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8394 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008395 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008396};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008397
Xiuli Pan972bea82016-03-24 03:57:17 +00008398} // End anonymous namespace.
8399
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008400namespace clang {
8401namespace CodeGen {
8402void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8403 DefaultABIInfo SPIRABI(CGM.getTypes());
8404 SPIRABI.computeInfo(FI);
8405}
8406}
8407}
8408
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008409unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8410 return llvm::CallingConv::SPIR_KERNEL;
8411}
8412
Robert Lytton844aeeb2014-05-02 09:33:20 +00008413static bool appendType(SmallStringEnc &Enc, QualType QType,
8414 const CodeGen::CodeGenModule &CGM,
8415 TypeStringCache &TSC);
8416
8417/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008418/// Builds a SmallVector containing the encoded field types in declaration
8419/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008420static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8421 const RecordDecl *RD,
8422 const CodeGen::CodeGenModule &CGM,
8423 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008424 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008425 SmallStringEnc Enc;
8426 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008427 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008428 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008429 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008430 Enc += "b(";
8431 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008432 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008433 Enc += ':';
8434 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008435 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008436 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008437 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008438 Enc += ')';
8439 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008440 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008441 }
8442 return true;
8443}
8444
8445/// Appends structure and union types to Enc and adds encoding to cache.
8446/// Recursively calls appendType (via extractFieldType) for each field.
8447/// Union types have their fields ordered according to the ABI.
8448static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8449 const CodeGen::CodeGenModule &CGM,
8450 TypeStringCache &TSC, const IdentifierInfo *ID) {
8451 // Append the cached TypeString if we have one.
8452 StringRef TypeString = TSC.lookupStr(ID);
8453 if (!TypeString.empty()) {
8454 Enc += TypeString;
8455 return true;
8456 }
8457
8458 // Start to emit an incomplete TypeString.
8459 size_t Start = Enc.size();
8460 Enc += (RT->isUnionType()? 'u' : 's');
8461 Enc += '(';
8462 if (ID)
8463 Enc += ID->getName();
8464 Enc += "){";
8465
8466 // We collect all encoded fields and order as necessary.
8467 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008468 const RecordDecl *RD = RT->getDecl()->getDefinition();
8469 if (RD && !RD->field_empty()) {
8470 // An incomplete TypeString stub is placed in the cache for this RecordType
8471 // so that recursive calls to this RecordType will use it whilst building a
8472 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008473 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008474 std::string StubEnc(Enc.substr(Start).str());
8475 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8476 TSC.addIncomplete(ID, std::move(StubEnc));
8477 if (!extractFieldType(FE, RD, CGM, TSC)) {
8478 (void) TSC.removeIncomplete(ID);
8479 return false;
8480 }
8481 IsRecursive = TSC.removeIncomplete(ID);
8482 // The ABI requires unions to be sorted but not structures.
8483 // See FieldEncoding::operator< for sort algorithm.
8484 if (RT->isUnionType())
8485 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008486 // We can now complete the TypeString.
8487 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008488 for (unsigned I = 0; I != E; ++I) {
8489 if (I)
8490 Enc += ',';
8491 Enc += FE[I].str();
8492 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008493 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008494 Enc += '}';
8495 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8496 return true;
8497}
8498
8499/// Appends enum types to Enc and adds the encoding to the cache.
8500static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8501 TypeStringCache &TSC,
8502 const IdentifierInfo *ID) {
8503 // Append the cached TypeString if we have one.
8504 StringRef TypeString = TSC.lookupStr(ID);
8505 if (!TypeString.empty()) {
8506 Enc += TypeString;
8507 return true;
8508 }
8509
8510 size_t Start = Enc.size();
8511 Enc += "e(";
8512 if (ID)
8513 Enc += ID->getName();
8514 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008515
8516 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008517 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008518 SmallVector<FieldEncoding, 16> FE;
8519 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8520 ++I) {
8521 SmallStringEnc EnumEnc;
8522 EnumEnc += "m(";
8523 EnumEnc += I->getName();
8524 EnumEnc += "){";
8525 I->getInitVal().toString(EnumEnc);
8526 EnumEnc += '}';
8527 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8528 }
8529 std::sort(FE.begin(), FE.end());
8530 unsigned E = FE.size();
8531 for (unsigned I = 0; I != E; ++I) {
8532 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008533 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008534 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008535 }
8536 }
8537 Enc += '}';
8538 TSC.addIfComplete(ID, Enc.substr(Start), false);
8539 return true;
8540}
8541
8542/// Appends type's qualifier to Enc.
8543/// This is done prior to appending the type's encoding.
8544static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8545 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008546 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008547 int Lookup = 0;
8548 if (QT.isConstQualified())
8549 Lookup += 1<<0;
8550 if (QT.isRestrictQualified())
8551 Lookup += 1<<1;
8552 if (QT.isVolatileQualified())
8553 Lookup += 1<<2;
8554 Enc += Table[Lookup];
8555}
8556
8557/// Appends built-in types to Enc.
8558static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8559 const char *EncType;
8560 switch (BT->getKind()) {
8561 case BuiltinType::Void:
8562 EncType = "0";
8563 break;
8564 case BuiltinType::Bool:
8565 EncType = "b";
8566 break;
8567 case BuiltinType::Char_U:
8568 EncType = "uc";
8569 break;
8570 case BuiltinType::UChar:
8571 EncType = "uc";
8572 break;
8573 case BuiltinType::SChar:
8574 EncType = "sc";
8575 break;
8576 case BuiltinType::UShort:
8577 EncType = "us";
8578 break;
8579 case BuiltinType::Short:
8580 EncType = "ss";
8581 break;
8582 case BuiltinType::UInt:
8583 EncType = "ui";
8584 break;
8585 case BuiltinType::Int:
8586 EncType = "si";
8587 break;
8588 case BuiltinType::ULong:
8589 EncType = "ul";
8590 break;
8591 case BuiltinType::Long:
8592 EncType = "sl";
8593 break;
8594 case BuiltinType::ULongLong:
8595 EncType = "ull";
8596 break;
8597 case BuiltinType::LongLong:
8598 EncType = "sll";
8599 break;
8600 case BuiltinType::Float:
8601 EncType = "ft";
8602 break;
8603 case BuiltinType::Double:
8604 EncType = "d";
8605 break;
8606 case BuiltinType::LongDouble:
8607 EncType = "ld";
8608 break;
8609 default:
8610 return false;
8611 }
8612 Enc += EncType;
8613 return true;
8614}
8615
8616/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8617static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8618 const CodeGen::CodeGenModule &CGM,
8619 TypeStringCache &TSC) {
8620 Enc += "p(";
8621 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8622 return false;
8623 Enc += ')';
8624 return true;
8625}
8626
8627/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008628static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8629 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008630 const CodeGen::CodeGenModule &CGM,
8631 TypeStringCache &TSC, StringRef NoSizeEnc) {
8632 if (AT->getSizeModifier() != ArrayType::Normal)
8633 return false;
8634 Enc += "a(";
8635 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8636 CAT->getSize().toStringUnsigned(Enc);
8637 else
8638 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8639 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008640 // The Qualifiers should be attached to the type rather than the array.
8641 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008642 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8643 return false;
8644 Enc += ')';
8645 return true;
8646}
8647
8648/// Appends a function encoding to Enc, calling appendType for the return type
8649/// and the arguments.
8650static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8651 const CodeGen::CodeGenModule &CGM,
8652 TypeStringCache &TSC) {
8653 Enc += "f{";
8654 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8655 return false;
8656 Enc += "}(";
8657 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8658 // N.B. we are only interested in the adjusted param types.
8659 auto I = FPT->param_type_begin();
8660 auto E = FPT->param_type_end();
8661 if (I != E) {
8662 do {
8663 if (!appendType(Enc, *I, CGM, TSC))
8664 return false;
8665 ++I;
8666 if (I != E)
8667 Enc += ',';
8668 } while (I != E);
8669 if (FPT->isVariadic())
8670 Enc += ",va";
8671 } else {
8672 if (FPT->isVariadic())
8673 Enc += "va";
8674 else
8675 Enc += '0';
8676 }
8677 }
8678 Enc += ')';
8679 return true;
8680}
8681
8682/// Handles the type's qualifier before dispatching a call to handle specific
8683/// type encodings.
8684static bool appendType(SmallStringEnc &Enc, QualType QType,
8685 const CodeGen::CodeGenModule &CGM,
8686 TypeStringCache &TSC) {
8687
8688 QualType QT = QType.getCanonicalType();
8689
Robert Lytton6adb20f2014-06-05 09:06:21 +00008690 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8691 // The Qualifiers should be attached to the type rather than the array.
8692 // Thus we don't call appendQualifier() here.
8693 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8694
Robert Lytton844aeeb2014-05-02 09:33:20 +00008695 appendQualifier(Enc, QT);
8696
8697 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8698 return appendBuiltinType(Enc, BT);
8699
Robert Lytton844aeeb2014-05-02 09:33:20 +00008700 if (const PointerType *PT = QT->getAs<PointerType>())
8701 return appendPointerType(Enc, PT, CGM, TSC);
8702
8703 if (const EnumType *ET = QT->getAs<EnumType>())
8704 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8705
8706 if (const RecordType *RT = QT->getAsStructureType())
8707 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8708
8709 if (const RecordType *RT = QT->getAsUnionType())
8710 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8711
8712 if (const FunctionType *FT = QT->getAs<FunctionType>())
8713 return appendFunctionType(Enc, FT, CGM, TSC);
8714
8715 return false;
8716}
8717
8718static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8719 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8720 if (!D)
8721 return false;
8722
8723 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8724 if (FD->getLanguageLinkage() != CLanguageLinkage)
8725 return false;
8726 return appendType(Enc, FD->getType(), CGM, TSC);
8727 }
8728
8729 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8730 if (VD->getLanguageLinkage() != CLanguageLinkage)
8731 return false;
8732 QualType QT = VD->getType().getCanonicalType();
8733 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8734 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008735 // The Qualifiers should be attached to the type rather than the array.
8736 // Thus we don't call appendQualifier() here.
8737 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008738 }
8739 return appendType(Enc, QT, CGM, TSC);
8740 }
8741 return false;
8742}
8743
8744
Robert Lytton0e076492013-08-13 09:43:10 +00008745//===----------------------------------------------------------------------===//
8746// Driver code
8747//===----------------------------------------------------------------------===//
8748
Rafael Espindola9f834732014-09-19 01:54:22 +00008749bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008750 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008751}
8752
Chris Lattner2b037972010-07-29 02:01:43 +00008753const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008754 if (TheTargetCodeGenInfo)
8755 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008756
Reid Kleckner9305fd12016-04-13 23:37:17 +00008757 // Helper to set the unique_ptr while still keeping the return value.
8758 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8759 this->TheTargetCodeGenInfo.reset(P);
8760 return *P;
8761 };
8762
John McCallc8e01702013-04-16 22:48:15 +00008763 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008764 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008765 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008766 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008767
Derek Schuff09338a22012-09-06 17:37:28 +00008768 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008769 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008770 case llvm::Triple::mips:
8771 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008772 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008773 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8774 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008775
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008776 case llvm::Triple::mips64:
8777 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008778 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008779
Dylan McKaye8232d72017-02-08 05:09:26 +00008780 case llvm::Triple::avr:
8781 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8782
Tim Northover25e8a672014-05-24 12:51:25 +00008783 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008784 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008785 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008786 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008787 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008788 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008789 return SetCGInfo(
8790 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008791
Reid Kleckner9305fd12016-04-13 23:37:17 +00008792 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008793 }
8794
Dan Gohmanc2853072015-09-03 22:51:53 +00008795 case llvm::Triple::wasm32:
8796 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008797 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008798
Daniel Dunbard59655c2009-09-12 00:59:49 +00008799 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008800 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008801 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008802 case llvm::Triple::thumbeb: {
8803 if (Triple.getOS() == llvm::Triple::Win32) {
8804 return SetCGInfo(
8805 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008806 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008807
Reid Kleckner9305fd12016-04-13 23:37:17 +00008808 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8809 StringRef ABIStr = getTarget().getABI();
8810 if (ABIStr == "apcs-gnu")
8811 Kind = ARMABIInfo::APCS;
8812 else if (ABIStr == "aapcs16")
8813 Kind = ARMABIInfo::AAPCS16_VFP;
8814 else if (CodeGenOpts.FloatABI == "hard" ||
8815 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008816 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008817 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008818 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008819 Kind = ARMABIInfo::AAPCS_VFP;
8820
8821 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8822 }
8823
John McCallea8d8bb2010-03-11 00:10:12 +00008824 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008825 return SetCGInfo(
8826 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008827 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008828 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008829 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008830 if (getTarget().getABI() == "elfv2")
8831 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008832 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008833 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008834
Hal Finkel415c2a32016-10-02 02:10:45 +00008835 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8836 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008837 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008838 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008839 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008840 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008841 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008842 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008843 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008844 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008845 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008846
Hal Finkel415c2a32016-10-02 02:10:45 +00008847 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8848 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008849 }
John McCallea8d8bb2010-03-11 00:10:12 +00008850
Peter Collingbournec947aae2012-05-20 23:28:41 +00008851 case llvm::Triple::nvptx:
8852 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008853 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008854
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008855 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008856 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008857
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008858 case llvm::Triple::systemz: {
8859 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008860 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008861 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008862
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008863 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008864 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008865 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008866
Eli Friedman33465822011-07-08 23:31:17 +00008867 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008868 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008869 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008870 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008871 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008872
John McCall1fe2a8c2013-06-18 02:46:29 +00008873 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008874 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8875 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8876 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008877 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008878 return SetCGInfo(new X86_32TargetCodeGenInfo(
8879 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8880 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8881 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008882 }
Eli Friedman33465822011-07-08 23:31:17 +00008883 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008884
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008885 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008886 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008887 X86AVXABILevel AVXLevel =
8888 (ABI == "avx512"
8889 ? X86AVXABILevel::AVX512
8890 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008891
Chris Lattner04dc9572010-08-31 16:44:54 +00008892 switch (Triple.getOS()) {
8893 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008894 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008895 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008896 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008897 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008898 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008899 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008900 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008901 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008902 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008903 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008904 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008905 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008906 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008907 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008908 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008909 case llvm::Triple::sparc:
8910 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008911 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008912 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008913 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008914 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008915 case llvm::Triple::spir:
8916 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008917 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008918 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008919}