blob: 44647a6fc558f052a66422e11c1447a2450ed10d [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"
Daniel Dunbare3532f82009-08-24 08:52:16 +000025#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000028#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000030
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000034// Helper for coercing an aggregate argument or return value into an integer
35// array of the same size (including padding) and alignment. This alternate
36// coercion happens only for the RenderScript ABI and can be removed after
37// runtimes that rely on it are no longer supported.
38//
39// RenderScript assumes that the size of the argument / return value in the IR
40// is the same as the size of the corresponding qualified type. This helper
41// coerces the aggregate type into an array of the same size (including
42// padding). This coercion is used in lieu of expansion of struct members or
43// other canonical coercions that return a coerced-type of larger size.
44//
45// Ty - The argument / return value type
46// Context - The associated ASTContext
47// LLVMContext - The associated LLVMContext
48static ABIArgInfo coerceToIntArray(QualType Ty,
49 ASTContext &Context,
50 llvm::LLVMContext &LLVMContext) {
51 // Alignment and Size are measured in bits.
52 const uint64_t Size = Context.getTypeSize(Ty);
53 const uint64_t Alignment = Context.getTypeAlign(Ty);
54 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
55 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
56 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
57}
58
John McCall943fae92010-05-27 06:19:26 +000059static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
60 llvm::Value *Array,
61 llvm::Value *Value,
62 unsigned FirstIndex,
63 unsigned LastIndex) {
64 // Alternatively, we could emit this as a loop in the source.
65 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000066 llvm::Value *Cell =
67 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000068 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000069 }
70}
71
John McCalla1dee5302010-08-22 10:59:02 +000072static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000073 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000074 T->isMemberFunctionPointerType();
75}
76
John McCall7f416cc2015-09-08 08:05:57 +000077ABIArgInfo
78ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
79 llvm::Type *Padding) const {
80 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
81 ByRef, Realign, Padding);
82}
83
84ABIArgInfo
85ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
86 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
87 /*ByRef*/ false, Realign);
88}
89
Charles Davisc7d5c942015-09-17 20:55:33 +000090Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
91 QualType Ty) const {
92 return Address::invalid();
93}
94
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000095ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000096
John McCall12f23522016-04-04 18:33:08 +000097/// Does the given lowering require more than the given number of
98/// registers when expanded?
99///
100/// This is intended to be the basis of a reasonable basic implementation
101/// of should{Pass,Return}IndirectlyForSwift.
102///
103/// For most targets, a limit of four total registers is reasonable; this
104/// limits the amount of code required in order to move around the value
105/// in case it wasn't produced immediately prior to the call by the caller
106/// (or wasn't produced in exactly the right registers) or isn't used
107/// immediately within the callee. But some targets may need to further
108/// limit the register count due to an inability to support that many
109/// return registers.
110static bool occupiesMoreThan(CodeGenTypes &cgt,
111 ArrayRef<llvm::Type*> scalarTypes,
112 unsigned maxAllRegisters) {
113 unsigned intCount = 0, fpCount = 0;
114 for (llvm::Type *type : scalarTypes) {
115 if (type->isPointerTy()) {
116 intCount++;
117 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
118 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
119 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
120 } else {
121 assert(type->isVectorTy() || type->isFloatingPointTy());
122 fpCount++;
123 }
124 }
125
126 return (intCount + fpCount > maxAllRegisters);
127}
128
129bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
130 llvm::Type *eltTy,
131 unsigned numElts) const {
132 // The default implementation of this assumes that the target guarantees
133 // 128-bit SIMD support but nothing more.
134 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
135}
136
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000137static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000138 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
140 if (!RD)
141 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000142 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000143}
144
145static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000146 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000147 const RecordType *RT = T->getAs<RecordType>();
148 if (!RT)
149 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000150 return getRecordArgABI(RT, CXXABI);
151}
152
Reid Klecknerb1be6832014-11-15 01:41:41 +0000153/// Pass transparent unions as if they were the type of the first element. Sema
154/// should ensure that all elements of the union have the same "machine type".
155static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
156 if (const RecordType *UT = Ty->getAsUnionType()) {
157 const RecordDecl *UD = UT->getDecl();
158 if (UD->hasAttr<TransparentUnionAttr>()) {
159 assert(!UD->field_empty() && "sema created an empty transparent union");
160 return UD->field_begin()->getType();
161 }
162 }
163 return Ty;
164}
165
Mark Lacey3825e832013-10-06 01:33:34 +0000166CGCXXABI &ABIInfo::getCXXABI() const {
167 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000168}
169
Chris Lattner2b037972010-07-29 02:01:43 +0000170ASTContext &ABIInfo::getContext() const {
171 return CGT.getContext();
172}
173
174llvm::LLVMContext &ABIInfo::getVMContext() const {
175 return CGT.getLLVMContext();
176}
177
Micah Villmowdd31ca12012-10-08 16:25:52 +0000178const llvm::DataLayout &ABIInfo::getDataLayout() const {
179 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000180}
181
John McCallc8e01702013-04-16 22:48:15 +0000182const TargetInfo &ABIInfo::getTarget() const {
183 return CGT.getTarget();
184}
Chris Lattner2b037972010-07-29 02:01:43 +0000185
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000186bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
187
Reid Klecknere9f6a712014-10-31 17:10:41 +0000188bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
189 return false;
190}
191
192bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
193 uint64_t Members) const {
194 return false;
195}
196
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000197bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
198 return false;
199}
200
Yaron Kerencdae9412016-01-29 19:38:18 +0000201LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000202 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000203 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000204 switch (TheKind) {
205 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000206 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000207 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000208 Ty->print(OS);
209 else
210 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000212 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000213 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000214 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000216 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000218 case InAlloca:
219 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
220 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000221 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000222 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000223 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000224 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000225 break;
226 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000227 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 break;
John McCallf26e73d2016-03-11 04:30:43 +0000229 case CoerceAndExpand:
230 OS << "CoerceAndExpand Type=";
231 getCoerceAndExpandType()->print(OS);
232 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000234 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235}
236
Petar Jovanovic402257b2015-12-04 00:26:47 +0000237// Dynamically round a pointer up to a multiple of the given alignment.
238static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
239 llvm::Value *Ptr,
240 CharUnits Align) {
241 llvm::Value *PtrAsInt = Ptr;
242 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
243 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
244 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
245 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
246 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
247 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
248 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
249 Ptr->getType(),
250 Ptr->getName() + ".aligned");
251 return PtrAsInt;
252}
253
John McCall7f416cc2015-09-08 08:05:57 +0000254/// Emit va_arg for a platform using the common void* representation,
255/// where arguments are simply emitted in an array of slots on the stack.
256///
257/// This version implements the core direct-value passing rules.
258///
259/// \param SlotSize - The size and alignment of a stack slot.
260/// Each argument will be allocated to a multiple of this number of
261/// slots, and all the slots will be aligned to this value.
262/// \param AllowHigherAlign - The slot alignment is not a cap;
263/// an argument type with an alignment greater than the slot size
264/// will be emitted on a higher-alignment address, potentially
265/// leaving one or more empty slots behind as padding. If this
266/// is false, the returned address might be less-aligned than
267/// DirectAlign.
268static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
269 Address VAListAddr,
270 llvm::Type *DirectTy,
271 CharUnits DirectSize,
272 CharUnits DirectAlign,
273 CharUnits SlotSize,
274 bool AllowHigherAlign) {
275 // Cast the element type to i8* if necessary. Some platforms define
276 // va_list as a struct containing an i8* instead of just an i8*.
277 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
278 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
279
280 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
281
282 // If the CC aligns values higher than the slot size, do so if needed.
283 Address Addr = Address::invalid();
284 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000285 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
286 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000287 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000288 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000289 }
290
291 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000292 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000293 llvm::Value *NextPtr =
294 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
295 "argp.next");
296 CGF.Builder.CreateStore(NextPtr, VAListAddr);
297
298 // If the argument is smaller than a slot, and this is a big-endian
299 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000300 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
301 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000302 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
303 }
304
305 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
306 return Addr;
307}
308
309/// Emit va_arg for a platform using the common void* representation,
310/// where arguments are simply emitted in an array of slots on the stack.
311///
312/// \param IsIndirect - Values of this type are passed indirectly.
313/// \param ValueInfo - The size and alignment of this type, generally
314/// computed with getContext().getTypeInfoInChars(ValueTy).
315/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
316/// Each argument will be allocated to a multiple of this number of
317/// slots, and all the slots will be aligned to this value.
318/// \param AllowHigherAlign - The slot alignment is not a cap;
319/// an argument type with an alignment greater than the slot size
320/// will be emitted on a higher-alignment address, potentially
321/// leaving one or more empty slots behind as padding.
322static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
323 QualType ValueTy, bool IsIndirect,
324 std::pair<CharUnits, CharUnits> ValueInfo,
325 CharUnits SlotSizeAndAlign,
326 bool AllowHigherAlign) {
327 // The size and alignment of the value that was passed directly.
328 CharUnits DirectSize, DirectAlign;
329 if (IsIndirect) {
330 DirectSize = CGF.getPointerSize();
331 DirectAlign = CGF.getPointerAlign();
332 } else {
333 DirectSize = ValueInfo.first;
334 DirectAlign = ValueInfo.second;
335 }
336
337 // Cast the address we've calculated to the right type.
338 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
339 if (IsIndirect)
340 DirectTy = DirectTy->getPointerTo(0);
341
342 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
343 DirectSize, DirectAlign,
344 SlotSizeAndAlign,
345 AllowHigherAlign);
346
347 if (IsIndirect) {
348 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
349 }
350
351 return Addr;
352
353}
354
355static Address emitMergePHI(CodeGenFunction &CGF,
356 Address Addr1, llvm::BasicBlock *Block1,
357 Address Addr2, llvm::BasicBlock *Block2,
358 const llvm::Twine &Name = "") {
359 assert(Addr1.getType() == Addr2.getType());
360 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
361 PHI->addIncoming(Addr1.getPointer(), Block1);
362 PHI->addIncoming(Addr2.getPointer(), Block2);
363 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
364 return Address(PHI, Align);
365}
366
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000367TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
368
John McCall3480ef22011-08-30 01:42:09 +0000369// If someone can figure out a general rule for this, that would be great.
370// It's probably just doomed to be platform-dependent, though.
371unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
372 // Verified for:
373 // x86-64 FreeBSD, Linux, Darwin
374 // x86-32 FreeBSD, Linux, Darwin
375 // PowerPC Linux, Darwin
376 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000377 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000378 return 32;
379}
380
John McCalla729c622012-02-17 03:33:10 +0000381bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
382 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000383 // The following conventions are known to require this to be false:
384 // x86_stdcall
385 // MIPS
386 // For everything else, we just prefer false unless we opt out.
387 return false;
388}
389
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000390void
391TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
392 llvm::SmallString<24> &Opt) const {
393 // This assumes the user is passing a library name like "rt" instead of a
394 // filename like "librt.a/so", and that they don't care whether it's static or
395 // dynamic.
396 Opt = "-l";
397 Opt += Lib;
398}
399
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000400unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000401 // OpenCL kernels are called via an explicit runtime API with arguments
402 // set with clSetKernelArg(), not as normal sub-functions.
403 // Return SPIR_KERNEL by default as the kernel calling convention to
404 // ensure the fingerprint is fixed such way that each OpenCL argument
405 // gets one matching argument in the produced kernel function argument
406 // list to enable feasible implementation of clSetKernelArg() with
407 // aggregates etc. In case we would use the default C calling conv here,
408 // clSetKernelArg() might break depending on the target-specific
409 // conventions; different targets might split structs passed as values
410 // to multiple function arguments etc.
411 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000412}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000413
Yaxun Liu402804b2016-12-15 08:09:08 +0000414llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
415 llvm::PointerType *T, QualType QT) const {
416 return llvm::ConstantPointerNull::get(T);
417}
418
Yaxun Liucbf647c2017-07-08 13:24:52 +0000419unsigned TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
420 const VarDecl *D) const {
421 assert(!CGM.getLangOpts().OpenCL &&
422 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
423 "Address space agnostic languages only");
Yaxun Liu7bce6422017-07-08 19:13:41 +0000424 return D ? D->getType().getAddressSpace()
425 : static_cast<unsigned>(LangAS::Default);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000426}
427
Yaxun Liu402804b2016-12-15 08:09:08 +0000428llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000429 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
430 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000431 // Since target may map different address spaces in AST to the same address
432 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000433 if (auto *C = dyn_cast<llvm::Constant>(Src))
434 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000435 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000436}
437
Yaxun Liucbf647c2017-07-08 13:24:52 +0000438llvm::Constant *
439TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
440 unsigned SrcAddr, unsigned DestAddr,
441 llvm::Type *DestTy) const {
442 // Since target may map different address spaces in AST to the same address
443 // space, an address space conversion may end up as a bitcast.
444 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
445}
446
Yaxun Liu39195062017-08-04 18:16:31 +0000447llvm::SyncScope::ID
448TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
449 return C.getOrInsertSyncScopeID(""); /* default sync scope */
450}
451
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000452static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000453
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000454/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000455/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000456static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
457 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000458 if (FD->isUnnamedBitfield())
459 return true;
460
461 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000462
Eli Friedman0b3f2012011-11-18 03:47:20 +0000463 // Constant arrays of empty records count as empty, strip them off.
464 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000465 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000466 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
467 if (AT->getSize() == 0)
468 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000469 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000470 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000472 const RecordType *RT = FT->getAs<RecordType>();
473 if (!RT)
474 return false;
475
476 // C++ record fields are never empty, at least in the Itanium ABI.
477 //
478 // FIXME: We should use a predicate for whether this behavior is true in the
479 // current ABI.
480 if (isa<CXXRecordDecl>(RT->getDecl()))
481 return false;
482
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000483 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000484}
485
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000486/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000487/// fields. Note that a structure with a flexible array member is not
488/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000489static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000490 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000492 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000493 const RecordDecl *RD = RT->getDecl();
494 if (RD->hasFlexibleArrayMember())
495 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000496
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000497 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000498 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000499 for (const auto &I : CXXRD->bases())
500 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000501 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000502
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000503 for (const auto *I : RD->fields())
504 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000505 return false;
506 return true;
507}
508
509/// isSingleElementStruct - Determine if a structure is a "single
510/// element struct", i.e. it has exactly one non-empty field or
511/// exactly one field which is itself a single element
512/// struct. Structures with flexible array members are never
513/// considered single element structs.
514///
515/// \return The field declaration for the single non-empty field, if
516/// it exists.
517static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000518 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000519 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000520 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000521
522 const RecordDecl *RD = RT->getDecl();
523 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000524 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525
Craig Topper8a13c412014-05-21 05:09:00 +0000526 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000527
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000528 // If this is a C++ record, check the bases first.
529 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000530 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000531 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000532 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000533 continue;
534
535 // If we already found an element then this isn't a single-element struct.
536 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000537 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000538
539 // If this is non-empty and not a single element struct, the composite
540 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000541 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000542 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000544 }
545 }
546
547 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000548 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000549 QualType FT = FD->getType();
550
551 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000552 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000553 continue;
554
555 // If we already found an element then this isn't a single-element
556 // struct.
557 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000558 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559
560 // Treat single element arrays as the element.
561 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
562 if (AT->getSize().getZExtValue() != 1)
563 break;
564 FT = AT->getElementType();
565 }
566
John McCalla1dee5302010-08-22 10:59:02 +0000567 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568 Found = FT.getTypePtr();
569 } else {
570 Found = isSingleElementStruct(FT, Context);
571 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000572 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000573 }
574 }
575
Eli Friedmanee945342011-11-18 01:25:50 +0000576 // We don't consider a struct a single-element struct if it has
577 // padding beyond the element type.
578 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000579 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000580
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000581 return Found;
582}
583
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000584namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000585Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
586 const ABIArgInfo &AI) {
587 // This default implementation defers to the llvm backend's va_arg
588 // instruction. It can handle only passing arguments directly
589 // (typically only handled in the backend for primitive types), or
590 // aggregates passed indirectly by pointer (NOTE: if the "byval"
591 // flag has ABI impact in the callee, this implementation cannot
592 // work.)
593
594 // Only a few cases are covered here at the moment -- those needed
595 // by the default abi.
596 llvm::Value *Val;
597
598 if (AI.isIndirect()) {
599 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000600 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000601 assert(
602 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000603 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000604
605 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
606 CharUnits TyAlignForABI = TyInfo.second;
607
608 llvm::Type *BaseTy =
609 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
610 llvm::Value *Addr =
611 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
612 return Address(Addr, TyAlignForABI);
613 } else {
614 assert((AI.isDirect() || AI.isExtend()) &&
615 "Unexpected ArgInfo Kind in generic VAArg emitter!");
616
617 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000618 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000619 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000620 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000621 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000622 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000623 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000624 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000625
626 Address Temp = CGF.CreateMemTemp(Ty, "varet");
627 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
628 CGF.Builder.CreateStore(Val, Temp);
629 return Temp;
630 }
631}
632
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000633/// DefaultABIInfo - The default implementation for ABI specific
634/// details. This implementation provides information which results in
635/// self-consistent and sensible LLVM IR generation, but does not
636/// conform to any particular ABI.
637class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000638public:
639 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000640
Chris Lattner458b2aa2010-07-29 02:16:43 +0000641 ABIArgInfo classifyReturnType(QualType RetTy) const;
642 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000643
Craig Topper4f12f102014-03-12 06:41:41 +0000644 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000645 if (!getCXXABI().classifyReturnType(FI))
646 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000647 for (auto &I : FI.arguments())
648 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000649 }
650
John McCall7f416cc2015-09-08 08:05:57 +0000651 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000652 QualType Ty) const override {
653 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
654 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000655};
656
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000657class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
658public:
Chris Lattner2b037972010-07-29 02:01:43 +0000659 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
660 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000661};
662
Chris Lattner458b2aa2010-07-29 02:16:43 +0000663ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000664 Ty = useFirstFieldIfTransparentUnion(Ty);
665
666 if (isAggregateTypeForABI(Ty)) {
667 // Records with non-trivial destructors/copy-constructors should not be
668 // passed by value.
669 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000670 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000671
John McCall7f416cc2015-09-08 08:05:57 +0000672 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000673 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000674
Chris Lattner9723d6c2010-03-11 18:19:55 +0000675 // Treat an enum type as its underlying type.
676 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
677 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000678
Chris Lattner9723d6c2010-03-11 18:19:55 +0000679 return (Ty->isPromotableIntegerType() ?
680 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000681}
682
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000683ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
684 if (RetTy->isVoidType())
685 return ABIArgInfo::getIgnore();
686
687 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000688 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000689
690 // Treat an enum type as its underlying type.
691 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
692 RetTy = EnumTy->getDecl()->getIntegerType();
693
694 return (RetTy->isPromotableIntegerType() ?
695 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
696}
697
Derek Schuff09338a22012-09-06 17:37:28 +0000698//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000699// WebAssembly ABI Implementation
700//
701// This is a very simple ABI that relies a lot on DefaultABIInfo.
702//===----------------------------------------------------------------------===//
703
704class WebAssemblyABIInfo final : public DefaultABIInfo {
705public:
706 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
707 : DefaultABIInfo(CGT) {}
708
709private:
710 ABIArgInfo classifyReturnType(QualType RetTy) const;
711 ABIArgInfo classifyArgumentType(QualType Ty) const;
712
713 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000714 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000715 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000716 void computeInfo(CGFunctionInfo &FI) const override {
717 if (!getCXXABI().classifyReturnType(FI))
718 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
719 for (auto &Arg : FI.arguments())
720 Arg.info = classifyArgumentType(Arg.type);
721 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000722
723 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
724 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000725};
726
727class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
728public:
729 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
730 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
731};
732
733/// \brief Classify argument of given type \p Ty.
734ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
735 Ty = useFirstFieldIfTransparentUnion(Ty);
736
737 if (isAggregateTypeForABI(Ty)) {
738 // Records with non-trivial destructors/copy-constructors should not be
739 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000741 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000742 // Ignore empty structs/unions.
743 if (isEmptyRecord(getContext(), Ty, true))
744 return ABIArgInfo::getIgnore();
745 // Lower single-element structs to just pass a regular value. TODO: We
746 // could do reasonable-size multiple-element structs too, using getExpand(),
747 // though watch out for things like bitfields.
748 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
749 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000750 }
751
752 // Otherwise just do the default thing.
753 return DefaultABIInfo::classifyArgumentType(Ty);
754}
755
756ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
757 if (isAggregateTypeForABI(RetTy)) {
758 // Records with non-trivial destructors/copy-constructors should not be
759 // returned by value.
760 if (!getRecordArgABI(RetTy, getCXXABI())) {
761 // Ignore empty structs/unions.
762 if (isEmptyRecord(getContext(), RetTy, true))
763 return ABIArgInfo::getIgnore();
764 // Lower single-element structs to just return a regular value. TODO: We
765 // could do reasonable-size multiple-element structs too, using
766 // ABIArgInfo::getDirect().
767 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
768 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
769 }
770 }
771
772 // Otherwise just do the default thing.
773 return DefaultABIInfo::classifyReturnType(RetTy);
774}
775
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000776Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
777 QualType Ty) const {
778 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
779 getContext().getTypeInfoInChars(Ty),
780 CharUnits::fromQuantity(4),
781 /*AllowHigherAlign=*/ true);
782}
783
Dan Gohmanc2853072015-09-03 22:51:53 +0000784//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000785// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000786//
787// This is a simplified version of the x86_32 ABI. Arguments and return values
788// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000789//===----------------------------------------------------------------------===//
790
791class PNaClABIInfo : public ABIInfo {
792 public:
793 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
794
795 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000796 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000797
Craig Topper4f12f102014-03-12 06:41:41 +0000798 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000799 Address EmitVAArg(CodeGenFunction &CGF,
800 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000801};
802
803class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
804 public:
805 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
806 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
807};
808
809void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000810 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000811 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
812
Reid Kleckner40ca9132014-05-13 22:05:45 +0000813 for (auto &I : FI.arguments())
814 I.info = classifyArgumentType(I.type);
815}
Derek Schuff09338a22012-09-06 17:37:28 +0000816
John McCall7f416cc2015-09-08 08:05:57 +0000817Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
818 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000819 // The PNaCL ABI is a bit odd, in that varargs don't use normal
820 // function classification. Structs get passed directly for varargs
821 // functions, through a rewriting transform in
822 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
823 // this target to actually support a va_arg instructions with an
824 // aggregate type, unlike other targets.
825 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000826}
827
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000828/// \brief Classify argument of given type \p Ty.
829ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000830 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000831 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000832 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
833 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000834 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
835 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000836 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000837 } else if (Ty->isFloatingType()) {
838 // Floating-point types don't go inreg.
839 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000840 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000841
842 return (Ty->isPromotableIntegerType() ?
843 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000844}
845
846ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
847 if (RetTy->isVoidType())
848 return ABIArgInfo::getIgnore();
849
Eli Benderskye20dad62013-04-04 22:49:35 +0000850 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000851 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000852 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000853
854 // Treat an enum type as its underlying type.
855 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
856 RetTy = EnumTy->getDecl()->getIntegerType();
857
858 return (RetTy->isPromotableIntegerType() ?
859 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
860}
861
Chad Rosier651c1832013-03-25 21:00:27 +0000862/// IsX86_MMXType - Return true if this is an MMX type.
863bool IsX86_MMXType(llvm::Type *IRType) {
864 // 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 +0000865 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
866 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
867 IRType->getScalarSizeInBits() != 64;
868}
869
Jay Foad7c57be32011-07-11 09:56:20 +0000870static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000871 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000872 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000873 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
874 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
875 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000876 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000877 }
878
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000879 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000880 }
881
882 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000883 return Ty;
884}
885
Reid Kleckner80944df2014-10-31 22:00:51 +0000886/// Returns true if this type can be passed in SSE registers with the
887/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
888static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
889 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000890 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
891 if (BT->getKind() == BuiltinType::LongDouble) {
892 if (&Context.getTargetInfo().getLongDoubleFormat() ==
893 &llvm::APFloat::x87DoubleExtended())
894 return false;
895 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000896 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000897 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000898 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
899 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
900 // registers specially.
901 unsigned VecSize = Context.getTypeSize(VT);
902 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
903 return true;
904 }
905 return false;
906}
907
908/// Returns true if this aggregate is small enough to be passed in SSE registers
909/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
910static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
911 return NumMembers <= 4;
912}
913
Erich Keane521ed962017-01-05 00:20:51 +0000914/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
915static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
916 auto AI = ABIArgInfo::getDirect(T);
917 AI.setInReg(true);
918 AI.setCanBeFlattened(false);
919 return AI;
920}
921
Chris Lattner0cf24192010-06-28 20:05:43 +0000922//===----------------------------------------------------------------------===//
923// X86-32 ABI Implementation
924//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000925
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926/// \brief Similar to llvm::CCState, but for Clang.
927struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000928 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000929
930 unsigned CC;
931 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000932 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000933};
934
Erich Keane521ed962017-01-05 00:20:51 +0000935enum {
936 // Vectorcall only allows the first 6 parameters to be passed in registers.
937 VectorcallMaxParamNumAsReg = 6
938};
939
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000940/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000941class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000942 enum Class {
943 Integer,
944 Float
945 };
946
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000947 static const unsigned MinABIStackAlignInBytes = 4;
948
David Chisnallde3a0692009-08-17 23:08:21 +0000949 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000950 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000951 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000952 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000953 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000954 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000955
956 static bool isRegisterSize(unsigned Size) {
957 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
958 }
959
Reid Kleckner80944df2014-10-31 22:00:51 +0000960 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
961 // FIXME: Assumes vectorcall is in use.
962 return isX86VectorTypeForVectorCall(getContext(), Ty);
963 }
964
965 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
966 uint64_t NumMembers) const override {
967 // FIXME: Assumes vectorcall is in use.
968 return isX86VectorCallAggregateSmallEnough(NumMembers);
969 }
970
Reid Kleckner40ca9132014-05-13 22:05:45 +0000971 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000972
Daniel Dunbar557893d2010-04-21 19:10:51 +0000973 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
974 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
976
John McCall7f416cc2015-09-08 08:05:57 +0000977 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000978
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000979 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000980 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000981
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000982 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000983 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000985
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000986 /// \brief Updates the number of available free registers, returns
987 /// true if any registers were allocated.
988 bool updateFreeRegs(QualType Ty, CCState &State) const;
989
990 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
991 bool &NeedsPadding) const;
992 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000993
Reid Kleckner04046052016-05-02 17:41:07 +0000994 bool canExpandIndirectArgument(QualType Ty) const;
995
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000996 /// \brief Rewrite the function info so that all memory arguments use
997 /// inalloca.
998 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
999
1000 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001001 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001002 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001003 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1004 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001005
Rafael Espindola75419dc2012-07-23 23:30:29 +00001006public:
1007
Craig Topper4f12f102014-03-12 06:41:41 +00001008 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001009 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1010 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001011
Michael Kupersteindc745202015-10-19 07:52:25 +00001012 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1013 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001014 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001015 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001016 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1017 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001018 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001019 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001020 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001021
1022 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1023 ArrayRef<llvm::Type*> scalars,
1024 bool asReturnValue) const override {
1025 // LLVM's x86-32 lowering currently only assigns up to three
1026 // integer registers and three fp registers. Oddly, it'll use up to
1027 // four vector registers for vectors, but those can overlap with the
1028 // scalar registers.
1029 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1030 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001031
1032 bool isSwiftErrorInRegister() const override {
1033 // x86-32 lowering does not support passing swifterror in a register.
1034 return false;
1035 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001037
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001038class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1039public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001040 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1041 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001042 unsigned NumRegisterParameters, bool SoftFloatABI)
1043 : TargetCodeGenInfo(new X86_32ABIInfo(
1044 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1045 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001046
John McCall1fe2a8c2013-06-18 02:46:29 +00001047 static bool isStructReturnInRegABI(
1048 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1049
Eric Christopher162c91c2015-06-05 22:03:00 +00001050 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001051 CodeGen::CodeGenModule &CGM,
1052 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001053
Craig Topper4f12f102014-03-12 06:41:41 +00001054 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001055 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001056 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001057 return 4;
1058 }
1059
1060 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001061 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001062
Jay Foad7c57be32011-07-11 09:56:20 +00001063 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001064 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001065 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001066 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1067 }
1068
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001069 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1070 std::string &Constraints,
1071 std::vector<llvm::Type *> &ResultRegTypes,
1072 std::vector<llvm::Type *> &ResultTruncRegTypes,
1073 std::vector<LValue> &ResultRegDests,
1074 std::string &AsmString,
1075 unsigned NumOutputs) const override;
1076
Craig Topper4f12f102014-03-12 06:41:41 +00001077 llvm::Constant *
1078 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001079 unsigned Sig = (0xeb << 0) | // jmp rel8
1080 (0x06 << 8) | // .+0x08
1081 ('F' << 16) |
1082 ('T' << 24);
1083 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1084 }
John McCall01391782016-02-05 21:37:38 +00001085
1086 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1087 return "movl\t%ebp, %ebp"
1088 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1089 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001090};
1091
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001092}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001093
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001094/// Rewrite input constraint references after adding some output constraints.
1095/// In the case where there is one output and one input and we add one output,
1096/// we need to replace all operand references greater than or equal to 1:
1097/// mov $0, $1
1098/// mov eax, $1
1099/// The result will be:
1100/// mov $0, $2
1101/// mov eax, $2
1102static void rewriteInputConstraintReferences(unsigned FirstIn,
1103 unsigned NumNewOuts,
1104 std::string &AsmString) {
1105 std::string Buf;
1106 llvm::raw_string_ostream OS(Buf);
1107 size_t Pos = 0;
1108 while (Pos < AsmString.size()) {
1109 size_t DollarStart = AsmString.find('$', Pos);
1110 if (DollarStart == std::string::npos)
1111 DollarStart = AsmString.size();
1112 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1113 if (DollarEnd == std::string::npos)
1114 DollarEnd = AsmString.size();
1115 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1116 Pos = DollarEnd;
1117 size_t NumDollars = DollarEnd - DollarStart;
1118 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1119 // We have an operand reference.
1120 size_t DigitStart = Pos;
1121 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1122 if (DigitEnd == std::string::npos)
1123 DigitEnd = AsmString.size();
1124 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1125 unsigned OperandIndex;
1126 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1127 if (OperandIndex >= FirstIn)
1128 OperandIndex += NumNewOuts;
1129 OS << OperandIndex;
1130 } else {
1131 OS << OperandStr;
1132 }
1133 Pos = DigitEnd;
1134 }
1135 }
1136 AsmString = std::move(OS.str());
1137}
1138
1139/// Add output constraints for EAX:EDX because they are return registers.
1140void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1141 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1142 std::vector<llvm::Type *> &ResultRegTypes,
1143 std::vector<llvm::Type *> &ResultTruncRegTypes,
1144 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1145 unsigned NumOutputs) const {
1146 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1147
1148 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1149 // larger.
1150 if (!Constraints.empty())
1151 Constraints += ',';
1152 if (RetWidth <= 32) {
1153 Constraints += "={eax}";
1154 ResultRegTypes.push_back(CGF.Int32Ty);
1155 } else {
1156 // Use the 'A' constraint for EAX:EDX.
1157 Constraints += "=A";
1158 ResultRegTypes.push_back(CGF.Int64Ty);
1159 }
1160
1161 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1162 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1163 ResultTruncRegTypes.push_back(CoerceTy);
1164
1165 // Coerce the integer by bitcasting the return slot pointer.
1166 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1167 CoerceTy->getPointerTo()));
1168 ResultRegDests.push_back(ReturnSlot);
1169
1170 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1171}
1172
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001173/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001174/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001175bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1176 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001177 uint64_t Size = Context.getTypeSize(Ty);
1178
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001179 // For i386, type must be register sized.
1180 // For the MCU ABI, it only needs to be <= 8-byte
1181 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1182 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001183
1184 if (Ty->isVectorType()) {
1185 // 64- and 128- bit vectors inside structures are not returned in
1186 // registers.
1187 if (Size == 64 || Size == 128)
1188 return false;
1189
1190 return true;
1191 }
1192
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001193 // If this is a builtin, pointer, enum, complex type, member pointer, or
1194 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001195 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001196 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001197 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001198 return true;
1199
1200 // Arrays are treated like records.
1201 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001202 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001203
1204 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001205 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206 if (!RT) return false;
1207
Anders Carlsson40446e82010-01-27 03:25:19 +00001208 // FIXME: Traverse bases here too.
1209
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210 // Structure types are passed in register if all fields would be
1211 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001212 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001213 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001214 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001215 continue;
1216
1217 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001218 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001219 return false;
1220 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221 return true;
1222}
1223
Reid Kleckner04046052016-05-02 17:41:07 +00001224static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1225 // Treat complex types as the element type.
1226 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1227 Ty = CTy->getElementType();
1228
1229 // Check for a type which we know has a simple scalar argument-passing
1230 // convention without any padding. (We're specifically looking for 32
1231 // and 64-bit integer and integer-equivalents, float, and double.)
1232 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1233 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1234 return false;
1235
1236 uint64_t Size = Context.getTypeSize(Ty);
1237 return Size == 32 || Size == 64;
1238}
1239
Reid Kleckner791bbf62017-01-13 17:18:19 +00001240static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1241 uint64_t &Size) {
1242 for (const auto *FD : RD->fields()) {
1243 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1244 // argument is smaller than 32-bits, expanding the struct will create
1245 // alignment padding.
1246 if (!is32Or64BitBasicType(FD->getType(), Context))
1247 return false;
1248
1249 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1250 // how to expand them yet, and the predicate for telling if a bitfield still
1251 // counts as "basic" is more complicated than what we were doing previously.
1252 if (FD->isBitField())
1253 return false;
1254
1255 Size += Context.getTypeSize(FD->getType());
1256 }
1257 return true;
1258}
1259
1260static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1261 uint64_t &Size) {
1262 // Don't do this if there are any non-empty bases.
1263 for (const CXXBaseSpecifier &Base : RD->bases()) {
1264 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1265 Size))
1266 return false;
1267 }
1268 if (!addFieldSizes(Context, RD, Size))
1269 return false;
1270 return true;
1271}
1272
Reid Kleckner04046052016-05-02 17:41:07 +00001273/// Test whether an argument type which is to be passed indirectly (on the
1274/// stack) would have the equivalent layout if it was expanded into separate
1275/// arguments. If so, we prefer to do the latter to avoid inhibiting
1276/// optimizations.
1277bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1278 // We can only expand structure types.
1279 const RecordType *RT = Ty->getAs<RecordType>();
1280 if (!RT)
1281 return false;
1282 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001283 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001284 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001285 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001286 // On non-Windows, we have to conservatively match our old bitcode
1287 // prototypes in order to be ABI-compatible at the bitcode level.
1288 if (!CXXRD->isCLike())
1289 return false;
1290 } else {
1291 // Don't do this for dynamic classes.
1292 if (CXXRD->isDynamicClass())
1293 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001294 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001295 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001296 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001297 } else {
1298 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001299 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001300 }
1301
1302 // We can do this if there was no alignment padding.
1303 return Size == getContext().getTypeSize(Ty);
1304}
1305
John McCall7f416cc2015-09-08 08:05:57 +00001306ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001307 // If the return value is indirect, then the hidden argument is consuming one
1308 // integer register.
1309 if (State.FreeRegs) {
1310 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001311 if (!IsMCUABI)
1312 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001313 }
John McCall7f416cc2015-09-08 08:05:57 +00001314 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001315}
1316
Eric Christopher7565e0d2015-05-29 23:09:49 +00001317ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1318 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001319 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001320 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001321
Reid Kleckner80944df2014-10-31 22:00:51 +00001322 const Type *Base = nullptr;
1323 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001324 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1325 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001326 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1327 // The LLVM struct type for such an aggregate should lower properly.
1328 return ABIArgInfo::getDirect();
1329 }
1330
Chris Lattner458b2aa2010-07-29 02:16:43 +00001331 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001332 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001333 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001334 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001335
1336 // 128-bit vectors are a special case; they are returned in
1337 // registers and we need to make sure to pick a type the LLVM
1338 // backend will like.
1339 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001340 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001341 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001342
1343 // Always return in register if it fits in a general purpose
1344 // register, or if it is 64 bits and has a single element.
1345 if ((Size == 8 || Size == 16 || Size == 32) ||
1346 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001347 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001348 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001349
John McCall7f416cc2015-09-08 08:05:57 +00001350 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001351 }
1352
1353 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001354 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001355
John McCalla1dee5302010-08-22 10:59:02 +00001356 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001357 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001358 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001360 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001361 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001362
David Chisnallde3a0692009-08-17 23:08:21 +00001363 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001364 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001365 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001366
Denis Zobnin380b2242016-02-11 11:26:03 +00001367 // Ignore empty structs/unions.
1368 if (isEmptyRecord(getContext(), RetTy, true))
1369 return ABIArgInfo::getIgnore();
1370
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001371 // Small structures which are register sized are generally returned
1372 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001373 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001374 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001375
1376 // As a special-case, if the struct is a "single-element" struct, and
1377 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001378 // floating-point register. (MSVC does not apply this special case.)
1379 // We apply a similar transformation for pointer types to improve the
1380 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001381 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001382 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001383 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001384 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1385
1386 // FIXME: We should be able to narrow this integer in cases with dead
1387 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001388 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001389 }
1390
John McCall7f416cc2015-09-08 08:05:57 +00001391 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001392 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001393
Chris Lattner458b2aa2010-07-29 02:16:43 +00001394 // Treat an enum type as its underlying type.
1395 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1396 RetTy = EnumTy->getDecl()->getIntegerType();
1397
1398 return (RetTy->isPromotableIntegerType() ?
1399 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400}
1401
Eli Friedman7919bea2012-06-05 19:40:46 +00001402static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1403 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1404}
1405
Daniel Dunbared23de32010-09-16 20:42:00 +00001406static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1407 const RecordType *RT = Ty->getAs<RecordType>();
1408 if (!RT)
1409 return 0;
1410 const RecordDecl *RD = RT->getDecl();
1411
1412 // If this is a C++ record, check the bases first.
1413 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001414 for (const auto &I : CXXRD->bases())
1415 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001416 return false;
1417
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001418 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001419 QualType FT = i->getType();
1420
Eli Friedman7919bea2012-06-05 19:40:46 +00001421 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001422 return true;
1423
1424 if (isRecordWithSSEVectorType(Context, FT))
1425 return true;
1426 }
1427
1428 return false;
1429}
1430
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001431unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1432 unsigned Align) const {
1433 // Otherwise, if the alignment is less than or equal to the minimum ABI
1434 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001435 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001436 return 0; // Use default alignment.
1437
1438 // On non-Darwin, the stack type alignment is always 4.
1439 if (!IsDarwinVectorABI) {
1440 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001441 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001442 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001443
Daniel Dunbared23de32010-09-16 20:42:00 +00001444 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001445 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1446 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001447 return 16;
1448
1449 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001450}
1451
Rafael Espindola703c47f2012-10-19 05:04:37 +00001452ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001453 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001454 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001455 if (State.FreeRegs) {
1456 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001457 if (!IsMCUABI)
1458 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001459 }
John McCall7f416cc2015-09-08 08:05:57 +00001460 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001461 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001462
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001463 // Compute the byval alignment.
1464 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1465 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1466 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001467 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001468
1469 // If the stack alignment is less than the type alignment, realign the
1470 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001471 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001472 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1473 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001474}
1475
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001476X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1477 const Type *T = isSingleElementStruct(Ty, getContext());
1478 if (!T)
1479 T = Ty.getTypePtr();
1480
1481 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1482 BuiltinType::Kind K = BT->getKind();
1483 if (K == BuiltinType::Float || K == BuiltinType::Double)
1484 return Float;
1485 }
1486 return Integer;
1487}
1488
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001489bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001490 if (!IsSoftFloatABI) {
1491 Class C = classify(Ty);
1492 if (C == Float)
1493 return false;
1494 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001495
Rafael Espindola077dd592012-10-24 01:58:58 +00001496 unsigned Size = getContext().getTypeSize(Ty);
1497 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001498
1499 if (SizeInRegs == 0)
1500 return false;
1501
Michael Kuperstein68901882015-10-25 08:18:20 +00001502 if (!IsMCUABI) {
1503 if (SizeInRegs > State.FreeRegs) {
1504 State.FreeRegs = 0;
1505 return false;
1506 }
1507 } else {
1508 // The MCU psABI allows passing parameters in-reg even if there are
1509 // earlier parameters that are passed on the stack. Also,
1510 // it does not allow passing >8-byte structs in-register,
1511 // even if there are 3 free registers available.
1512 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1513 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001514 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001515
Reid Kleckner661f35b2014-01-18 01:12:41 +00001516 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001517 return true;
1518}
1519
1520bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1521 bool &InReg,
1522 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001523 // On Windows, aggregates other than HFAs are never passed in registers, and
1524 // they do not consume register slots. Homogenous floating-point aggregates
1525 // (HFAs) have already been dealt with at this point.
1526 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1527 return false;
1528
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001529 NeedsPadding = false;
1530 InReg = !IsMCUABI;
1531
1532 if (!updateFreeRegs(Ty, State))
1533 return false;
1534
1535 if (IsMCUABI)
1536 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001537
Reid Kleckner80944df2014-10-31 22:00:51 +00001538 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001539 State.CC == llvm::CallingConv::X86_VectorCall ||
1540 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001541 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001542 NeedsPadding = true;
1543
Rafael Espindola077dd592012-10-24 01:58:58 +00001544 return false;
1545 }
1546
Rafael Espindola703c47f2012-10-19 05:04:37 +00001547 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001548}
1549
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001550bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1551 if (!updateFreeRegs(Ty, State))
1552 return false;
1553
1554 if (IsMCUABI)
1555 return false;
1556
1557 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001558 State.CC == llvm::CallingConv::X86_VectorCall ||
1559 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001560 if (getContext().getTypeSize(Ty) > 32)
1561 return false;
1562
1563 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1564 Ty->isReferenceType());
1565 }
1566
1567 return true;
1568}
1569
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001570ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1571 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001572 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001573
Reid Klecknerb1be6832014-11-15 01:41:41 +00001574 Ty = useFirstFieldIfTransparentUnion(Ty);
1575
Reid Kleckner80944df2014-10-31 22:00:51 +00001576 // Check with the C++ ABI first.
1577 const RecordType *RT = Ty->getAs<RecordType>();
1578 if (RT) {
1579 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1580 if (RAA == CGCXXABI::RAA_Indirect) {
1581 return getIndirectResult(Ty, false, State);
1582 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1583 // The field index doesn't matter, we'll fix it up later.
1584 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1585 }
1586 }
1587
Erich Keane4bd39302017-06-21 16:37:22 +00001588 // Regcall uses the concept of a homogenous vector aggregate, similar
1589 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001590 const Type *Base = nullptr;
1591 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001592 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001593 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001594
Erich Keane4bd39302017-06-21 16:37:22 +00001595 if (State.FreeSSERegs >= NumElts) {
1596 State.FreeSSERegs -= NumElts;
1597 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001599 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001600 }
Erich Keane4bd39302017-06-21 16:37:22 +00001601 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001602 }
1603
1604 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001605 // Structures with flexible arrays are always indirect.
1606 // FIXME: This should not be byval!
1607 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1608 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001609
Reid Kleckner04046052016-05-02 17:41:07 +00001610 // Ignore empty structs/unions on non-Windows.
1611 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001612 return ABIArgInfo::getIgnore();
1613
Rafael Espindolafad28de2012-10-24 01:59:00 +00001614 llvm::LLVMContext &LLVMContext = getVMContext();
1615 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001616 bool NeedsPadding = false;
1617 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001618 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001619 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001620 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001621 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001622 if (InReg)
1623 return ABIArgInfo::getDirectInReg(Result);
1624 else
1625 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001626 }
Craig Topper8a13c412014-05-21 05:09:00 +00001627 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001628
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001629 // Expand small (<= 128-bit) record types when we know that the stack layout
1630 // of those arguments will match the struct. This is important because the
1631 // LLVM backend isn't smart enough to remove byval, which inhibits many
1632 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001633 // Don't do this for the MCU if there are still free integer registers
1634 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001635 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1636 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001637 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001638 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001639 State.CC == llvm::CallingConv::X86_VectorCall ||
1640 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001641 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001642
Reid Kleckner661f35b2014-01-18 01:12:41 +00001643 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001644 }
1645
Chris Lattnerd774ae92010-08-26 20:05:13 +00001646 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001647 // On Darwin, some vectors are passed in memory, we handle this by passing
1648 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001649 if (IsDarwinVectorABI) {
1650 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001651 if ((Size == 8 || Size == 16 || Size == 32) ||
1652 (Size == 64 && VT->getNumElements() == 1))
1653 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1654 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001655 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001656
Chad Rosier651c1832013-03-25 21:00:27 +00001657 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1658 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001659
Chris Lattnerd774ae92010-08-26 20:05:13 +00001660 return ABIArgInfo::getDirect();
1661 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001662
1663
Chris Lattner458b2aa2010-07-29 02:16:43 +00001664 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1665 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001666
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001667 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001668
1669 if (Ty->isPromotableIntegerType()) {
1670 if (InReg)
1671 return ABIArgInfo::getExtendInReg();
1672 return ABIArgInfo::getExtend();
1673 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001674
Rafael Espindola703c47f2012-10-19 05:04:37 +00001675 if (InReg)
1676 return ABIArgInfo::getDirectInReg();
1677 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001678}
1679
Erich Keane521ed962017-01-05 00:20:51 +00001680void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1681 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001682 // Vectorcall x86 works subtly different than in x64, so the format is
1683 // a bit different than the x64 version. First, all vector types (not HVAs)
1684 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1685 // This differs from the x64 implementation, where the first 6 by INDEX get
1686 // registers.
1687 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1688 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1689 // first take up the remaining YMM/XMM registers. If insufficient registers
1690 // remain but an integer register (ECX/EDX) is available, it will be passed
1691 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001692 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001693 // First pass do all the vector types.
1694 const Type *Base = nullptr;
1695 uint64_t NumElts = 0;
1696 const QualType& Ty = I.type;
1697 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1698 isHomogeneousAggregate(Ty, Base, NumElts)) {
1699 if (State.FreeSSERegs >= NumElts) {
1700 State.FreeSSERegs -= NumElts;
1701 I.info = ABIArgInfo::getDirect();
1702 } else {
1703 I.info = classifyArgumentType(Ty, State);
1704 }
1705 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1706 }
Erich Keane521ed962017-01-05 00:20:51 +00001707 }
Erich Keane4bd39302017-06-21 16:37:22 +00001708
Erich Keane521ed962017-01-05 00:20:51 +00001709 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001710 // Second pass, do the rest!
1711 const Type *Base = nullptr;
1712 uint64_t NumElts = 0;
1713 const QualType& Ty = I.type;
1714 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1715
1716 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1717 // Assign true HVAs (non vector/native FP types).
1718 if (State.FreeSSERegs >= NumElts) {
1719 State.FreeSSERegs -= NumElts;
1720 I.info = getDirectX86Hva();
1721 } else {
1722 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1723 }
1724 } else if (!IsHva) {
1725 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1726 I.info = classifyArgumentType(Ty, State);
1727 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1728 }
Erich Keane521ed962017-01-05 00:20:51 +00001729 }
1730}
1731
Rafael Espindolaa6472962012-07-24 00:01:07 +00001732void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001733 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001734 if (IsMCUABI)
1735 State.FreeRegs = 3;
1736 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001737 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001738 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1739 State.FreeRegs = 2;
1740 State.FreeSSERegs = 6;
1741 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001742 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001743 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1744 State.FreeRegs = 5;
1745 State.FreeSSERegs = 8;
1746 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001747 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001748
Reid Kleckner677539d2014-07-10 01:58:55 +00001749 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001750 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001751 } else if (FI.getReturnInfo().isIndirect()) {
1752 // The C++ ABI is not aware of register usage, so we have to check if the
1753 // return value was sret and put it in a register ourselves if appropriate.
1754 if (State.FreeRegs) {
1755 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001756 if (!IsMCUABI)
1757 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001758 }
1759 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001760
Peter Collingbournef7706832014-12-12 23:41:25 +00001761 // The chain argument effectively gives us another free register.
1762 if (FI.isChainCall())
1763 ++State.FreeRegs;
1764
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001765 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001766 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1767 computeVectorCallArgs(FI, State, UsedInAlloca);
1768 } else {
1769 // If not vectorcall, revert to normal behavior.
1770 for (auto &I : FI.arguments()) {
1771 I.info = classifyArgumentType(I.type, State);
1772 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1773 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001774 }
1775
1776 // If we needed to use inalloca for any argument, do a second pass and rewrite
1777 // all the memory arguments to use inalloca.
1778 if (UsedInAlloca)
1779 rewriteWithInAlloca(FI);
1780}
1781
1782void
1783X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001784 CharUnits &StackOffset, ABIArgInfo &Info,
1785 QualType Type) const {
1786 // Arguments are always 4-byte-aligned.
1787 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1788
1789 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001790 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1791 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001792 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001793
John McCall7f416cc2015-09-08 08:05:57 +00001794 // Insert padding bytes to respect alignment.
1795 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001796 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001797 if (StackOffset != FieldEnd) {
1798 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001799 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001800 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001801 FrameFields.push_back(Ty);
1802 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001803}
1804
Reid Kleckner852361d2014-07-26 00:12:26 +00001805static bool isArgInAlloca(const ABIArgInfo &Info) {
1806 // Leave ignored and inreg arguments alone.
1807 switch (Info.getKind()) {
1808 case ABIArgInfo::InAlloca:
1809 return true;
1810 case ABIArgInfo::Indirect:
1811 assert(Info.getIndirectByVal());
1812 return true;
1813 case ABIArgInfo::Ignore:
1814 return false;
1815 case ABIArgInfo::Direct:
1816 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001817 if (Info.getInReg())
1818 return false;
1819 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001820 case ABIArgInfo::Expand:
1821 case ABIArgInfo::CoerceAndExpand:
1822 // These are aggregate types which are never passed in registers when
1823 // inalloca is involved.
1824 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001825 }
1826 llvm_unreachable("invalid enum");
1827}
1828
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001829void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1830 assert(IsWin32StructABI && "inalloca only supported on win32");
1831
1832 // Build a packed struct type for all of the arguments in memory.
1833 SmallVector<llvm::Type *, 6> FrameFields;
1834
John McCall7f416cc2015-09-08 08:05:57 +00001835 // The stack alignment is always 4.
1836 CharUnits StackAlign = CharUnits::fromQuantity(4);
1837
1838 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001839 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1840
1841 // Put 'this' into the struct before 'sret', if necessary.
1842 bool IsThisCall =
1843 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1844 ABIArgInfo &Ret = FI.getReturnInfo();
1845 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1846 isArgInAlloca(I->info)) {
1847 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1848 ++I;
1849 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001850
1851 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001852 if (Ret.isIndirect() && !Ret.getInReg()) {
1853 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1854 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001855 // On Windows, the hidden sret parameter is always returned in eax.
1856 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001857 }
1858
1859 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001860 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001861 ++I;
1862
1863 // Put arguments passed in memory into the struct.
1864 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001865 if (isArgInAlloca(I->info))
1866 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001867 }
1868
1869 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001870 /*isPacked=*/true),
1871 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001872}
1873
John McCall7f416cc2015-09-08 08:05:57 +00001874Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1875 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001876
John McCall7f416cc2015-09-08 08:05:57 +00001877 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001878
John McCall7f416cc2015-09-08 08:05:57 +00001879 // x86-32 changes the alignment of certain arguments on the stack.
1880 //
1881 // Just messing with TypeInfo like this works because we never pass
1882 // anything indirectly.
1883 TypeInfo.second = CharUnits::fromQuantity(
1884 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001885
John McCall7f416cc2015-09-08 08:05:57 +00001886 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1887 TypeInfo, CharUnits::fromQuantity(4),
1888 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001889}
1890
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001891bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1892 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1893 assert(Triple.getArch() == llvm::Triple::x86);
1894
1895 switch (Opts.getStructReturnConvention()) {
1896 case CodeGenOptions::SRCK_Default:
1897 break;
1898 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1899 return false;
1900 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1901 return true;
1902 }
1903
Michael Kupersteind749f232015-10-27 07:46:22 +00001904 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001905 return true;
1906
1907 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001908 case llvm::Triple::DragonFly:
1909 case llvm::Triple::FreeBSD:
1910 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001911 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001912 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001913 default:
1914 return false;
1915 }
1916}
1917
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001918void X86_32TargetCodeGenInfo::setTargetAttributes(
1919 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1920 ForDefinition_t IsForDefinition) const {
1921 if (!IsForDefinition)
1922 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001923 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001924 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1925 // Get the LLVM function.
1926 llvm::Function *Fn = cast<llvm::Function>(GV);
1927
1928 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001929 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001930 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001931 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001932 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001933 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1934 llvm::Function *Fn = cast<llvm::Function>(GV);
1935 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1936 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001937 }
1938}
1939
John McCallbeec5a02010-03-06 00:35:14 +00001940bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1941 CodeGen::CodeGenFunction &CGF,
1942 llvm::Value *Address) const {
1943 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001944
Chris Lattnerece04092012-02-07 00:39:47 +00001945 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001946
John McCallbeec5a02010-03-06 00:35:14 +00001947 // 0-7 are the eight integer registers; the order is different
1948 // on Darwin (for EH), but the range is the same.
1949 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001950 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001951
John McCallc8e01702013-04-16 22:48:15 +00001952 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001953 // 12-16 are st(0..4). Not sure why we stop at 4.
1954 // These have size 16, which is sizeof(long double) on
1955 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001956 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001957 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001958
John McCallbeec5a02010-03-06 00:35:14 +00001959 } else {
1960 // 9 is %eflags, which doesn't get a size on Darwin for some
1961 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001962 Builder.CreateAlignedStore(
1963 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1964 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001965
1966 // 11-16 are st(0..5). Not sure why we stop at 5.
1967 // These have size 12, which is sizeof(long double) on
1968 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001969 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001970 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1971 }
John McCallbeec5a02010-03-06 00:35:14 +00001972
1973 return false;
1974}
1975
Chris Lattner0cf24192010-06-28 20:05:43 +00001976//===----------------------------------------------------------------------===//
1977// X86-64 ABI Implementation
1978//===----------------------------------------------------------------------===//
1979
1980
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001981namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001982/// The AVX ABI level for X86 targets.
1983enum class X86AVXABILevel {
1984 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001985 AVX,
1986 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001987};
1988
1989/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1990static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1991 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001992 case X86AVXABILevel::AVX512:
1993 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001994 case X86AVXABILevel::AVX:
1995 return 256;
1996 case X86AVXABILevel::None:
1997 return 128;
1998 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001999 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002000}
2001
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002002/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002003class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002004 enum Class {
2005 Integer = 0,
2006 SSE,
2007 SSEUp,
2008 X87,
2009 X87Up,
2010 ComplexX87,
2011 NoClass,
2012 Memory
2013 };
2014
2015 /// merge - Implement the X86_64 ABI merging algorithm.
2016 ///
2017 /// Merge an accumulating classification \arg Accum with a field
2018 /// classification \arg Field.
2019 ///
2020 /// \param Accum - The accumulating classification. This should
2021 /// always be either NoClass or the result of a previous merge
2022 /// call. In addition, this should never be Memory (the caller
2023 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002024 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002025
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002026 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2027 ///
2028 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2029 /// final MEMORY or SSE classes when necessary.
2030 ///
2031 /// \param AggregateSize - The size of the current aggregate in
2032 /// the classification process.
2033 ///
2034 /// \param Lo - The classification for the parts of the type
2035 /// residing in the low word of the containing object.
2036 ///
2037 /// \param Hi - The classification for the parts of the type
2038 /// residing in the higher words of the containing object.
2039 ///
2040 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2041
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002042 /// classify - Determine the x86_64 register classes in which the
2043 /// given type T should be passed.
2044 ///
2045 /// \param Lo - The classification for the parts of the type
2046 /// residing in the low word of the containing object.
2047 ///
2048 /// \param Hi - The classification for the parts of the type
2049 /// residing in the high word of the containing object.
2050 ///
2051 /// \param OffsetBase - The bit offset of this type in the
2052 /// containing object. Some parameters are classified different
2053 /// depending on whether they straddle an eightbyte boundary.
2054 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002055 /// \param isNamedArg - Whether the argument in question is a "named"
2056 /// argument, as used in AMD64-ABI 3.5.7.
2057 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002058 /// If a word is unused its result will be NoClass; if a type should
2059 /// be passed in Memory then at least the classification of \arg Lo
2060 /// will be Memory.
2061 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002062 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063 ///
2064 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2065 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002066 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2067 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002068
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002069 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002070 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2071 unsigned IROffset, QualType SourceTy,
2072 unsigned SourceOffset) const;
2073 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2074 unsigned IROffset, QualType SourceTy,
2075 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002076
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002077 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002078 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002079 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002080
2081 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002082 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002083 ///
2084 /// \param freeIntRegs - The number of free integer registers remaining
2085 /// available.
2086 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002087
Chris Lattner458b2aa2010-07-29 02:16:43 +00002088 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002089
Erich Keane757d3172016-11-02 18:29:35 +00002090 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2091 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002092 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002093
Erich Keane757d3172016-11-02 18:29:35 +00002094 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2095 unsigned &NeededSSE) const;
2096
2097 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2098 unsigned &NeededSSE) const;
2099
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002100 bool IsIllegalVectorType(QualType Ty) const;
2101
John McCalle0fda732011-04-21 01:20:55 +00002102 /// The 0.98 ABI revision clarified a lot of ambiguities,
2103 /// unfortunately in ways that were not always consistent with
2104 /// certain previous compilers. In particular, platforms which
2105 /// required strict binary compatibility with older versions of GCC
2106 /// may need to exempt themselves.
2107 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002108 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002109 }
2110
David Majnemere2ae2282016-03-04 05:26:16 +00002111 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2112 // compilers require us to classify it as INTEGER.
2113 bool classifyIntegerMMXAsSSE() const {
2114 const llvm::Triple &Triple = getTarget().getTriple();
2115 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2116 return false;
2117 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2118 return false;
2119 return true;
2120 }
2121
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002122 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002123 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2124 // 64-bit hardware.
2125 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002126
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002127public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002128 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002129 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002130 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002131 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002132
John McCalla729c622012-02-17 03:33:10 +00002133 bool isPassedUsingAVXType(QualType type) const {
2134 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002135 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002136 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2137 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002138 if (info.isDirect()) {
2139 llvm::Type *ty = info.getCoerceToType();
2140 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2141 return (vectorTy->getBitWidth() > 128);
2142 }
2143 return false;
2144 }
2145
Craig Topper4f12f102014-03-12 06:41:41 +00002146 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002147
John McCall7f416cc2015-09-08 08:05:57 +00002148 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2149 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002150 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2151 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002152
2153 bool has64BitPointers() const {
2154 return Has64BitPointers;
2155 }
John McCall12f23522016-04-04 18:33:08 +00002156
2157 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2158 ArrayRef<llvm::Type*> scalars,
2159 bool asReturnValue) const override {
2160 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2161 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002162 bool isSwiftErrorInRegister() const override {
2163 return true;
2164 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002165};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002166
Chris Lattner04dc9572010-08-31 16:44:54 +00002167/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002168class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002169public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002170 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002171 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002172 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002173
Craig Topper4f12f102014-03-12 06:41:41 +00002174 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002175
John McCall7f416cc2015-09-08 08:05:57 +00002176 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2177 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002178
2179 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2180 // FIXME: Assumes vectorcall is in use.
2181 return isX86VectorTypeForVectorCall(getContext(), Ty);
2182 }
2183
2184 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2185 uint64_t NumMembers) const override {
2186 // FIXME: Assumes vectorcall is in use.
2187 return isX86VectorCallAggregateSmallEnough(NumMembers);
2188 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002189
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002190 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2191 ArrayRef<llvm::Type *> scalars,
2192 bool asReturnValue) const override {
2193 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2194 }
2195
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002196 bool isSwiftErrorInRegister() const override {
2197 return true;
2198 }
2199
Reid Kleckner11a17192015-10-28 22:29:52 +00002200private:
Erich Keane521ed962017-01-05 00:20:51 +00002201 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2202 bool IsVectorCall, bool IsRegCall) const;
2203 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2204 const ABIArgInfo &current) const;
2205 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2206 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002207
Erich Keane521ed962017-01-05 00:20:51 +00002208 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002209};
2210
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002211class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2212public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002213 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002214 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002215
John McCalla729c622012-02-17 03:33:10 +00002216 const X86_64ABIInfo &getABIInfo() const {
2217 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2218 }
2219
Craig Topper4f12f102014-03-12 06:41:41 +00002220 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002221 return 7;
2222 }
2223
2224 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002225 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002226 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002227
John McCall943fae92010-05-27 06:19:26 +00002228 // 0-15 are the 16 integer registers.
2229 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002230 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002231 return false;
2232 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002233
Jay Foad7c57be32011-07-11 09:56:20 +00002234 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002235 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002236 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002237 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2238 }
2239
John McCalla729c622012-02-17 03:33:10 +00002240 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002241 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002242 // The default CC on x86-64 sets %al to the number of SSA
2243 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002244 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002245 // that when AVX types are involved: the ABI explicitly states it is
2246 // undefined, and it doesn't work in practice because of how the ABI
2247 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002248 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002249 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002250 for (CallArgList::const_iterator
2251 it = args.begin(), ie = args.end(); it != ie; ++it) {
2252 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2253 HasAVXType = true;
2254 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002255 }
2256 }
John McCalla729c622012-02-17 03:33:10 +00002257
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002258 if (!HasAVXType)
2259 return true;
2260 }
John McCallcbc038a2011-09-21 08:08:30 +00002261
John McCalla729c622012-02-17 03:33:10 +00002262 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002263 }
2264
Craig Topper4f12f102014-03-12 06:41:41 +00002265 llvm::Constant *
2266 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002267 unsigned Sig;
2268 if (getABIInfo().has64BitPointers())
2269 Sig = (0xeb << 0) | // jmp rel8
2270 (0x0a << 8) | // .+0x0c
2271 ('F' << 16) |
2272 ('T' << 24);
2273 else
2274 Sig = (0xeb << 0) | // jmp rel8
2275 (0x06 << 8) | // .+0x08
2276 ('F' << 16) |
2277 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002278 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2279 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002280
2281 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002282 CodeGen::CodeGenModule &CGM,
2283 ForDefinition_t IsForDefinition) const override {
2284 if (!IsForDefinition)
2285 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002286 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2287 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2288 llvm::Function *Fn = cast<llvm::Function>(GV);
2289 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2290 }
2291 }
2292 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002293};
2294
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002295class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2296public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002297 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2298 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002299
2300 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002301 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002302 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002303 // If the argument contains a space, enclose it in quotes.
2304 if (Lib.find(" ") != StringRef::npos)
2305 Opt += "\"" + Lib.str() + "\"";
2306 else
2307 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002308 }
2309};
2310
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002311static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002312 // If the argument does not end in .lib, automatically add the suffix.
2313 // If the argument contains a space, enclose it in quotes.
2314 // This matches the behavior of MSVC.
2315 bool Quote = (Lib.find(" ") != StringRef::npos);
2316 std::string ArgStr = Quote ? "\"" : "";
2317 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002318 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002319 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002320 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002321 return ArgStr;
2322}
2323
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002324class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2325public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002326 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002327 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2328 unsigned NumRegisterParameters)
2329 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002330 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002331
Eric Christopher162c91c2015-06-05 22:03:00 +00002332 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002333 CodeGen::CodeGenModule &CGM,
2334 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002335
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002336 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002337 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002338 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002339 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002340 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002341
2342 void getDetectMismatchOption(llvm::StringRef Name,
2343 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002344 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002345 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002346 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002347};
2348
Hans Wennborg77dc2362015-01-20 19:45:50 +00002349static void addStackProbeSizeTargetAttribute(const Decl *D,
2350 llvm::GlobalValue *GV,
2351 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002352 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002353 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2354 llvm::Function *Fn = cast<llvm::Function>(GV);
2355
Eric Christopher7565e0d2015-05-29 23:09:49 +00002356 Fn->addFnAttr("stack-probe-size",
2357 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002358 }
2359 }
2360}
2361
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002362void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2363 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2364 ForDefinition_t IsForDefinition) const {
2365 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2366 if (!IsForDefinition)
2367 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002368 addStackProbeSizeTargetAttribute(D, GV, CGM);
2369}
2370
Chris Lattner04dc9572010-08-31 16:44:54 +00002371class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2372public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002373 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2374 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002375 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002376
Eric Christopher162c91c2015-06-05 22:03:00 +00002377 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002378 CodeGen::CodeGenModule &CGM,
2379 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002380
Craig Topper4f12f102014-03-12 06:41:41 +00002381 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002382 return 7;
2383 }
2384
2385 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002386 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002387 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002388
Chris Lattner04dc9572010-08-31 16:44:54 +00002389 // 0-15 are the 16 integer registers.
2390 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002391 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002392 return false;
2393 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002394
2395 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002396 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002397 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002398 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002399 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002400
2401 void getDetectMismatchOption(llvm::StringRef Name,
2402 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002403 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002404 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002405 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002406};
2407
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002408void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2409 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2410 ForDefinition_t IsForDefinition) const {
2411 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2412 if (!IsForDefinition)
2413 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002414 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2415 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2416 llvm::Function *Fn = cast<llvm::Function>(GV);
2417 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2418 }
2419 }
2420
Hans Wennborg77dc2362015-01-20 19:45:50 +00002421 addStackProbeSizeTargetAttribute(D, GV, CGM);
2422}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002423}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002424
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002425void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2426 Class &Hi) const {
2427 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2428 //
2429 // (a) If one of the classes is Memory, the whole argument is passed in
2430 // memory.
2431 //
2432 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2433 // memory.
2434 //
2435 // (c) If the size of the aggregate exceeds two eightbytes and the first
2436 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2437 // argument is passed in memory. NOTE: This is necessary to keep the
2438 // ABI working for processors that don't support the __m256 type.
2439 //
2440 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2441 //
2442 // Some of these are enforced by the merging logic. Others can arise
2443 // only with unions; for example:
2444 // union { _Complex double; unsigned; }
2445 //
2446 // Note that clauses (b) and (c) were added in 0.98.
2447 //
2448 if (Hi == Memory)
2449 Lo = Memory;
2450 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2451 Lo = Memory;
2452 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2453 Lo = Memory;
2454 if (Hi == SSEUp && Lo != SSE)
2455 Hi = SSE;
2456}
2457
Chris Lattnerd776fb12010-06-28 21:43:59 +00002458X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002459 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2460 // classified recursively so that always two fields are
2461 // considered. The resulting class is calculated according to
2462 // the classes of the fields in the eightbyte:
2463 //
2464 // (a) If both classes are equal, this is the resulting class.
2465 //
2466 // (b) If one of the classes is NO_CLASS, the resulting class is
2467 // the other class.
2468 //
2469 // (c) If one of the classes is MEMORY, the result is the MEMORY
2470 // class.
2471 //
2472 // (d) If one of the classes is INTEGER, the result is the
2473 // INTEGER.
2474 //
2475 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2476 // MEMORY is used as class.
2477 //
2478 // (f) Otherwise class SSE is used.
2479
2480 // Accum should never be memory (we should have returned) or
2481 // ComplexX87 (because this cannot be passed in a structure).
2482 assert((Accum != Memory && Accum != ComplexX87) &&
2483 "Invalid accumulated classification during merge.");
2484 if (Accum == Field || Field == NoClass)
2485 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002486 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002487 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002488 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002490 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002491 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002492 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2493 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002494 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002495 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496}
2497
Chris Lattner5c740f12010-06-30 19:14:05 +00002498void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002499 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500 // FIXME: This code can be simplified by introducing a simple value class for
2501 // Class pairs with appropriate constructor methods for the various
2502 // situations.
2503
2504 // FIXME: Some of the split computations are wrong; unaligned vectors
2505 // shouldn't be passed in registers for example, so there is no chance they
2506 // can straddle an eightbyte. Verify & simplify.
2507
2508 Lo = Hi = NoClass;
2509
2510 Class &Current = OffsetBase < 64 ? Lo : Hi;
2511 Current = Memory;
2512
John McCall9dd450b2009-09-21 23:43:11 +00002513 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002514 BuiltinType::Kind k = BT->getKind();
2515
2516 if (k == BuiltinType::Void) {
2517 Current = NoClass;
2518 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2519 Lo = Integer;
2520 Hi = Integer;
2521 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2522 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002523 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524 Current = SSE;
2525 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002526 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002527 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002528 Lo = SSE;
2529 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002530 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002531 Lo = X87;
2532 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002533 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002534 Current = SSE;
2535 } else
2536 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 }
2538 // FIXME: _Decimal32 and _Decimal64 are SSE.
2539 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002540 return;
2541 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002542
Chris Lattnerd776fb12010-06-28 21:43:59 +00002543 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002544 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002545 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002546 return;
2547 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002548
Chris Lattnerd776fb12010-06-28 21:43:59 +00002549 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002550 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002551 return;
2552 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002553
Chris Lattnerd776fb12010-06-28 21:43:59 +00002554 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002555 if (Ty->isMemberFunctionPointerType()) {
2556 if (Has64BitPointers) {
2557 // If Has64BitPointers, this is an {i64, i64}, so classify both
2558 // Lo and Hi now.
2559 Lo = Hi = Integer;
2560 } else {
2561 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2562 // straddles an eightbyte boundary, Hi should be classified as well.
2563 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2564 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2565 if (EB_FuncPtr != EB_ThisAdj) {
2566 Lo = Hi = Integer;
2567 } else {
2568 Current = Integer;
2569 }
2570 }
2571 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002572 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002573 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002574 return;
2575 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002576
Chris Lattnerd776fb12010-06-28 21:43:59 +00002577 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002578 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002579 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2580 // gcc passes the following as integer:
2581 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2582 // 2 bytes - <2 x char>, <1 x short>
2583 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002584 Current = Integer;
2585
2586 // If this type crosses an eightbyte boundary, it should be
2587 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002588 uint64_t EB_Lo = (OffsetBase) / 64;
2589 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2590 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002591 Hi = Lo;
2592 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002593 QualType ElementType = VT->getElementType();
2594
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002595 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002596 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002597 return;
2598
David Majnemere2ae2282016-03-04 05:26:16 +00002599 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2600 // pass them as integer. For platforms where clang is the de facto
2601 // platform compiler, we must continue to use integer.
2602 if (!classifyIntegerMMXAsSSE() &&
2603 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2604 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2605 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2606 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002607 Current = Integer;
2608 else
2609 Current = SSE;
2610
2611 // If this type crosses an eightbyte boundary, it should be
2612 // split.
2613 if (OffsetBase && OffsetBase != 64)
2614 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002615 } else if (Size == 128 ||
2616 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002617 // Arguments of 256-bits are split into four eightbyte chunks. The
2618 // least significant one belongs to class SSE and all the others to class
2619 // SSEUP. The original Lo and Hi design considers that types can't be
2620 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2621 // This design isn't correct for 256-bits, but since there're no cases
2622 // where the upper parts would need to be inspected, avoid adding
2623 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002624 //
2625 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2626 // registers if they are "named", i.e. not part of the "..." of a
2627 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002628 //
2629 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2630 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 Lo = SSE;
2632 Hi = SSEUp;
2633 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002634 return;
2635 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002636
Chris Lattnerd776fb12010-06-28 21:43:59 +00002637 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002638 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639
Chris Lattner2b037972010-07-29 02:01:43 +00002640 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002641 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 if (Size <= 64)
2643 Current = Integer;
2644 else if (Size <= 128)
2645 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002646 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002647 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002648 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002650 } else if (ET == getContext().LongDoubleTy) {
2651 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002652 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002653 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002654 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002655 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002656 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002657 Lo = Hi = SSE;
2658 else
2659 llvm_unreachable("unexpected long double representation!");
2660 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661
2662 // If this complex type crosses an eightbyte boundary then it
2663 // should be split.
2664 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002665 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666 if (Hi == NoClass && EB_Real != EB_Imag)
2667 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002668
Chris Lattnerd776fb12010-06-28 21:43:59 +00002669 return;
2670 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002671
Chris Lattner2b037972010-07-29 02:01:43 +00002672 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002673 // Arrays are treated like structures.
2674
Chris Lattner2b037972010-07-29 02:01:43 +00002675 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002676
2677 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002678 // than eight eightbytes, ..., it has class MEMORY.
2679 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680 return;
2681
2682 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2683 // fields, it has class MEMORY.
2684 //
2685 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002686 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002687 return;
2688
2689 // Otherwise implement simplified merge. We could be smarter about
2690 // this, but it isn't worth it and would be harder to verify.
2691 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002692 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002694
2695 // The only case a 256-bit wide vector could be used is when the array
2696 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2697 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002698 //
2699 if (Size > 128 &&
2700 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002701 return;
2702
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002703 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2704 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002705 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706 Lo = merge(Lo, FieldLo);
2707 Hi = merge(Hi, FieldHi);
2708 if (Lo == Memory || Hi == Memory)
2709 break;
2710 }
2711
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002712 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002713 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002714 return;
2715 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002716
Chris Lattnerd776fb12010-06-28 21:43:59 +00002717 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002718 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719
2720 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002721 // than eight eightbytes, ..., it has class MEMORY.
2722 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002723 return;
2724
Anders Carlsson20759ad2009-09-16 15:53:40 +00002725 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2726 // copy constructor or a non-trivial destructor, it is passed by invisible
2727 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002728 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002729 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002730
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002731 const RecordDecl *RD = RT->getDecl();
2732
2733 // Assume variable sized types are passed in memory.
2734 if (RD->hasFlexibleArrayMember())
2735 return;
2736
Chris Lattner2b037972010-07-29 02:01:43 +00002737 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738
2739 // Reset Lo class, this will be recomputed.
2740 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002741
2742 // If this is a C++ record, classify the bases first.
2743 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002744 for (const auto &I : CXXRD->bases()) {
2745 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002746 "Unexpected base class!");
2747 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002748 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002749
2750 // Classify this field.
2751 //
2752 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2753 // single eightbyte, each is classified separately. Each eightbyte gets
2754 // initialized to class NO_CLASS.
2755 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002756 uint64_t Offset =
2757 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002758 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002759 Lo = merge(Lo, FieldLo);
2760 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002761 if (Lo == Memory || Hi == Memory) {
2762 postMerge(Size, Lo, Hi);
2763 return;
2764 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002765 }
2766 }
2767
2768 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002770 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002771 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002772 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2773 bool BitField = i->isBitField();
2774
David Majnemerb439dfe2016-08-15 07:20:40 +00002775 // Ignore padding bit-fields.
2776 if (BitField && i->isUnnamedBitfield())
2777 continue;
2778
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002779 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2780 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002782 // The only case a 256-bit wide vector could be used is when the struct
2783 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2784 // to work for sizes wider than 128, early check and fallback to memory.
2785 //
David Majnemerb229cb02016-08-15 06:39:18 +00002786 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2787 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002788 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002789 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002790 return;
2791 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002792 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002793 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002795 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002796 return;
2797 }
2798
2799 // Classify this field.
2800 //
2801 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2802 // exceeds a single eightbyte, each is classified
2803 // separately. Each eightbyte gets initialized to class
2804 // NO_CLASS.
2805 Class FieldLo, FieldHi;
2806
2807 // Bit-fields require special handling, they do not force the
2808 // structure to be passed in memory even if unaligned, and
2809 // therefore they can straddle an eightbyte.
2810 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002811 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002812 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002813 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814
2815 uint64_t EB_Lo = Offset / 64;
2816 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002817
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 if (EB_Lo) {
2819 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2820 FieldLo = NoClass;
2821 FieldHi = Integer;
2822 } else {
2823 FieldLo = Integer;
2824 FieldHi = EB_Hi ? Integer : NoClass;
2825 }
2826 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002827 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002828 Lo = merge(Lo, FieldLo);
2829 Hi = merge(Hi, FieldHi);
2830 if (Lo == Memory || Hi == Memory)
2831 break;
2832 }
2833
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002834 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 }
2836}
2837
Chris Lattner22a931e2010-06-29 06:01:59 +00002838ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002839 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2840 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002841 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002842 // Treat an enum type as its underlying type.
2843 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2844 Ty = EnumTy->getDecl()->getIntegerType();
2845
2846 return (Ty->isPromotableIntegerType() ?
2847 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2848 }
2849
John McCall7f416cc2015-09-08 08:05:57 +00002850 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002851}
2852
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002853bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2854 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2855 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002856 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002857 if (Size <= 64 || Size > LargestVector)
2858 return true;
2859 }
2860
2861 return false;
2862}
2863
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002864ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2865 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002866 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2867 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002868 //
2869 // This assumption is optimistic, as there could be free registers available
2870 // when we need to pass this argument in memory, and LLVM could try to pass
2871 // the argument in the free register. This does not seem to happen currently,
2872 // but this code would be much safer if we could mark the argument with
2873 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002874 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002875 // Treat an enum type as its underlying type.
2876 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2877 Ty = EnumTy->getDecl()->getIntegerType();
2878
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002879 return (Ty->isPromotableIntegerType() ?
2880 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002881 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002882
Mark Lacey3825e832013-10-06 01:33:34 +00002883 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002884 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002885
Chris Lattner44c2b902011-05-22 23:21:23 +00002886 // Compute the byval alignment. We specify the alignment of the byval in all
2887 // cases so that the mid-level optimizer knows the alignment of the byval.
2888 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002889
2890 // Attempt to avoid passing indirect results using byval when possible. This
2891 // is important for good codegen.
2892 //
2893 // We do this by coercing the value into a scalar type which the backend can
2894 // handle naturally (i.e., without using byval).
2895 //
2896 // For simplicity, we currently only do this when we have exhausted all of the
2897 // free integer registers. Doing this when there are free integer registers
2898 // would require more care, as we would have to ensure that the coerced value
2899 // did not claim the unused register. That would require either reording the
2900 // arguments to the function (so that any subsequent inreg values came first),
2901 // or only doing this optimization when there were no following arguments that
2902 // might be inreg.
2903 //
2904 // We currently expect it to be rare (particularly in well written code) for
2905 // arguments to be passed on the stack when there are still free integer
2906 // registers available (this would typically imply large structs being passed
2907 // by value), so this seems like a fair tradeoff for now.
2908 //
2909 // We can revisit this if the backend grows support for 'onstack' parameter
2910 // attributes. See PR12193.
2911 if (freeIntRegs == 0) {
2912 uint64_t Size = getContext().getTypeSize(Ty);
2913
2914 // If this type fits in an eightbyte, coerce it into the matching integral
2915 // type, which will end up on the stack (with alignment 8).
2916 if (Align == 8 && Size <= 64)
2917 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2918 Size));
2919 }
2920
John McCall7f416cc2015-09-08 08:05:57 +00002921 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002922}
2923
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002924/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2925/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002926llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002927 // Wrapper structs/arrays that only contain vectors are passed just like
2928 // vectors; strip them off if present.
2929 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2930 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002931
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002932 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002933 if (isa<llvm::VectorType>(IRType) ||
2934 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002935 return IRType;
2936
2937 // We couldn't find the preferred IR vector type for 'Ty'.
2938 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002939 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002940
2941 // Return a LLVM IR vector type based on the size of 'Ty'.
2942 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2943 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002944}
2945
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002946/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2947/// is known to either be off the end of the specified type or being in
2948/// alignment padding. The user type specified is known to be at most 128 bits
2949/// in size, and have passed through X86_64ABIInfo::classify with a successful
2950/// classification that put one of the two halves in the INTEGER class.
2951///
2952/// It is conservatively correct to return false.
2953static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2954 unsigned EndBit, ASTContext &Context) {
2955 // If the bytes being queried are off the end of the type, there is no user
2956 // data hiding here. This handles analysis of builtins, vectors and other
2957 // types that don't contain interesting padding.
2958 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2959 if (TySize <= StartBit)
2960 return true;
2961
Chris Lattner98076a22010-07-29 07:43:55 +00002962 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2963 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2964 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2965
2966 // Check each element to see if the element overlaps with the queried range.
2967 for (unsigned i = 0; i != NumElts; ++i) {
2968 // If the element is after the span we care about, then we're done..
2969 unsigned EltOffset = i*EltSize;
2970 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002971
Chris Lattner98076a22010-07-29 07:43:55 +00002972 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2973 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2974 EndBit-EltOffset, Context))
2975 return false;
2976 }
2977 // If it overlaps no elements, then it is safe to process as padding.
2978 return true;
2979 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002980
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002981 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2982 const RecordDecl *RD = RT->getDecl();
2983 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002984
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002985 // If this is a C++ record, check the bases first.
2986 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002987 for (const auto &I : CXXRD->bases()) {
2988 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002989 "Unexpected base class!");
2990 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002991 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002992
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002993 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002994 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002995 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002996
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002997 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002998 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002999 EndBit-BaseOffset, Context))
3000 return false;
3001 }
3002 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003003
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003004 // Verify that no field has data that overlaps the region of interest. Yes
3005 // this could be sped up a lot by being smarter about queried fields,
3006 // however we're only looking at structs up to 16 bytes, so we don't care
3007 // much.
3008 unsigned idx = 0;
3009 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3010 i != e; ++i, ++idx) {
3011 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003012
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003013 // If we found a field after the region we care about, then we're done.
3014 if (FieldOffset >= EndBit) break;
3015
3016 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3017 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3018 Context))
3019 return false;
3020 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 // If nothing in this record overlapped the area of interest, then we're
3023 // clean.
3024 return true;
3025 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003026
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003027 return false;
3028}
3029
Chris Lattnere556a712010-07-29 18:39:32 +00003030/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3031/// float member at the specified offset. For example, {int,{float}} has a
3032/// float at offset 4. It is conservatively correct for this routine to return
3033/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003034static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003035 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003036 // Base case if we find a float.
3037 if (IROffset == 0 && IRType->isFloatTy())
3038 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattnere556a712010-07-29 18:39:32 +00003040 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003041 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003042 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3043 unsigned Elt = SL->getElementContainingOffset(IROffset);
3044 IROffset -= SL->getElementOffset(Elt);
3045 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3046 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003047
Chris Lattnere556a712010-07-29 18:39:32 +00003048 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003049 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3050 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003051 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3052 IROffset -= IROffset/EltSize*EltSize;
3053 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3054 }
3055
3056 return false;
3057}
3058
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003059
3060/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3061/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003062llvm::Type *X86_64ABIInfo::
3063GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003064 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003065 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003066 // pass as float if the last 4 bytes is just padding. This happens for
3067 // structs that contain 3 floats.
3068 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3069 SourceOffset*8+64, getContext()))
3070 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003071
Chris Lattnere556a712010-07-29 18:39:32 +00003072 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3073 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3074 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003075 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3076 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003077 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003078
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003079 return llvm::Type::getDoubleTy(getVMContext());
3080}
3081
3082
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003083/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3084/// an 8-byte GPR. This means that we either have a scalar or we are talking
3085/// about the high or low part of an up-to-16-byte struct. This routine picks
3086/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003087/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3088/// etc).
3089///
3090/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3091/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3092/// the 8-byte value references. PrefType may be null.
3093///
Alp Toker9907f082014-07-09 14:06:35 +00003094/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003095/// an offset into this that we're processing (which is always either 0 or 8).
3096///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003097llvm::Type *X86_64ABIInfo::
3098GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003099 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003100 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3101 // returning an 8-byte unit starting with it. See if we can safely use it.
3102 if (IROffset == 0) {
3103 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003104 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3105 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003106 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003107
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003108 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3109 // goodness in the source type is just tail padding. This is allowed to
3110 // kick in for struct {double,int} on the int, but not on
3111 // struct{double,int,int} because we wouldn't return the second int. We
3112 // have to do this analysis on the source type because we can't depend on
3113 // unions being lowered a specific way etc.
3114 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003115 IRType->isIntegerTy(32) ||
3116 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3117 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3118 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003119
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003120 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3121 SourceOffset*8+64, getContext()))
3122 return IRType;
3123 }
3124 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003125
Chris Lattner2192fe52011-07-18 04:24:23 +00003126 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003127 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003128 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003129 if (IROffset < SL->getSizeInBytes()) {
3130 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3131 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003132
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003133 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3134 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003135 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003136 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003137
Chris Lattner2192fe52011-07-18 04:24:23 +00003138 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003139 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003140 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003141 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003142 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3143 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003144 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003145
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003146 // Okay, we don't have any better idea of what to pass, so we pass this in an
3147 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003148 unsigned TySizeInBytes =
3149 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003150
Chris Lattner3f763422010-07-29 17:34:39 +00003151 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003152
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003153 // It is always safe to classify this as an integer type up to i64 that
3154 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003155 return llvm::IntegerType::get(getVMContext(),
3156 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003157}
3158
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003159
3160/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3161/// be used as elements of a two register pair to pass or return, return a
3162/// first class aggregate to represent them. For example, if the low part of
3163/// a by-value argument should be passed as i32* and the high part as float,
3164/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003165static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003166GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003167 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003168 // In order to correctly satisfy the ABI, we need to the high part to start
3169 // at offset 8. If the high and low parts we inferred are both 4-byte types
3170 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3171 // the second element at offset 8. Check for this:
3172 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3173 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003174 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003175 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003176
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003177 // To handle this, we have to increase the size of the low part so that the
3178 // second element will start at an 8 byte offset. We can't increase the size
3179 // of the second element because it might make us access off the end of the
3180 // struct.
3181 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003182 // There are usually two sorts of types the ABI generation code can produce
3183 // for the low part of a pair that aren't 8 bytes in size: float or
3184 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3185 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003186 // Promote these to a larger type.
3187 if (Lo->isFloatTy())
3188 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3189 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003190 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3191 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003192 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3193 }
3194 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003195
Serge Guelton1d993272017-05-09 19:31:30 +00003196 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003197
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003198 // Verify that the second element is at an 8-byte offset.
3199 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3200 "Invalid x86-64 argument pair!");
3201 return Result;
3202}
3203
Chris Lattner31faff52010-07-28 23:06:14 +00003204ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003205classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003206 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3207 // classification algorithm.
3208 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003209 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003210
3211 // Check some invariants.
3212 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003213 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3214
Craig Topper8a13c412014-05-21 05:09:00 +00003215 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003216 switch (Lo) {
3217 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003218 if (Hi == NoClass)
3219 return ABIArgInfo::getIgnore();
3220 // If the low part is just padding, it takes no register, leave ResType
3221 // null.
3222 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3223 "Unknown missing lo part");
3224 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003225
3226 case SSEUp:
3227 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003228 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003229
3230 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3231 // hidden argument.
3232 case Memory:
3233 return getIndirectReturnResult(RetTy);
3234
3235 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3236 // available register of the sequence %rax, %rdx is used.
3237 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003238 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003239
Chris Lattner1f3a0632010-07-29 21:42:50 +00003240 // If we have a sign or zero extended integer, make sure to return Extend
3241 // so that the parameter gets the right LLVM IR attributes.
3242 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3243 // Treat an enum type as its underlying type.
3244 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3245 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003246
Chris Lattner1f3a0632010-07-29 21:42:50 +00003247 if (RetTy->isIntegralOrEnumerationType() &&
3248 RetTy->isPromotableIntegerType())
3249 return ABIArgInfo::getExtend();
3250 }
Chris Lattner31faff52010-07-28 23:06:14 +00003251 break;
3252
3253 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3254 // available SSE register of the sequence %xmm0, %xmm1 is used.
3255 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003256 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003257 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003258
3259 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3260 // returned on the X87 stack in %st0 as 80-bit x87 number.
3261 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003262 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003263 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003264
3265 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3266 // part of the value is returned in %st0 and the imaginary part in
3267 // %st1.
3268 case ComplexX87:
3269 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003270 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003271 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003272 break;
3273 }
3274
Craig Topper8a13c412014-05-21 05:09:00 +00003275 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003276 switch (Hi) {
3277 // Memory was handled previously and X87 should
3278 // never occur as a hi class.
3279 case Memory:
3280 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003281 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003282
3283 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003284 case NoClass:
3285 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003286
Chris Lattner52b3c132010-09-01 00:20:33 +00003287 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003288 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003289 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3290 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003291 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003292 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003293 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003294 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3295 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003296 break;
3297
3298 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003299 // is passed in the next available eightbyte chunk if the last used
3300 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003301 //
Chris Lattner57540c52011-04-15 05:22:18 +00003302 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003303 case SSEUp:
3304 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003305 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003306 break;
3307
3308 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3309 // returned together with the previous X87 value in %st0.
3310 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003311 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003312 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003313 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003314 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003315 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003316 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003317 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3318 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003319 }
Chris Lattner31faff52010-07-28 23:06:14 +00003320 break;
3321 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003322
Chris Lattner52b3c132010-09-01 00:20:33 +00003323 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003324 // known to pass in the high eightbyte of the result. We do this by forming a
3325 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003326 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003327 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003328
Chris Lattner1f3a0632010-07-29 21:42:50 +00003329 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003330}
3331
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003332ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003333 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3334 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003335 const
3336{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003337 Ty = useFirstFieldIfTransparentUnion(Ty);
3338
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003339 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003340 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003341
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003342 // Check some invariants.
3343 // FIXME: Enforce these by construction.
3344 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003345 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3346
3347 neededInt = 0;
3348 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003349 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003350 switch (Lo) {
3351 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003352 if (Hi == NoClass)
3353 return ABIArgInfo::getIgnore();
3354 // If the low part is just padding, it takes no register, leave ResType
3355 // null.
3356 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3357 "Unknown missing lo part");
3358 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003359
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003360 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3361 // on the stack.
3362 case Memory:
3363
3364 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3365 // COMPLEX_X87, it is passed in memory.
3366 case X87:
3367 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003368 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003369 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003370 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003371
3372 case SSEUp:
3373 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003374 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003375
3376 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3377 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3378 // and %r9 is used.
3379 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003380 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003381
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003382 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003383 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003384
3385 // If we have a sign or zero extended integer, make sure to return Extend
3386 // so that the parameter gets the right LLVM IR attributes.
3387 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3388 // Treat an enum type as its underlying type.
3389 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3390 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003391
Chris Lattner1f3a0632010-07-29 21:42:50 +00003392 if (Ty->isIntegralOrEnumerationType() &&
3393 Ty->isPromotableIntegerType())
3394 return ABIArgInfo::getExtend();
3395 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003396
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003397 break;
3398
3399 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3400 // available SSE register is used, the registers are taken in the
3401 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003402 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003403 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003404 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003405 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406 break;
3407 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003408 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003409
Craig Topper8a13c412014-05-21 05:09:00 +00003410 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003411 switch (Hi) {
3412 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003413 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003414 // which is passed in memory.
3415 case Memory:
3416 case X87:
3417 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003418 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003419
3420 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003421
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003422 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003423 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003424 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003425 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003426
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003427 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3428 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003429 break;
3430
3431 // X87Up generally doesn't occur here (long double is passed in
3432 // memory), except in situations involving unions.
3433 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003434 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003435 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003436
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003437 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3438 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003439
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440 ++neededSSE;
3441 break;
3442
3443 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3444 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003445 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003446 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003447 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003448 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003449 break;
3450 }
3451
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003452 // If a high part was specified, merge it together with the low part. It is
3453 // known to pass in the high eightbyte of the result. We do this by forming a
3454 // first class struct aggregate with the high and low part: {low, high}
3455 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003456 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003457
Chris Lattner1f3a0632010-07-29 21:42:50 +00003458 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003459}
3460
Erich Keane757d3172016-11-02 18:29:35 +00003461ABIArgInfo
3462X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3463 unsigned &NeededSSE) const {
3464 auto RT = Ty->getAs<RecordType>();
3465 assert(RT && "classifyRegCallStructType only valid with struct types");
3466
3467 if (RT->getDecl()->hasFlexibleArrayMember())
3468 return getIndirectReturnResult(Ty);
3469
3470 // Sum up bases
3471 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3472 if (CXXRD->isDynamicClass()) {
3473 NeededInt = NeededSSE = 0;
3474 return getIndirectReturnResult(Ty);
3475 }
3476
3477 for (const auto &I : CXXRD->bases())
3478 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3479 .isIndirect()) {
3480 NeededInt = NeededSSE = 0;
3481 return getIndirectReturnResult(Ty);
3482 }
3483 }
3484
3485 // Sum up members
3486 for (const auto *FD : RT->getDecl()->fields()) {
3487 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3488 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3489 .isIndirect()) {
3490 NeededInt = NeededSSE = 0;
3491 return getIndirectReturnResult(Ty);
3492 }
3493 } else {
3494 unsigned LocalNeededInt, LocalNeededSSE;
3495 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3496 LocalNeededSSE, true)
3497 .isIndirect()) {
3498 NeededInt = NeededSSE = 0;
3499 return getIndirectReturnResult(Ty);
3500 }
3501 NeededInt += LocalNeededInt;
3502 NeededSSE += LocalNeededSSE;
3503 }
3504 }
3505
3506 return ABIArgInfo::getDirect();
3507}
3508
3509ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3510 unsigned &NeededInt,
3511 unsigned &NeededSSE) const {
3512
3513 NeededInt = 0;
3514 NeededSSE = 0;
3515
3516 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3517}
3518
Chris Lattner22326a12010-07-29 02:31:05 +00003519void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003520
Erich Keane757d3172016-11-02 18:29:35 +00003521 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003522
3523 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003524 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3525 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3526 unsigned NeededInt, NeededSSE;
3527
Erich Keanede1b2a92017-07-21 18:50:36 +00003528 if (!getCXXABI().classifyReturnType(FI)) {
3529 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3530 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3531 FI.getReturnInfo() =
3532 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3533 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3534 FreeIntRegs -= NeededInt;
3535 FreeSSERegs -= NeededSSE;
3536 } else {
3537 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3538 }
3539 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3540 // Complex Long Double Type is passed in Memory when Regcall
3541 // calling convention is used.
3542 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3543 if (getContext().getCanonicalType(CT->getElementType()) ==
3544 getContext().LongDoubleTy)
3545 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3546 } else
3547 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3548 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003549
3550 // If the return value is indirect, then the hidden argument is consuming one
3551 // integer register.
3552 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003553 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003554
Peter Collingbournef7706832014-12-12 23:41:25 +00003555 // The chain argument effectively gives us another free register.
3556 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003557 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003558
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003559 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003560 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3561 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003562 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003563 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003564 it != ie; ++it, ++ArgNo) {
3565 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003566
Erich Keane757d3172016-11-02 18:29:35 +00003567 if (IsRegCall && it->type->isStructureOrClassType())
3568 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3569 else
3570 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3571 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003572
3573 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3574 // eightbyte of an argument, the whole argument is passed on the
3575 // stack. If registers have already been assigned for some
3576 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003577 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3578 FreeIntRegs -= NeededInt;
3579 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003580 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003581 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003582 }
3583 }
3584}
3585
John McCall7f416cc2015-09-08 08:05:57 +00003586static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3587 Address VAListAddr, QualType Ty) {
3588 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3589 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003590 llvm::Value *overflow_arg_area =
3591 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3592
3593 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3594 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003595 // It isn't stated explicitly in the standard, but in practice we use
3596 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003597 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3598 if (Align > CharUnits::fromQuantity(8)) {
3599 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3600 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003601 }
3602
3603 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003604 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003605 llvm::Value *Res =
3606 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003607 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003608
3609 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3610 // l->overflow_arg_area + sizeof(type).
3611 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3612 // an 8 byte boundary.
3613
3614 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003615 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003616 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003617 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3618 "overflow_arg_area.next");
3619 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3620
3621 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003622 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003623}
3624
John McCall7f416cc2015-09-08 08:05:57 +00003625Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3626 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003627 // Assume that va_list type is correct; should be pointer to LLVM type:
3628 // struct {
3629 // i32 gp_offset;
3630 // i32 fp_offset;
3631 // i8* overflow_arg_area;
3632 // i8* reg_save_area;
3633 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003634 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003635
John McCall7f416cc2015-09-08 08:05:57 +00003636 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003637 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003638 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639
3640 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3641 // in the registers. If not go to step 7.
3642 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003643 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003644
3645 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3646 // general purpose registers needed to pass type and num_fp to hold
3647 // the number of floating point registers needed.
3648
3649 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3650 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3651 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3652 //
3653 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3654 // register save space).
3655
Craig Topper8a13c412014-05-21 05:09:00 +00003656 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003657 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3658 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003659 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003660 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003661 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3662 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003663 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003664 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3665 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003666 }
3667
3668 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003669 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003670 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3671 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003672 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3673 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003674 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3675 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003676 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3677 }
3678
3679 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3680 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3681 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3682 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3683
3684 // Emit code to load the value if it was passed in registers.
3685
3686 CGF.EmitBlock(InRegBlock);
3687
3688 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3689 // an offset of l->gp_offset and/or l->fp_offset. This may require
3690 // copying to a temporary location in case the parameter is passed
3691 // in different register classes or requires an alignment greater
3692 // than 8 for general purpose registers and 16 for XMM registers.
3693 //
3694 // FIXME: This really results in shameful code when we end up needing to
3695 // collect arguments from different places; often what should result in a
3696 // simple assembling of a structure from scattered addresses has many more
3697 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003698 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003699 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3700 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3701 "reg_save_area");
3702
3703 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003704 if (neededInt && neededSSE) {
3705 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003706 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003707 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003708 Address Tmp = CGF.CreateMemTemp(Ty);
3709 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003710 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003711 llvm::Type *TyLo = ST->getElementType(0);
3712 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003713 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003714 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003715 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3716 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003717 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3718 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003719 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3720 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003721
John McCall7f416cc2015-09-08 08:05:57 +00003722 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003723 // FIXME: Our choice of alignment here and below is probably pessimistic.
3724 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3725 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3726 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003727 CGF.Builder.CreateStore(V,
3728 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3729
3730 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003731 V = CGF.Builder.CreateAlignedLoad(
3732 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3733 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003734 CharUnits Offset = CharUnits::fromQuantity(
3735 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3736 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3737
3738 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003739 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003740 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3741 CharUnits::fromQuantity(8));
3742 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003743
3744 // Copy to a temporary if necessary to ensure the appropriate alignment.
3745 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003746 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003747 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003748 CharUnits TyAlign = SizeAlign.second;
3749
3750 // Copy into a temporary if the type is more aligned than the
3751 // register save area.
3752 if (TyAlign.getQuantity() > 8) {
3753 Address Tmp = CGF.CreateMemTemp(Ty);
3754 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003755 RegAddr = Tmp;
3756 }
John McCall7f416cc2015-09-08 08:05:57 +00003757
Chris Lattner0cf24192010-06-28 20:05:43 +00003758 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003759 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3760 CharUnits::fromQuantity(16));
3761 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003762 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003763 assert(neededSSE == 2 && "Invalid number of needed registers!");
3764 // SSE registers are spaced 16 bytes apart in the register save
3765 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003766 // The ABI isn't explicit about this, but it seems reasonable
3767 // to assume that the slots are 16-byte aligned, since the stack is
3768 // naturally 16-byte aligned and the prologue is expected to store
3769 // all the SSE registers to the RSA.
3770 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3771 CharUnits::fromQuantity(16));
3772 Address RegAddrHi =
3773 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3774 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003775 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003776 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003777 llvm::Value *V;
3778 Address Tmp = CGF.CreateMemTemp(Ty);
3779 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3780 V = CGF.Builder.CreateLoad(
3781 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3782 CGF.Builder.CreateStore(V,
3783 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3784 V = CGF.Builder.CreateLoad(
3785 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3786 CGF.Builder.CreateStore(V,
3787 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3788
3789 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003790 }
3791
3792 // AMD64-ABI 3.5.7p5: Step 5. Set:
3793 // l->gp_offset = l->gp_offset + num_gp * 8
3794 // l->fp_offset = l->fp_offset + num_fp * 16.
3795 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003796 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003797 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3798 gp_offset_p);
3799 }
3800 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003801 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003802 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3803 fp_offset_p);
3804 }
3805 CGF.EmitBranch(ContBlock);
3806
3807 // Emit code to load the value if it was passed in memory.
3808
3809 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003810 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003811
3812 // Return the appropriate result.
3813
3814 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003815 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3816 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003817 return ResAddr;
3818}
3819
Charles Davisc7d5c942015-09-17 20:55:33 +00003820Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3821 QualType Ty) const {
3822 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3823 CGF.getContext().getTypeInfoInChars(Ty),
3824 CharUnits::fromQuantity(8),
3825 /*allowHigherAlign*/ false);
3826}
3827
Erich Keane521ed962017-01-05 00:20:51 +00003828ABIArgInfo
3829WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3830 const ABIArgInfo &current) const {
3831 // Assumes vectorCall calling convention.
3832 const Type *Base = nullptr;
3833 uint64_t NumElts = 0;
3834
3835 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3836 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3837 FreeSSERegs -= NumElts;
3838 return getDirectX86Hva();
3839 }
3840 return current;
3841}
3842
Reid Kleckner80944df2014-10-31 22:00:51 +00003843ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003844 bool IsReturnType, bool IsVectorCall,
3845 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003846
3847 if (Ty->isVoidType())
3848 return ABIArgInfo::getIgnore();
3849
3850 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3851 Ty = EnumTy->getDecl()->getIntegerType();
3852
Reid Kleckner80944df2014-10-31 22:00:51 +00003853 TypeInfo Info = getContext().getTypeInfo(Ty);
3854 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003855 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003856
Reid Kleckner9005f412014-05-02 00:51:20 +00003857 const RecordType *RT = Ty->getAs<RecordType>();
3858 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003859 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003860 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003861 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003862 }
3863
3864 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003865 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003866
Reid Kleckner9005f412014-05-02 00:51:20 +00003867 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003868
Reid Kleckner80944df2014-10-31 22:00:51 +00003869 const Type *Base = nullptr;
3870 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003871 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3872 // other targets.
3873 if ((IsVectorCall || IsRegCall) &&
3874 isHomogeneousAggregate(Ty, Base, NumElts)) {
3875 if (IsRegCall) {
3876 if (FreeSSERegs >= NumElts) {
3877 FreeSSERegs -= NumElts;
3878 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3879 return ABIArgInfo::getDirect();
3880 return ABIArgInfo::getExpand();
3881 }
3882 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3883 } else if (IsVectorCall) {
3884 if (FreeSSERegs >= NumElts &&
3885 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3886 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003887 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003888 } else if (IsReturnType) {
3889 return ABIArgInfo::getExpand();
3890 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3891 // HVAs are delayed and reclassified in the 2nd step.
3892 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3893 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003894 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003895 }
3896
Reid Klecknerec87fec2014-05-02 01:17:12 +00003897 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003898 // If the member pointer is represented by an LLVM int or ptr, pass it
3899 // directly.
3900 llvm::Type *LLTy = CGT.ConvertType(Ty);
3901 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3902 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003903 }
3904
Michael Kuperstein4f818702015-02-24 09:35:58 +00003905 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003906 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3907 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003908 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003909 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003910
Reid Kleckner9005f412014-05-02 00:51:20 +00003911 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003912 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003913 }
3914
Julien Lerouge10dcff82014-08-27 00:36:55 +00003915 // Bool type is always extended to the ABI, other builtin types are not
3916 // extended.
3917 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3918 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003919 return ABIArgInfo::getExtend();
3920
Reid Kleckner11a17192015-10-28 22:29:52 +00003921 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3922 // passes them indirectly through memory.
3923 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3924 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003925 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003926 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3927 }
3928
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003929 return ABIArgInfo::getDirect();
3930}
3931
Erich Keane521ed962017-01-05 00:20:51 +00003932void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3933 unsigned FreeSSERegs,
3934 bool IsVectorCall,
3935 bool IsRegCall) const {
3936 unsigned Count = 0;
3937 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003938 // Vectorcall in x64 only permits the first 6 arguments to be passed
3939 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003940 if (Count < VectorcallMaxParamNumAsReg)
3941 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3942 else {
3943 // Since these cannot be passed in registers, pretend no registers
3944 // are left.
3945 unsigned ZeroSSERegsAvail = 0;
3946 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3947 IsVectorCall, IsRegCall);
3948 }
3949 ++Count;
3950 }
3951
Erich Keane521ed962017-01-05 00:20:51 +00003952 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003953 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003954 }
3955}
3956
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003957void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003958 bool IsVectorCall =
3959 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003960 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003961
Erich Keane757d3172016-11-02 18:29:35 +00003962 unsigned FreeSSERegs = 0;
3963 if (IsVectorCall) {
3964 // We can use up to 4 SSE return registers with vectorcall.
3965 FreeSSERegs = 4;
3966 } else if (IsRegCall) {
3967 // RegCall gives us 16 SSE registers.
3968 FreeSSERegs = 16;
3969 }
3970
Reid Kleckner80944df2014-10-31 22:00:51 +00003971 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003972 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3973 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003974
Erich Keane757d3172016-11-02 18:29:35 +00003975 if (IsVectorCall) {
3976 // We can use up to 6 SSE register parameters with vectorcall.
3977 FreeSSERegs = 6;
3978 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003979 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003980 FreeSSERegs = 16;
3981 }
3982
Erich Keane521ed962017-01-05 00:20:51 +00003983 if (IsVectorCall) {
3984 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3985 } else {
3986 for (auto &I : FI.arguments())
3987 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3988 }
3989
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003990}
3991
John McCall7f416cc2015-09-08 08:05:57 +00003992Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3993 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003994
3995 bool IsIndirect = false;
3996
3997 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3998 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3999 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4000 uint64_t Width = getContext().getTypeSize(Ty);
4001 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4002 }
4003
4004 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004005 CGF.getContext().getTypeInfoInChars(Ty),
4006 CharUnits::fromQuantity(8),
4007 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004008}
Chris Lattner0cf24192010-06-28 20:05:43 +00004009
John McCallea8d8bb2010-03-11 00:10:12 +00004010// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004011namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004012/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4013class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004014bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004015public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004016 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4017 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004018
John McCall7f416cc2015-09-08 08:05:57 +00004019 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4020 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004021};
4022
4023class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4024public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004025 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4026 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004027
Craig Topper4f12f102014-03-12 06:41:41 +00004028 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004029 // This is recovered from gcc output.
4030 return 1; // r1 is the dedicated stack pointer
4031 }
4032
4033 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004034 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004035};
4036
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004037}
John McCallea8d8bb2010-03-11 00:10:12 +00004038
James Y Knight29b5f082016-02-24 02:59:33 +00004039// TODO: this implementation is now likely redundant with
4040// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004041Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4042 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004043 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004044 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4045 // TODO: Implement this. For now ignore.
4046 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004047 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004048 }
4049
John McCall7f416cc2015-09-08 08:05:57 +00004050 // struct __va_list_tag {
4051 // unsigned char gpr;
4052 // unsigned char fpr;
4053 // unsigned short reserved;
4054 // void *overflow_arg_area;
4055 // void *reg_save_area;
4056 // };
4057
Roman Divacky8a12d842014-11-03 18:32:54 +00004058 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004059 bool isInt =
4060 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004061 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004062
4063 // All aggregates are passed indirectly? That doesn't seem consistent
4064 // with the argument-lowering code.
4065 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004066
4067 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004068
4069 // The calling convention either uses 1-2 GPRs or 1 FPR.
4070 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004071 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004072 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4073 } else {
4074 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004075 }
John McCall7f416cc2015-09-08 08:05:57 +00004076
4077 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4078
4079 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004080 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004081 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4082 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4083 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004084
Eric Christopher7565e0d2015-05-29 23:09:49 +00004085 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004086 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004087
4088 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4089 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4090 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4091
4092 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4093
John McCall7f416cc2015-09-08 08:05:57 +00004094 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4095 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004096
John McCall7f416cc2015-09-08 08:05:57 +00004097 // Case 1: consume registers.
4098 Address RegAddr = Address::invalid();
4099 {
4100 CGF.EmitBlock(UsingRegs);
4101
4102 Address RegSaveAreaPtr =
4103 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4104 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4105 CharUnits::fromQuantity(8));
4106 assert(RegAddr.getElementType() == CGF.Int8Ty);
4107
4108 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004109 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004110 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4111 CharUnits::fromQuantity(32));
4112 }
4113
4114 // Get the address of the saved value by scaling the number of
4115 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004116 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004117 llvm::Value *RegOffset =
4118 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4119 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4120 RegAddr.getPointer(), RegOffset),
4121 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4122 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4123
4124 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004125 NumRegs =
4126 Builder.CreateAdd(NumRegs,
4127 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004128 Builder.CreateStore(NumRegs, NumRegsAddr);
4129
4130 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004131 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004132
John McCall7f416cc2015-09-08 08:05:57 +00004133 // Case 2: consume space in the overflow area.
4134 Address MemAddr = Address::invalid();
4135 {
4136 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004137
Roman Divacky039b9702016-02-20 08:31:24 +00004138 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4139
John McCall7f416cc2015-09-08 08:05:57 +00004140 // Everything in the overflow area is rounded up to a size of at least 4.
4141 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4142
4143 CharUnits Size;
4144 if (!isIndirect) {
4145 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004146 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004147 } else {
4148 Size = CGF.getPointerSize();
4149 }
4150
4151 Address OverflowAreaAddr =
4152 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004153 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004154 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004155 // Round up address of argument to alignment
4156 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4157 if (Align > OverflowAreaAlign) {
4158 llvm::Value *Ptr = OverflowArea.getPointer();
4159 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4160 Align);
4161 }
4162
John McCall7f416cc2015-09-08 08:05:57 +00004163 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4164
4165 // Increase the overflow area.
4166 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4167 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4168 CGF.EmitBranch(Cont);
4169 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004170
4171 CGF.EmitBlock(Cont);
4172
John McCall7f416cc2015-09-08 08:05:57 +00004173 // Merge the cases with a phi.
4174 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4175 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004176
John McCall7f416cc2015-09-08 08:05:57 +00004177 // Load the pointer if the argument was passed indirectly.
4178 if (isIndirect) {
4179 Result = Address(Builder.CreateLoad(Result, "aggr"),
4180 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004181 }
4182
4183 return Result;
4184}
4185
John McCallea8d8bb2010-03-11 00:10:12 +00004186bool
4187PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4188 llvm::Value *Address) const {
4189 // This is calculated from the LLVM and GCC tables and verified
4190 // against gcc output. AFAIK all ABIs use the same encoding.
4191
4192 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004193
Chris Lattnerece04092012-02-07 00:39:47 +00004194 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004195 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4196 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4197 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4198
4199 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004200 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004201
4202 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004203 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004204
4205 // 64-76 are various 4-byte special-purpose registers:
4206 // 64: mq
4207 // 65: lr
4208 // 66: ctr
4209 // 67: ap
4210 // 68-75 cr0-7
4211 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004212 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004213
4214 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004215 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004216
4217 // 109: vrsave
4218 // 110: vscr
4219 // 111: spe_acc
4220 // 112: spefscr
4221 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004222 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004223
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004224 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004225}
4226
Roman Divackyd966e722012-05-09 18:22:46 +00004227// PowerPC-64
4228
4229namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004230/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004231class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004232public:
4233 enum ABIKind {
4234 ELFv1 = 0,
4235 ELFv2
4236 };
4237
4238private:
4239 static const unsigned GPRBits = 64;
4240 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004241 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004242 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004243
4244 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4245 // will be passed in a QPX register.
4246 bool IsQPXVectorTy(const Type *Ty) const {
4247 if (!HasQPX)
4248 return false;
4249
4250 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4251 unsigned NumElements = VT->getNumElements();
4252 if (NumElements == 1)
4253 return false;
4254
4255 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4256 if (getContext().getTypeSize(Ty) <= 256)
4257 return true;
4258 } else if (VT->getElementType()->
4259 isSpecificBuiltinType(BuiltinType::Float)) {
4260 if (getContext().getTypeSize(Ty) <= 128)
4261 return true;
4262 }
4263 }
4264
4265 return false;
4266 }
4267
4268 bool IsQPXVectorTy(QualType Ty) const {
4269 return IsQPXVectorTy(Ty.getTypePtr());
4270 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004271
4272public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004273 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4274 bool SoftFloatABI)
4275 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4276 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004277
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004278 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004279 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004280
4281 ABIArgInfo classifyReturnType(QualType RetTy) const;
4282 ABIArgInfo classifyArgumentType(QualType Ty) const;
4283
Reid Klecknere9f6a712014-10-31 17:10:41 +00004284 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4285 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4286 uint64_t Members) const override;
4287
Bill Schmidt84d37792012-10-12 19:26:17 +00004288 // TODO: We can add more logic to computeInfo to improve performance.
4289 // Example: For aggregate arguments that fit in a register, we could
4290 // use getDirectInReg (as is done below for structs containing a single
4291 // floating-point value) to avoid pushing them to memory on function
4292 // entry. This would require changing the logic in PPCISelLowering
4293 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004294 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004295 if (!getCXXABI().classifyReturnType(FI))
4296 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004297 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004298 // We rely on the default argument classification for the most part.
4299 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004300 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004301 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004302 if (T) {
4303 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004304 if (IsQPXVectorTy(T) ||
4305 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004306 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004307 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004308 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004309 continue;
4310 }
4311 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004312 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004313 }
4314 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004315
John McCall7f416cc2015-09-08 08:05:57 +00004316 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4317 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004318};
4319
4320class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004321
Bill Schmidt25cb3492012-10-03 19:18:57 +00004322public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004323 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004324 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4325 bool SoftFloatABI)
4326 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4327 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004328
Craig Topper4f12f102014-03-12 06:41:41 +00004329 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004330 // This is recovered from gcc output.
4331 return 1; // r1 is the dedicated stack pointer
4332 }
4333
4334 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004335 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004336};
4337
Roman Divackyd966e722012-05-09 18:22:46 +00004338class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4339public:
4340 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4341
Craig Topper4f12f102014-03-12 06:41:41 +00004342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004343 // This is recovered from gcc output.
4344 return 1; // r1 is the dedicated stack pointer
4345 }
4346
4347 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004348 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004349};
4350
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004351}
Roman Divackyd966e722012-05-09 18:22:46 +00004352
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004353// Return true if the ABI requires Ty to be passed sign- or zero-
4354// extended to 64 bits.
4355bool
4356PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4357 // Treat an enum type as its underlying type.
4358 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4359 Ty = EnumTy->getDecl()->getIntegerType();
4360
4361 // Promotable integer types are required to be promoted by the ABI.
4362 if (Ty->isPromotableIntegerType())
4363 return true;
4364
4365 // In addition to the usual promotable integer types, we also need to
4366 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4367 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4368 switch (BT->getKind()) {
4369 case BuiltinType::Int:
4370 case BuiltinType::UInt:
4371 return true;
4372 default:
4373 break;
4374 }
4375
4376 return false;
4377}
4378
John McCall7f416cc2015-09-08 08:05:57 +00004379/// isAlignedParamType - Determine whether a type requires 16-byte or
4380/// higher alignment in the parameter area. Always returns at least 8.
4381CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004382 // Complex types are passed just like their elements.
4383 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4384 Ty = CTy->getElementType();
4385
4386 // Only vector types of size 16 bytes need alignment (larger types are
4387 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004388 if (IsQPXVectorTy(Ty)) {
4389 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004390 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004391
John McCall7f416cc2015-09-08 08:05:57 +00004392 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004393 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004394 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004395 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004396
4397 // For single-element float/vector structs, we consider the whole type
4398 // to have the same alignment requirements as its single element.
4399 const Type *AlignAsType = nullptr;
4400 const Type *EltType = isSingleElementStruct(Ty, getContext());
4401 if (EltType) {
4402 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004403 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004404 getContext().getTypeSize(EltType) == 128) ||
4405 (BT && BT->isFloatingPoint()))
4406 AlignAsType = EltType;
4407 }
4408
Ulrich Weigandb7122372014-07-21 00:48:09 +00004409 // Likewise for ELFv2 homogeneous aggregates.
4410 const Type *Base = nullptr;
4411 uint64_t Members = 0;
4412 if (!AlignAsType && Kind == ELFv2 &&
4413 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4414 AlignAsType = Base;
4415
Ulrich Weigand581badc2014-07-10 17:20:07 +00004416 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004417 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4418 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004419 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004420
John McCall7f416cc2015-09-08 08:05:57 +00004421 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004422 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004423 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004424 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004425
4426 // Otherwise, we only need alignment for any aggregate type that
4427 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004428 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4429 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004430 return CharUnits::fromQuantity(32);
4431 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004432 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004433
John McCall7f416cc2015-09-08 08:05:57 +00004434 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004435}
4436
Ulrich Weigandb7122372014-07-21 00:48:09 +00004437/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4438/// aggregate. Base is set to the base element type, and Members is set
4439/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004440bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4441 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004442 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4443 uint64_t NElements = AT->getSize().getZExtValue();
4444 if (NElements == 0)
4445 return false;
4446 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4447 return false;
4448 Members *= NElements;
4449 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4450 const RecordDecl *RD = RT->getDecl();
4451 if (RD->hasFlexibleArrayMember())
4452 return false;
4453
4454 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004455
4456 // If this is a C++ record, check the bases first.
4457 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4458 for (const auto &I : CXXRD->bases()) {
4459 // Ignore empty records.
4460 if (isEmptyRecord(getContext(), I.getType(), true))
4461 continue;
4462
4463 uint64_t FldMembers;
4464 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4465 return false;
4466
4467 Members += FldMembers;
4468 }
4469 }
4470
Ulrich Weigandb7122372014-07-21 00:48:09 +00004471 for (const auto *FD : RD->fields()) {
4472 // Ignore (non-zero arrays of) empty records.
4473 QualType FT = FD->getType();
4474 while (const ConstantArrayType *AT =
4475 getContext().getAsConstantArrayType(FT)) {
4476 if (AT->getSize().getZExtValue() == 0)
4477 return false;
4478 FT = AT->getElementType();
4479 }
4480 if (isEmptyRecord(getContext(), FT, true))
4481 continue;
4482
4483 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4484 if (getContext().getLangOpts().CPlusPlus &&
4485 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4486 continue;
4487
4488 uint64_t FldMembers;
4489 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4490 return false;
4491
4492 Members = (RD->isUnion() ?
4493 std::max(Members, FldMembers) : Members + FldMembers);
4494 }
4495
4496 if (!Base)
4497 return false;
4498
4499 // Ensure there is no padding.
4500 if (getContext().getTypeSize(Base) * Members !=
4501 getContext().getTypeSize(Ty))
4502 return false;
4503 } else {
4504 Members = 1;
4505 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4506 Members = 2;
4507 Ty = CT->getElementType();
4508 }
4509
Reid Klecknere9f6a712014-10-31 17:10:41 +00004510 // Most ABIs only support float, double, and some vector type widths.
4511 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004512 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004513
4514 // The base type must be the same for all members. Types that
4515 // agree in both total size and mode (float vs. vector) are
4516 // treated as being equivalent here.
4517 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004518 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004519 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004520 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4521 // so make sure to widen it explicitly.
4522 if (const VectorType *VT = Base->getAs<VectorType>()) {
4523 QualType EltTy = VT->getElementType();
4524 unsigned NumElements =
4525 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4526 Base = getContext()
4527 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4528 .getTypePtr();
4529 }
4530 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004531
4532 if (Base->isVectorType() != TyPtr->isVectorType() ||
4533 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4534 return false;
4535 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004536 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4537}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004538
Reid Klecknere9f6a712014-10-31 17:10:41 +00004539bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4540 // Homogeneous aggregates for ELFv2 must have base types of float,
4541 // double, long double, or 128-bit vectors.
4542 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4543 if (BT->getKind() == BuiltinType::Float ||
4544 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004545 BT->getKind() == BuiltinType::LongDouble) {
4546 if (IsSoftFloatABI)
4547 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004548 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004549 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004550 }
4551 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004552 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004553 return true;
4554 }
4555 return false;
4556}
4557
4558bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4559 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004560 // Vector types require one register, floating point types require one
4561 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004562 uint32_t NumRegs =
4563 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004564
4565 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004566 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004567}
4568
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004569ABIArgInfo
4570PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004571 Ty = useFirstFieldIfTransparentUnion(Ty);
4572
Bill Schmidt90b22c92012-11-27 02:46:43 +00004573 if (Ty->isAnyComplexType())
4574 return ABIArgInfo::getDirect();
4575
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004576 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4577 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004578 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004579 uint64_t Size = getContext().getTypeSize(Ty);
4580 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004581 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004582 else if (Size < 128) {
4583 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4584 return ABIArgInfo::getDirect(CoerceTy);
4585 }
4586 }
4587
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004588 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004589 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004590 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004591
John McCall7f416cc2015-09-08 08:05:57 +00004592 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4593 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004594
4595 // ELFv2 homogeneous aggregates are passed as array types.
4596 const Type *Base = nullptr;
4597 uint64_t Members = 0;
4598 if (Kind == ELFv2 &&
4599 isHomogeneousAggregate(Ty, Base, Members)) {
4600 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4601 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4602 return ABIArgInfo::getDirect(CoerceTy);
4603 }
4604
Ulrich Weigand601957f2014-07-21 00:56:36 +00004605 // If an aggregate may end up fully in registers, we do not
4606 // use the ByVal method, but pass the aggregate as array.
4607 // This is usually beneficial since we avoid forcing the
4608 // back-end to store the argument to memory.
4609 uint64_t Bits = getContext().getTypeSize(Ty);
4610 if (Bits > 0 && Bits <= 8 * GPRBits) {
4611 llvm::Type *CoerceTy;
4612
4613 // Types up to 8 bytes are passed as integer type (which will be
4614 // properly aligned in the argument save area doubleword).
4615 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004616 CoerceTy =
4617 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004618 // Larger types are passed as arrays, with the base type selected
4619 // according to the required alignment in the save area.
4620 else {
4621 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004622 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004623 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4624 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4625 }
4626
4627 return ABIArgInfo::getDirect(CoerceTy);
4628 }
4629
Ulrich Weigandb7122372014-07-21 00:48:09 +00004630 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004631 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4632 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004633 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004634 }
4635
4636 return (isPromotableTypeForABI(Ty) ?
4637 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4638}
4639
4640ABIArgInfo
4641PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4642 if (RetTy->isVoidType())
4643 return ABIArgInfo::getIgnore();
4644
Bill Schmidta3d121c2012-12-17 04:20:17 +00004645 if (RetTy->isAnyComplexType())
4646 return ABIArgInfo::getDirect();
4647
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004648 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4649 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004650 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004651 uint64_t Size = getContext().getTypeSize(RetTy);
4652 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004653 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004654 else if (Size < 128) {
4655 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4656 return ABIArgInfo::getDirect(CoerceTy);
4657 }
4658 }
4659
Ulrich Weigandb7122372014-07-21 00:48:09 +00004660 if (isAggregateTypeForABI(RetTy)) {
4661 // ELFv2 homogeneous aggregates are returned as array types.
4662 const Type *Base = nullptr;
4663 uint64_t Members = 0;
4664 if (Kind == ELFv2 &&
4665 isHomogeneousAggregate(RetTy, Base, Members)) {
4666 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4667 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4668 return ABIArgInfo::getDirect(CoerceTy);
4669 }
4670
4671 // ELFv2 small aggregates are returned in up to two registers.
4672 uint64_t Bits = getContext().getTypeSize(RetTy);
4673 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4674 if (Bits == 0)
4675 return ABIArgInfo::getIgnore();
4676
4677 llvm::Type *CoerceTy;
4678 if (Bits > GPRBits) {
4679 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004680 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004681 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004682 CoerceTy =
4683 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004684 return ABIArgInfo::getDirect(CoerceTy);
4685 }
4686
4687 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004688 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004689 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004690
4691 return (isPromotableTypeForABI(RetTy) ?
4692 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4693}
4694
Bill Schmidt25cb3492012-10-03 19:18:57 +00004695// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004696Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4697 QualType Ty) const {
4698 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4699 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004700
John McCall7f416cc2015-09-08 08:05:57 +00004701 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004702
Bill Schmidt924c4782013-01-14 17:45:36 +00004703 // If we have a complex type and the base type is smaller than 8 bytes,
4704 // the ABI calls for the real and imaginary parts to be right-adjusted
4705 // in separate doublewords. However, Clang expects us to produce a
4706 // pointer to a structure with the two parts packed tightly. So generate
4707 // loads of the real and imaginary parts relative to the va_list pointer,
4708 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004709 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4710 CharUnits EltSize = TypeInfo.first / 2;
4711 if (EltSize < SlotSize) {
4712 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4713 SlotSize * 2, SlotSize,
4714 SlotSize, /*AllowHigher*/ true);
4715
4716 Address RealAddr = Addr;
4717 Address ImagAddr = RealAddr;
4718 if (CGF.CGM.getDataLayout().isBigEndian()) {
4719 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4720 SlotSize - EltSize);
4721 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4722 2 * SlotSize - EltSize);
4723 } else {
4724 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4725 }
4726
4727 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4728 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4729 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4730 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4731 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4732
4733 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4734 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4735 /*init*/ true);
4736 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004737 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004738 }
4739
John McCall7f416cc2015-09-08 08:05:57 +00004740 // Otherwise, just use the general rule.
4741 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4742 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004743}
4744
4745static bool
4746PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4747 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004748 // This is calculated from the LLVM and GCC tables and verified
4749 // against gcc output. AFAIK all ABIs use the same encoding.
4750
4751 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4752
4753 llvm::IntegerType *i8 = CGF.Int8Ty;
4754 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4755 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4756 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4757
4758 // 0-31: r0-31, the 8-byte general-purpose registers
4759 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4760
4761 // 32-63: fp0-31, the 8-byte floating-point registers
4762 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4763
Hal Finkel84832a72016-08-30 02:38:34 +00004764 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004765 // 64: mq
4766 // 65: lr
4767 // 66: ctr
4768 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004769 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4770
4771 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004772 // 68-75 cr0-7
4773 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004774 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004775
4776 // 77-108: v0-31, the 16-byte vector registers
4777 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4778
4779 // 109: vrsave
4780 // 110: vscr
4781 // 111: spe_acc
4782 // 112: spefscr
4783 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004784 // 114: tfhar
4785 // 115: tfiar
4786 // 116: texasr
4787 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004788
4789 return false;
4790}
John McCallea8d8bb2010-03-11 00:10:12 +00004791
Bill Schmidt25cb3492012-10-03 19:18:57 +00004792bool
4793PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4794 CodeGen::CodeGenFunction &CGF,
4795 llvm::Value *Address) const {
4796
4797 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4798}
4799
4800bool
4801PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4802 llvm::Value *Address) const {
4803
4804 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4805}
4806
Chris Lattner0cf24192010-06-28 20:05:43 +00004807//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004808// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004809//===----------------------------------------------------------------------===//
4810
4811namespace {
4812
John McCall12f23522016-04-04 18:33:08 +00004813class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004814public:
4815 enum ABIKind {
4816 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004817 DarwinPCS,
4818 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004819 };
4820
4821private:
4822 ABIKind Kind;
4823
4824public:
John McCall12f23522016-04-04 18:33:08 +00004825 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4826 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004827
4828private:
4829 ABIKind getABIKind() const { return Kind; }
4830 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4831
4832 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004833 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004834 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4835 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4836 uint64_t Members) const override;
4837
Tim Northovera2ee4332014-03-29 15:09:45 +00004838 bool isIllegalVectorType(QualType Ty) const;
4839
David Blaikie1cbb9712014-11-14 19:09:44 +00004840 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004841 if (!getCXXABI().classifyReturnType(FI))
4842 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004843
Tim Northoverb047bfa2014-11-27 21:02:49 +00004844 for (auto &it : FI.arguments())
4845 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004846 }
4847
John McCall7f416cc2015-09-08 08:05:57 +00004848 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4849 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004850
John McCall7f416cc2015-09-08 08:05:57 +00004851 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4852 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004853
John McCall7f416cc2015-09-08 08:05:57 +00004854 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4855 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004856 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4857 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4858 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004859 }
John McCall12f23522016-04-04 18:33:08 +00004860
Martin Storsjo502de222017-07-13 17:59:14 +00004861 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4862 QualType Ty) const override;
4863
John McCall12f23522016-04-04 18:33:08 +00004864 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4865 ArrayRef<llvm::Type*> scalars,
4866 bool asReturnValue) const override {
4867 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4868 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004869 bool isSwiftErrorInRegister() const override {
4870 return true;
4871 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004872
4873 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4874 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004875};
4876
Tim Northover573cbee2014-05-24 12:52:07 +00004877class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004878public:
Tim Northover573cbee2014-05-24 12:52:07 +00004879 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4880 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004881
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004882 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Saleem Abdulrasool40db4772017-02-11 23:03:13 +00004883 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004884 }
4885
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004886 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4887 return 31;
4888 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004889
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004890 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004891};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004892
4893class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4894public:
4895 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4896 : AArch64TargetCodeGenInfo(CGT, K) {}
4897
4898 void getDependentLibraryOption(llvm::StringRef Lib,
4899 llvm::SmallString<24> &Opt) const override {
4900 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4901 }
4902
4903 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4904 llvm::SmallString<32> &Opt) const override {
4905 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4906 }
4907};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004908}
Tim Northovera2ee4332014-03-29 15:09:45 +00004909
Tim Northoverb047bfa2014-11-27 21:02:49 +00004910ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004911 Ty = useFirstFieldIfTransparentUnion(Ty);
4912
Tim Northovera2ee4332014-03-29 15:09:45 +00004913 // Handle illegal vector types here.
4914 if (isIllegalVectorType(Ty)) {
4915 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004916 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004917 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004918 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4919 return ABIArgInfo::getDirect(ResType);
4920 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004921 if (Size <= 32) {
4922 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004923 return ABIArgInfo::getDirect(ResType);
4924 }
4925 if (Size == 64) {
4926 llvm::Type *ResType =
4927 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004928 return ABIArgInfo::getDirect(ResType);
4929 }
4930 if (Size == 128) {
4931 llvm::Type *ResType =
4932 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004933 return ABIArgInfo::getDirect(ResType);
4934 }
John McCall7f416cc2015-09-08 08:05:57 +00004935 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004936 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004937
4938 if (!isAggregateTypeForABI(Ty)) {
4939 // Treat an enum type as its underlying type.
4940 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4941 Ty = EnumTy->getDecl()->getIntegerType();
4942
Tim Northovera2ee4332014-03-29 15:09:45 +00004943 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4944 ? ABIArgInfo::getExtend()
4945 : ABIArgInfo::getDirect());
4946 }
4947
4948 // Structures with either a non-trivial destructor or a non-trivial
4949 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004950 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004951 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4952 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004953 }
4954
4955 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4956 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004957 uint64_t Size = getContext().getTypeSize(Ty);
4958 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4959 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004960 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4961 return ABIArgInfo::getIgnore();
4962
Tim Northover23bcad22017-05-05 22:36:06 +00004963 // GNU C mode. The only argument that gets ignored is an empty one with size
4964 // 0.
4965 if (IsEmpty && Size == 0)
4966 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004967 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4968 }
4969
4970 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004971 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004972 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004973 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004974 return ABIArgInfo::getDirect(
4975 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004976 }
4977
4978 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00004979 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004980 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4981 // same size and alignment.
4982 if (getTarget().isRenderScriptTarget()) {
4983 return coerceToIntArray(Ty, getContext(), getVMContext());
4984 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004985 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00004986 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004987
Tim Northovera2ee4332014-03-29 15:09:45 +00004988 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4989 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004990 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004991 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4992 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4993 }
4994 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4995 }
4996
John McCall7f416cc2015-09-08 08:05:57 +00004997 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004998}
4999
Tim Northover573cbee2014-05-24 12:52:07 +00005000ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005001 if (RetTy->isVoidType())
5002 return ABIArgInfo::getIgnore();
5003
5004 // Large vector types should be returned via memory.
5005 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005006 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005007
5008 if (!isAggregateTypeForABI(RetTy)) {
5009 // Treat an enum type as its underlying type.
5010 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5011 RetTy = EnumTy->getDecl()->getIntegerType();
5012
Tim Northover4dab6982014-04-18 13:46:08 +00005013 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5014 ? ABIArgInfo::getExtend()
5015 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005016 }
5017
Tim Northover23bcad22017-05-05 22:36:06 +00005018 uint64_t Size = getContext().getTypeSize(RetTy);
5019 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005020 return ABIArgInfo::getIgnore();
5021
Craig Topper8a13c412014-05-21 05:09:00 +00005022 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005023 uint64_t Members = 0;
5024 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005025 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5026 return ABIArgInfo::getDirect();
5027
5028 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005030 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5031 // same size and alignment.
5032 if (getTarget().isRenderScriptTarget()) {
5033 return coerceToIntArray(RetTy, getContext(), getVMContext());
5034 }
Pete Cooper635b5092015-04-17 22:16:24 +00005035 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005036 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005037
5038 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5039 // For aggregates with 16-byte alignment, we use i128.
5040 if (Alignment < 128 && Size == 128) {
5041 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5042 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5043 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005044 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5045 }
5046
John McCall7f416cc2015-09-08 08:05:57 +00005047 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005048}
5049
Tim Northover573cbee2014-05-24 12:52:07 +00005050/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5051bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005052 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5053 // Check whether VT is legal.
5054 unsigned NumElements = VT->getNumElements();
5055 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005056 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005057 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005058 return true;
5059 return Size != 64 && (Size != 128 || NumElements == 1);
5060 }
5061 return false;
5062}
5063
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005064bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5065 llvm::Type *eltTy,
5066 unsigned elts) const {
5067 if (!llvm::isPowerOf2_32(elts))
5068 return false;
5069 if (totalSize.getQuantity() != 8 &&
5070 (totalSize.getQuantity() != 16 || elts == 1))
5071 return false;
5072 return true;
5073}
5074
Reid Klecknere9f6a712014-10-31 17:10:41 +00005075bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5076 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5077 // point type or a short-vector type. This is the same as the 32-bit ABI,
5078 // but with the difference that any floating-point type is allowed,
5079 // including __fp16.
5080 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5081 if (BT->isFloatingPoint())
5082 return true;
5083 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5084 unsigned VecSize = getContext().getTypeSize(VT);
5085 if (VecSize == 64 || VecSize == 128)
5086 return true;
5087 }
5088 return false;
5089}
5090
5091bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5092 uint64_t Members) const {
5093 return Members <= 4;
5094}
5095
John McCall7f416cc2015-09-08 08:05:57 +00005096Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005097 QualType Ty,
5098 CodeGenFunction &CGF) const {
5099 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005100 bool IsIndirect = AI.isIndirect();
5101
Tim Northoverb047bfa2014-11-27 21:02:49 +00005102 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5103 if (IsIndirect)
5104 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5105 else if (AI.getCoerceToType())
5106 BaseTy = AI.getCoerceToType();
5107
5108 unsigned NumRegs = 1;
5109 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5110 BaseTy = ArrTy->getElementType();
5111 NumRegs = ArrTy->getNumElements();
5112 }
5113 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5114
Tim Northovera2ee4332014-03-29 15:09:45 +00005115 // The AArch64 va_list type and handling is specified in the Procedure Call
5116 // Standard, section B.4:
5117 //
5118 // struct {
5119 // void *__stack;
5120 // void *__gr_top;
5121 // void *__vr_top;
5122 // int __gr_offs;
5123 // int __vr_offs;
5124 // };
5125
5126 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5127 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5128 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5129 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005130
John McCall7f416cc2015-09-08 08:05:57 +00005131 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5132 CharUnits TyAlign = TyInfo.second;
5133
5134 Address reg_offs_p = Address::invalid();
5135 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005136 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005137 CharUnits reg_top_offset;
5138 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005139 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005140 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005141 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005142 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5143 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005144 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5145 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005146 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005147 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005148 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005149 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005150 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005151 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5152 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005153 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5154 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005155 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005156 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005157 }
5158
5159 //=======================================
5160 // Find out where argument was passed
5161 //=======================================
5162
5163 // If reg_offs >= 0 we're already using the stack for this type of
5164 // argument. We don't want to keep updating reg_offs (in case it overflows,
5165 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5166 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005167 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005168 UsingStack = CGF.Builder.CreateICmpSGE(
5169 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5170
5171 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5172
5173 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005174 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005175 CGF.EmitBlock(MaybeRegBlock);
5176
5177 // Integer arguments may need to correct register alignment (for example a
5178 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5179 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005180 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5181 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005182
5183 reg_offs = CGF.Builder.CreateAdd(
5184 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5185 "align_regoffs");
5186 reg_offs = CGF.Builder.CreateAnd(
5187 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5188 "aligned_regoffs");
5189 }
5190
5191 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005192 // The fact that this is done unconditionally reflects the fact that
5193 // allocating an argument to the stack also uses up all the remaining
5194 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005195 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005196 NewOffset = CGF.Builder.CreateAdd(
5197 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5198 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5199
5200 // Now we're in a position to decide whether this argument really was in
5201 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005202 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005203 InRegs = CGF.Builder.CreateICmpSLE(
5204 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5205
5206 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5207
5208 //=======================================
5209 // Argument was in registers
5210 //=======================================
5211
5212 // Now we emit the code for if the argument was originally passed in
5213 // registers. First start the appropriate block:
5214 CGF.EmitBlock(InRegBlock);
5215
John McCall7f416cc2015-09-08 08:05:57 +00005216 llvm::Value *reg_top = nullptr;
5217 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5218 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005219 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005220 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5221 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5222 Address RegAddr = Address::invalid();
5223 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005224
5225 if (IsIndirect) {
5226 // If it's been passed indirectly (actually a struct), whatever we find from
5227 // stored registers or on the stack will actually be a struct **.
5228 MemTy = llvm::PointerType::getUnqual(MemTy);
5229 }
5230
Craig Topper8a13c412014-05-21 05:09:00 +00005231 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005232 uint64_t NumMembers = 0;
5233 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005234 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005235 // Homogeneous aggregates passed in registers will have their elements split
5236 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5237 // qN+1, ...). We reload and store into a temporary local variable
5238 // contiguously.
5239 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005240 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005241 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5242 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005243 Address Tmp = CGF.CreateTempAlloca(HFATy,
5244 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005245
John McCall7f416cc2015-09-08 08:05:57 +00005246 // On big-endian platforms, the value will be right-aligned in its slot.
5247 int Offset = 0;
5248 if (CGF.CGM.getDataLayout().isBigEndian() &&
5249 BaseTyInfo.first.getQuantity() < 16)
5250 Offset = 16 - BaseTyInfo.first.getQuantity();
5251
Tim Northovera2ee4332014-03-29 15:09:45 +00005252 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005253 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5254 Address LoadAddr =
5255 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5256 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5257
5258 Address StoreAddr =
5259 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005260
5261 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5262 CGF.Builder.CreateStore(Elem, StoreAddr);
5263 }
5264
John McCall7f416cc2015-09-08 08:05:57 +00005265 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005266 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005267 // Otherwise the object is contiguous in memory.
5268
5269 // It might be right-aligned in its slot.
5270 CharUnits SlotSize = BaseAddr.getAlignment();
5271 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005272 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005273 TyInfo.first < SlotSize) {
5274 CharUnits Offset = SlotSize - TyInfo.first;
5275 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005276 }
5277
John McCall7f416cc2015-09-08 08:05:57 +00005278 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005279 }
5280
5281 CGF.EmitBranch(ContBlock);
5282
5283 //=======================================
5284 // Argument was on the stack
5285 //=======================================
5286 CGF.EmitBlock(OnStackBlock);
5287
John McCall7f416cc2015-09-08 08:05:57 +00005288 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5289 CharUnits::Zero(), "stack_p");
5290 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005291
John McCall7f416cc2015-09-08 08:05:57 +00005292 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005293 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005294 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5295 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005296
John McCall7f416cc2015-09-08 08:05:57 +00005297 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005298
John McCall7f416cc2015-09-08 08:05:57 +00005299 OnStackPtr = CGF.Builder.CreateAdd(
5300 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005301 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005302 OnStackPtr = CGF.Builder.CreateAnd(
5303 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005304 "align_stack");
5305
John McCall7f416cc2015-09-08 08:05:57 +00005306 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005307 }
John McCall7f416cc2015-09-08 08:05:57 +00005308 Address OnStackAddr(OnStackPtr,
5309 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005310
John McCall7f416cc2015-09-08 08:05:57 +00005311 // All stack slots are multiples of 8 bytes.
5312 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5313 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005314 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005315 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005316 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005317 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005318
John McCall7f416cc2015-09-08 08:05:57 +00005319 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005320 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005321 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005322
5323 // Write the new value of __stack for the next call to va_arg
5324 CGF.Builder.CreateStore(NewStack, stack_p);
5325
5326 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005327 TyInfo.first < StackSlotSize) {
5328 CharUnits Offset = StackSlotSize - TyInfo.first;
5329 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005330 }
5331
John McCall7f416cc2015-09-08 08:05:57 +00005332 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005333
5334 CGF.EmitBranch(ContBlock);
5335
5336 //=======================================
5337 // Tidy up
5338 //=======================================
5339 CGF.EmitBlock(ContBlock);
5340
John McCall7f416cc2015-09-08 08:05:57 +00005341 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5342 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005343
5344 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005345 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5346 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005347
5348 return ResAddr;
5349}
5350
John McCall7f416cc2015-09-08 08:05:57 +00005351Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5352 CodeGenFunction &CGF) const {
5353 // The backend's lowering doesn't support va_arg for aggregates or
5354 // illegal vector types. Lower VAArg here for these cases and use
5355 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005356 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005357 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005358
John McCall7f416cc2015-09-08 08:05:57 +00005359 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005360
John McCall7f416cc2015-09-08 08:05:57 +00005361 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005362 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005363 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5364 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5365 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005366 }
5367
John McCall7f416cc2015-09-08 08:05:57 +00005368 // The size of the actual thing passed, which might end up just
5369 // being a pointer for indirect types.
5370 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5371
5372 // Arguments bigger than 16 bytes which aren't homogeneous
5373 // aggregates should be passed indirectly.
5374 bool IsIndirect = false;
5375 if (TyInfo.first.getQuantity() > 16) {
5376 const Type *Base = nullptr;
5377 uint64_t Members = 0;
5378 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005379 }
5380
John McCall7f416cc2015-09-08 08:05:57 +00005381 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5382 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005383}
5384
Martin Storsjo502de222017-07-13 17:59:14 +00005385Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5386 QualType Ty) const {
5387 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5388 CGF.getContext().getTypeInfoInChars(Ty),
5389 CharUnits::fromQuantity(8),
5390 /*allowHigherAlign*/ false);
5391}
5392
Tim Northovera2ee4332014-03-29 15:09:45 +00005393//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005394// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005395//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005396
5397namespace {
5398
John McCall12f23522016-04-04 18:33:08 +00005399class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005400public:
5401 enum ABIKind {
5402 APCS = 0,
5403 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005404 AAPCS_VFP = 2,
5405 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005406 };
5407
5408private:
5409 ABIKind Kind;
5410
5411public:
John McCall12f23522016-04-04 18:33:08 +00005412 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5413 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005414 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005415 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005416
John McCall3480ef22011-08-30 01:42:09 +00005417 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005418 switch (getTarget().getTriple().getEnvironment()) {
5419 case llvm::Triple::Android:
5420 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005421 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005422 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005423 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005424 case llvm::Triple::MuslEABI:
5425 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005426 return true;
5427 default:
5428 return false;
5429 }
John McCall3480ef22011-08-30 01:42:09 +00005430 }
5431
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005432 bool isEABIHF() const {
5433 switch (getTarget().getTriple().getEnvironment()) {
5434 case llvm::Triple::EABIHF:
5435 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005436 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005437 return true;
5438 default:
5439 return false;
5440 }
5441 }
5442
Daniel Dunbar020daa92009-09-12 01:00:39 +00005443 ABIKind getABIKind() const { return Kind; }
5444
Tim Northovera484bc02013-10-01 14:34:25 +00005445private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005446 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005447 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005448 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005449
Reid Klecknere9f6a712014-10-31 17:10:41 +00005450 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5451 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5452 uint64_t Members) const override;
5453
Craig Topper4f12f102014-03-12 06:41:41 +00005454 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005455
John McCall7f416cc2015-09-08 08:05:57 +00005456 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5457 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005458
5459 llvm::CallingConv::ID getLLVMDefaultCC() const;
5460 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005461 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005462
5463 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5464 ArrayRef<llvm::Type*> scalars,
5465 bool asReturnValue) const override {
5466 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5467 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005468 bool isSwiftErrorInRegister() const override {
5469 return true;
5470 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005471 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5472 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005473};
5474
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005475class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5476public:
Chris Lattner2b037972010-07-29 02:01:43 +00005477 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5478 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005479
John McCall3480ef22011-08-30 01:42:09 +00005480 const ARMABIInfo &getABIInfo() const {
5481 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5482 }
5483
Craig Topper4f12f102014-03-12 06:41:41 +00005484 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005485 return 13;
5486 }
Roman Divackyc1617352011-05-18 19:36:54 +00005487
Craig Topper4f12f102014-03-12 06:41:41 +00005488 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005489 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5490 }
5491
Roman Divackyc1617352011-05-18 19:36:54 +00005492 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005493 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005494 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005495
5496 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005497 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005498 return false;
5499 }
John McCall3480ef22011-08-30 01:42:09 +00005500
Craig Topper4f12f102014-03-12 06:41:41 +00005501 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005502 if (getABIInfo().isEABI()) return 88;
5503 return TargetCodeGenInfo::getSizeOfUnwindException();
5504 }
Tim Northovera484bc02013-10-01 14:34:25 +00005505
Eric Christopher162c91c2015-06-05 22:03:00 +00005506 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005507 CodeGen::CodeGenModule &CGM,
5508 ForDefinition_t IsForDefinition) const override {
5509 if (!IsForDefinition)
5510 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005511 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005512 if (!FD)
5513 return;
5514
5515 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5516 if (!Attr)
5517 return;
5518
5519 const char *Kind;
5520 switch (Attr->getInterrupt()) {
5521 case ARMInterruptAttr::Generic: Kind = ""; break;
5522 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5523 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5524 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5525 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5526 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5527 }
5528
5529 llvm::Function *Fn = cast<llvm::Function>(GV);
5530
5531 Fn->addFnAttr("interrupt", Kind);
5532
Tim Northover5627d392015-10-30 16:30:45 +00005533 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5534 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005535 return;
5536
5537 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5538 // however this is not necessarily true on taking any interrupt. Instruct
5539 // the backend to perform a realignment as part of the function prologue.
5540 llvm::AttrBuilder B;
5541 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005542 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005543 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005544};
5545
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005546class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005547public:
5548 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5549 : ARMTargetCodeGenInfo(CGT, K) {}
5550
Eric Christopher162c91c2015-06-05 22:03:00 +00005551 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005552 CodeGen::CodeGenModule &CGM,
5553 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005554
5555 void getDependentLibraryOption(llvm::StringRef Lib,
5556 llvm::SmallString<24> &Opt) const override {
5557 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5558 }
5559
5560 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5561 llvm::SmallString<32> &Opt) const override {
5562 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5563 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005564};
5565
Eric Christopher162c91c2015-06-05 22:03:00 +00005566void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005567 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5568 ForDefinition_t IsForDefinition) const {
5569 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5570 if (!IsForDefinition)
5571 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005572 addStackProbeSizeTargetAttribute(D, GV, CGM);
5573}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005574}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005575
Chris Lattner22326a12010-07-29 02:31:05 +00005576void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005577 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005578 FI.getReturnInfo() =
5579 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005580
Tim Northoverbc784d12015-02-24 17:22:40 +00005581 for (auto &I : FI.arguments())
5582 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005583
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005584 // Always honor user-specified calling convention.
5585 if (FI.getCallingConvention() != llvm::CallingConv::C)
5586 return;
5587
John McCall882987f2013-02-28 19:01:20 +00005588 llvm::CallingConv::ID cc = getRuntimeCC();
5589 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005590 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005591}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005592
John McCall882987f2013-02-28 19:01:20 +00005593/// Return the default calling convention that LLVM will use.
5594llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5595 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005596 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005597 return llvm::CallingConv::ARM_AAPCS_VFP;
5598 else if (isEABI())
5599 return llvm::CallingConv::ARM_AAPCS;
5600 else
5601 return llvm::CallingConv::ARM_APCS;
5602}
5603
5604/// Return the calling convention that our ABI would like us to use
5605/// as the C calling convention.
5606llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005607 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005608 case APCS: return llvm::CallingConv::ARM_APCS;
5609 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5610 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005611 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005612 }
John McCall882987f2013-02-28 19:01:20 +00005613 llvm_unreachable("bad ABI kind");
5614}
5615
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005616void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005617 assert(getRuntimeCC() == llvm::CallingConv::C);
5618
5619 // Don't muddy up the IR with a ton of explicit annotations if
5620 // they'd just match what LLVM will infer from the triple.
5621 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5622 if (abiCC != getLLVMDefaultCC())
5623 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005624
Tim Northover5627d392015-10-30 16:30:45 +00005625 // AAPCS apparently requires runtime support functions to be soft-float, but
5626 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5627 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005628
5629 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5630 // AEABI-complying FP helper functions to use the base AAPCS.
5631 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5632 // support functions emitted by clang such as the _Complex helpers follow the
5633 // abiCC.
5634 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005635 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005636}
5637
Tim Northoverbc784d12015-02-24 17:22:40 +00005638ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5639 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005640 // 6.1.2.1 The following argument types are VFP CPRCs:
5641 // A single-precision floating-point type (including promoted
5642 // half-precision types); A double-precision floating-point type;
5643 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5644 // with a Base Type of a single- or double-precision floating-point type,
5645 // 64-bit containerized vectors or 128-bit containerized vectors with one
5646 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005647 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005648
Reid Klecknerb1be6832014-11-15 01:41:41 +00005649 Ty = useFirstFieldIfTransparentUnion(Ty);
5650
Manman Renfef9e312012-10-16 19:18:39 +00005651 // Handle illegal vector types here.
5652 if (isIllegalVectorType(Ty)) {
5653 uint64_t Size = getContext().getTypeSize(Ty);
5654 if (Size <= 32) {
5655 llvm::Type *ResType =
5656 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005657 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005658 }
5659 if (Size == 64) {
5660 llvm::Type *ResType = llvm::VectorType::get(
5661 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005662 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005663 }
5664 if (Size == 128) {
5665 llvm::Type *ResType = llvm::VectorType::get(
5666 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005667 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005668 }
John McCall7f416cc2015-09-08 08:05:57 +00005669 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005670 }
5671
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005672 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5673 // unspecified. This is not done for OpenCL as it handles the half type
5674 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005675 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005676 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5677 llvm::Type::getFloatTy(getVMContext()) :
5678 llvm::Type::getInt32Ty(getVMContext());
5679 return ABIArgInfo::getDirect(ResType);
5680 }
5681
John McCalla1dee5302010-08-22 10:59:02 +00005682 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005683 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005684 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005685 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005686 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005687
Tim Northover5a1558e2014-11-07 22:30:50 +00005688 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5689 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005690 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005691
Oliver Stannard405bded2014-02-11 09:25:50 +00005692 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005693 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005694 }
Tim Northover1060eae2013-06-21 22:49:34 +00005695
Daniel Dunbar09d33622009-09-14 21:54:03 +00005696 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005697 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005698 return ABIArgInfo::getIgnore();
5699
Tim Northover5a1558e2014-11-07 22:30:50 +00005700 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005701 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5702 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005703 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005704 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005705 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005706 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005707 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005708 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005709 }
Tim Northover5627d392015-10-30 16:30:45 +00005710 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5711 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5712 // this convention even for a variadic function: the backend will use GPRs
5713 // if needed.
5714 const Type *Base = nullptr;
5715 uint64_t Members = 0;
5716 if (isHomogeneousAggregate(Ty, Base, Members)) {
5717 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5718 llvm::Type *Ty =
5719 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5720 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5721 }
5722 }
5723
5724 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5725 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5726 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5727 // bigger than 128-bits, they get placed in space allocated by the caller,
5728 // and a pointer is passed.
5729 return ABIArgInfo::getIndirect(
5730 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005731 }
5732
Manman Ren6c30e132012-08-13 21:23:55 +00005733 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005734 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5735 // most 8-byte. We realign the indirect argument if type alignment is bigger
5736 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005737 uint64_t ABIAlign = 4;
5738 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5739 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005740 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005741 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005742
Manman Ren8cd99812012-11-06 04:58:01 +00005743 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005744 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005745 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5746 /*ByVal=*/true,
5747 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005748 }
5749
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005750 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5751 // same size and alignment.
5752 if (getTarget().isRenderScriptTarget()) {
5753 return coerceToIntArray(Ty, getContext(), getVMContext());
5754 }
5755
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005756 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005757 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005758 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005759 // FIXME: Try to match the types of the arguments more accurately where
5760 // we can.
5761 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005762 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5763 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005764 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005765 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5766 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005767 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005768
Tim Northover5a1558e2014-11-07 22:30:50 +00005769 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005770}
5771
Chris Lattner458b2aa2010-07-29 02:16:43 +00005772static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005773 llvm::LLVMContext &VMContext) {
5774 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5775 // is called integer-like if its size is less than or equal to one word, and
5776 // the offset of each of its addressable sub-fields is zero.
5777
5778 uint64_t Size = Context.getTypeSize(Ty);
5779
5780 // Check that the type fits in a word.
5781 if (Size > 32)
5782 return false;
5783
5784 // FIXME: Handle vector types!
5785 if (Ty->isVectorType())
5786 return false;
5787
Daniel Dunbard53bac72009-09-14 02:20:34 +00005788 // Float types are never treated as "integer like".
5789 if (Ty->isRealFloatingType())
5790 return false;
5791
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005792 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005793 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005794 return true;
5795
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005796 // Small complex integer types are "integer like".
5797 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5798 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005799
5800 // Single element and zero sized arrays should be allowed, by the definition
5801 // above, but they are not.
5802
5803 // Otherwise, it must be a record type.
5804 const RecordType *RT = Ty->getAs<RecordType>();
5805 if (!RT) return false;
5806
5807 // Ignore records with flexible arrays.
5808 const RecordDecl *RD = RT->getDecl();
5809 if (RD->hasFlexibleArrayMember())
5810 return false;
5811
5812 // Check that all sub-fields are at offset 0, and are themselves "integer
5813 // like".
5814 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5815
5816 bool HadField = false;
5817 unsigned idx = 0;
5818 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5819 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005820 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005821
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005822 // Bit-fields are not addressable, we only need to verify they are "integer
5823 // like". We still have to disallow a subsequent non-bitfield, for example:
5824 // struct { int : 0; int x }
5825 // is non-integer like according to gcc.
5826 if (FD->isBitField()) {
5827 if (!RD->isUnion())
5828 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005829
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005830 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5831 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005832
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005833 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005834 }
5835
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005836 // Check if this field is at offset 0.
5837 if (Layout.getFieldOffset(idx) != 0)
5838 return false;
5839
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005840 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5841 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005842
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005843 // Only allow at most one field in a structure. This doesn't match the
5844 // wording above, but follows gcc in situations with a field following an
5845 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005846 if (!RD->isUnion()) {
5847 if (HadField)
5848 return false;
5849
5850 HadField = true;
5851 }
5852 }
5853
5854 return true;
5855}
5856
Oliver Stannard405bded2014-02-11 09:25:50 +00005857ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5858 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005859 bool IsEffectivelyAAPCS_VFP =
5860 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005861
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005862 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005863 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005864
Daniel Dunbar19964db2010-09-23 01:54:32 +00005865 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005866 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005867 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005868 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005869
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005870 // __fp16 gets returned as if it were an int or float, but with the top 16
5871 // bits unspecified. This is not done for OpenCL as it handles the half type
5872 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005873 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005874 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5875 llvm::Type::getFloatTy(getVMContext()) :
5876 llvm::Type::getInt32Ty(getVMContext());
5877 return ABIArgInfo::getDirect(ResType);
5878 }
5879
John McCalla1dee5302010-08-22 10:59:02 +00005880 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005881 // Treat an enum type as its underlying type.
5882 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5883 RetTy = EnumTy->getDecl()->getIntegerType();
5884
Tim Northover5a1558e2014-11-07 22:30:50 +00005885 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5886 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005887 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005888
5889 // Are we following APCS?
5890 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005891 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005892 return ABIArgInfo::getIgnore();
5893
Daniel Dunbareedf1512010-02-01 23:31:19 +00005894 // Complex types are all returned as packed integers.
5895 //
5896 // FIXME: Consider using 2 x vector types if the back end handles them
5897 // correctly.
5898 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005899 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5900 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005901
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005902 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005903 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005904 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005905 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005906 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005907 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005908 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005909 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5910 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005911 }
5912
5913 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005914 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005915 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005916
5917 // Otherwise this is an AAPCS variant.
5918
Chris Lattner458b2aa2010-07-29 02:16:43 +00005919 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005920 return ABIArgInfo::getIgnore();
5921
Bob Wilson1d9269a2011-11-02 04:51:36 +00005922 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005923 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005924 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005925 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005926 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005927 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005928 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005929 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005930 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005931 }
5932
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005933 // Aggregates <= 4 bytes are returned in r0; other aggregates
5934 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005935 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005936 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005937 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5938 // same size and alignment.
5939 if (getTarget().isRenderScriptTarget()) {
5940 return coerceToIntArray(RetTy, getContext(), getVMContext());
5941 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005942 if (getDataLayout().isBigEndian())
5943 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005944 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005945
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005946 // Return in the smallest viable integer type.
5947 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005948 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005949 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005950 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5951 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005952 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5953 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5954 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005955 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005956 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005957 }
5958
John McCall7f416cc2015-09-08 08:05:57 +00005959 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005960}
5961
Manman Renfef9e312012-10-16 19:18:39 +00005962/// isIllegalVector - check whether Ty is an illegal vector type.
5963bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005964 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5965 if (isAndroid()) {
5966 // Android shipped using Clang 3.1, which supported a slightly different
5967 // vector ABI. The primary differences were that 3-element vector types
5968 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5969 // accepts that legacy behavior for Android only.
5970 // Check whether VT is legal.
5971 unsigned NumElements = VT->getNumElements();
5972 // NumElements should be power of 2 or equal to 3.
5973 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5974 return true;
5975 } else {
5976 // Check whether VT is legal.
5977 unsigned NumElements = VT->getNumElements();
5978 uint64_t Size = getContext().getTypeSize(VT);
5979 // NumElements should be power of 2.
5980 if (!llvm::isPowerOf2_32(NumElements))
5981 return true;
5982 // Size should be greater than 32 bits.
5983 return Size <= 32;
5984 }
Manman Renfef9e312012-10-16 19:18:39 +00005985 }
5986 return false;
5987}
5988
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005989bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
5990 llvm::Type *eltTy,
5991 unsigned numElts) const {
5992 if (!llvm::isPowerOf2_32(numElts))
5993 return false;
5994 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
5995 if (size > 64)
5996 return false;
5997 if (vectorSize.getQuantity() != 8 &&
5998 (vectorSize.getQuantity() != 16 || numElts == 1))
5999 return false;
6000 return true;
6001}
6002
Reid Klecknere9f6a712014-10-31 17:10:41 +00006003bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6004 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6005 // double, or 64-bit or 128-bit vectors.
6006 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6007 if (BT->getKind() == BuiltinType::Float ||
6008 BT->getKind() == BuiltinType::Double ||
6009 BT->getKind() == BuiltinType::LongDouble)
6010 return true;
6011 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6012 unsigned VecSize = getContext().getTypeSize(VT);
6013 if (VecSize == 64 || VecSize == 128)
6014 return true;
6015 }
6016 return false;
6017}
6018
6019bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6020 uint64_t Members) const {
6021 return Members <= 4;
6022}
6023
John McCall7f416cc2015-09-08 08:05:57 +00006024Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6025 QualType Ty) const {
6026 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006027
John McCall7f416cc2015-09-08 08:05:57 +00006028 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006029 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006030 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6031 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6032 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006033 }
6034
John McCall7f416cc2015-09-08 08:05:57 +00006035 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6036 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006037
John McCall7f416cc2015-09-08 08:05:57 +00006038 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6039 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006040 const Type *Base = nullptr;
6041 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006042 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6043 IsIndirect = true;
6044
Tim Northover5627d392015-10-30 16:30:45 +00006045 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6046 // allocated by the caller.
6047 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6048 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6049 !isHomogeneousAggregate(Ty, Base, Members)) {
6050 IsIndirect = true;
6051
John McCall7f416cc2015-09-08 08:05:57 +00006052 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006053 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6054 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006055 // Our callers should be prepared to handle an under-aligned address.
6056 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6057 getABIKind() == ARMABIInfo::AAPCS) {
6058 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6059 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006060 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6061 // ARMv7k allows type alignment up to 16 bytes.
6062 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6063 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006064 } else {
6065 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006066 }
John McCall7f416cc2015-09-08 08:05:57 +00006067 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006068
John McCall7f416cc2015-09-08 08:05:57 +00006069 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6070 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006071}
6072
Chris Lattner0cf24192010-06-28 20:05:43 +00006073//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006074// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006075//===----------------------------------------------------------------------===//
6076
6077namespace {
6078
Justin Holewinski83e96682012-05-24 17:43:12 +00006079class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006080public:
Justin Holewinski36837432013-03-30 14:38:24 +00006081 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006082
6083 ABIArgInfo classifyReturnType(QualType RetTy) const;
6084 ABIArgInfo classifyArgumentType(QualType Ty) const;
6085
Craig Topper4f12f102014-03-12 06:41:41 +00006086 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006087 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6088 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006089};
6090
Justin Holewinski83e96682012-05-24 17:43:12 +00006091class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006092public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006093 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6094 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006095
Eric Christopher162c91c2015-06-05 22:03:00 +00006096 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006097 CodeGen::CodeGenModule &M,
6098 ForDefinition_t IsForDefinition) const override;
6099
Justin Holewinski36837432013-03-30 14:38:24 +00006100private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006101 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6102 // resulting MDNode to the nvvm.annotations MDNode.
6103 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006104};
6105
Justin Holewinski83e96682012-05-24 17:43:12 +00006106ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006107 if (RetTy->isVoidType())
6108 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006109
6110 // note: this is different from default ABI
6111 if (!RetTy->isScalarType())
6112 return ABIArgInfo::getDirect();
6113
6114 // Treat an enum type as its underlying type.
6115 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6116 RetTy = EnumTy->getDecl()->getIntegerType();
6117
6118 return (RetTy->isPromotableIntegerType() ?
6119 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006120}
6121
Justin Holewinski83e96682012-05-24 17:43:12 +00006122ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006123 // Treat an enum type as its underlying type.
6124 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6125 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006126
Eli Bendersky95338a02014-10-29 13:43:21 +00006127 // Return aggregates type as indirect by value
6128 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006129 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006130
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006131 return (Ty->isPromotableIntegerType() ?
6132 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006133}
6134
Justin Holewinski83e96682012-05-24 17:43:12 +00006135void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006136 if (!getCXXABI().classifyReturnType(FI))
6137 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006138 for (auto &I : FI.arguments())
6139 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006140
6141 // Always honor user-specified calling convention.
6142 if (FI.getCallingConvention() != llvm::CallingConv::C)
6143 return;
6144
John McCall882987f2013-02-28 19:01:20 +00006145 FI.setEffectiveCallingConvention(getRuntimeCC());
6146}
6147
John McCall7f416cc2015-09-08 08:05:57 +00006148Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6149 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006150 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006151}
6152
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006153void NVPTXTargetCodeGenInfo::setTargetAttributes(
6154 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6155 ForDefinition_t IsForDefinition) const {
6156 if (!IsForDefinition)
6157 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006158 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006159 if (!FD) return;
6160
6161 llvm::Function *F = cast<llvm::Function>(GV);
6162
6163 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006164 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006165 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006166 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006167 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006168 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006169 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6170 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006171 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006172 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006173 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006174 }
Justin Holewinski38031972011-10-05 17:58:44 +00006175
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006176 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006177 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006178 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006179 // __global__ functions cannot be called from the device, we do not
6180 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006181 if (FD->hasAttr<CUDAGlobalAttr>()) {
6182 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6183 addNVVMMetadata(F, "kernel", 1);
6184 }
Artem Belevich7093e402015-04-21 22:55:54 +00006185 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006186 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006187 llvm::APSInt MaxThreads(32);
6188 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6189 if (MaxThreads > 0)
6190 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6191
6192 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6193 // not specified in __launch_bounds__ or if the user specified a 0 value,
6194 // we don't have to add a PTX directive.
6195 if (Attr->getMinBlocks()) {
6196 llvm::APSInt MinBlocks(32);
6197 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6198 if (MinBlocks > 0)
6199 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6200 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006201 }
6202 }
Justin Holewinski38031972011-10-05 17:58:44 +00006203 }
6204}
6205
Eli Benderskye06a2c42014-04-15 16:57:05 +00006206void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6207 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006208 llvm::Module *M = F->getParent();
6209 llvm::LLVMContext &Ctx = M->getContext();
6210
6211 // Get "nvvm.annotations" metadata node
6212 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6213
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006214 llvm::Metadata *MDVals[] = {
6215 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6216 llvm::ConstantAsMetadata::get(
6217 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006218 // Append metadata to nvvm.annotations
6219 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6220}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006221}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006222
6223//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006224// SystemZ ABI Implementation
6225//===----------------------------------------------------------------------===//
6226
6227namespace {
6228
Bryan Chane3f1ed52016-04-28 13:56:43 +00006229class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006230 bool HasVector;
6231
Ulrich Weigand47445072013-05-06 16:26:41 +00006232public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006233 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006234 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006235
6236 bool isPromotableIntegerType(QualType Ty) const;
6237 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006238 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006239 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006240 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006241
6242 ABIArgInfo classifyReturnType(QualType RetTy) const;
6243 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6244
Craig Topper4f12f102014-03-12 06:41:41 +00006245 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006246 if (!getCXXABI().classifyReturnType(FI))
6247 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006248 for (auto &I : FI.arguments())
6249 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006250 }
6251
John McCall7f416cc2015-09-08 08:05:57 +00006252 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6253 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006254
6255 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6256 ArrayRef<llvm::Type*> scalars,
6257 bool asReturnValue) const override {
6258 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6259 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006260 bool isSwiftErrorInRegister() const override {
6261 return true;
6262 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006263};
6264
6265class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6266public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006267 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6268 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006269};
6270
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006271}
Ulrich Weigand47445072013-05-06 16:26:41 +00006272
6273bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6274 // Treat an enum type as its underlying type.
6275 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6276 Ty = EnumTy->getDecl()->getIntegerType();
6277
6278 // Promotable integer types are required to be promoted by the ABI.
6279 if (Ty->isPromotableIntegerType())
6280 return true;
6281
6282 // 32-bit values must also be promoted.
6283 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6284 switch (BT->getKind()) {
6285 case BuiltinType::Int:
6286 case BuiltinType::UInt:
6287 return true;
6288 default:
6289 return false;
6290 }
6291 return false;
6292}
6293
6294bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006295 return (Ty->isAnyComplexType() ||
6296 Ty->isVectorType() ||
6297 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006298}
6299
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006300bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6301 return (HasVector &&
6302 Ty->isVectorType() &&
6303 getContext().getTypeSize(Ty) <= 128);
6304}
6305
Ulrich Weigand47445072013-05-06 16:26:41 +00006306bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6307 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6308 switch (BT->getKind()) {
6309 case BuiltinType::Float:
6310 case BuiltinType::Double:
6311 return true;
6312 default:
6313 return false;
6314 }
6315
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006316 return false;
6317}
6318
6319QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006320 if (const RecordType *RT = Ty->getAsStructureType()) {
6321 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006322 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006323
6324 // If this is a C++ record, check the bases first.
6325 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006326 for (const auto &I : CXXRD->bases()) {
6327 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006328
6329 // Empty bases don't affect things either way.
6330 if (isEmptyRecord(getContext(), Base, true))
6331 continue;
6332
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006333 if (!Found.isNull())
6334 return Ty;
6335 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006336 }
6337
6338 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006339 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006340 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006341 // Unlike isSingleElementStruct(), empty structure and array fields
6342 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006343 if (getContext().getLangOpts().CPlusPlus &&
6344 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6345 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006346
6347 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006348 // Nested structures still do though.
6349 if (!Found.isNull())
6350 return Ty;
6351 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006352 }
6353
6354 // Unlike isSingleElementStruct(), trailing padding is allowed.
6355 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006356 if (!Found.isNull())
6357 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006358 }
6359
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006360 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006361}
6362
John McCall7f416cc2015-09-08 08:05:57 +00006363Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6364 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006365 // Assume that va_list type is correct; should be pointer to LLVM type:
6366 // struct {
6367 // i64 __gpr;
6368 // i64 __fpr;
6369 // i8 *__overflow_arg_area;
6370 // i8 *__reg_save_area;
6371 // };
6372
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006373 // Every non-vector argument occupies 8 bytes and is passed by preference
6374 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6375 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006376 Ty = getContext().getCanonicalType(Ty);
6377 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006378 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006379 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006380 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006381 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006382 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006383 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006384 CharUnits UnpaddedSize;
6385 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006386 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006387 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6388 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006389 } else {
6390 if (AI.getCoerceToType())
6391 ArgTy = AI.getCoerceToType();
6392 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006393 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006394 UnpaddedSize = TyInfo.first;
6395 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006396 }
John McCall7f416cc2015-09-08 08:05:57 +00006397 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6398 if (IsVector && UnpaddedSize > PaddedSize)
6399 PaddedSize = CharUnits::fromQuantity(16);
6400 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006401
John McCall7f416cc2015-09-08 08:05:57 +00006402 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006403
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006404 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006405 llvm::Value *PaddedSizeV =
6406 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006407
6408 if (IsVector) {
6409 // Work out the address of a vector argument on the stack.
6410 // Vector arguments are always passed in the high bits of a
6411 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006412 Address OverflowArgAreaPtr =
6413 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006414 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006415 Address OverflowArgArea =
6416 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6417 TyInfo.second);
6418 Address MemAddr =
6419 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006420
6421 // Update overflow_arg_area_ptr pointer
6422 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006423 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6424 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006425 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6426
6427 return MemAddr;
6428 }
6429
John McCall7f416cc2015-09-08 08:05:57 +00006430 assert(PaddedSize.getQuantity() == 8);
6431
6432 unsigned MaxRegs, RegCountField, RegSaveIndex;
6433 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006434 if (InFPRs) {
6435 MaxRegs = 4; // Maximum of 4 FPR arguments
6436 RegCountField = 1; // __fpr
6437 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006438 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006439 } else {
6440 MaxRegs = 5; // Maximum of 5 GPR arguments
6441 RegCountField = 0; // __gpr
6442 RegSaveIndex = 2; // save offset for r2
6443 RegPadding = Padding; // values are passed in the low bits of a GPR
6444 }
6445
John McCall7f416cc2015-09-08 08:05:57 +00006446 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6447 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6448 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006449 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006450 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6451 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006452 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006453
6454 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6455 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6456 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6457 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6458
6459 // Emit code to load the value if it was passed in registers.
6460 CGF.EmitBlock(InRegBlock);
6461
6462 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006463 llvm::Value *ScaledRegCount =
6464 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6465 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006466 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6467 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006468 llvm::Value *RegOffset =
6469 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006470 Address RegSaveAreaPtr =
6471 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6472 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006473 llvm::Value *RegSaveArea =
6474 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006475 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6476 "raw_reg_addr"),
6477 PaddedSize);
6478 Address RegAddr =
6479 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006480
6481 // Update the register count
6482 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6483 llvm::Value *NewRegCount =
6484 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6485 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6486 CGF.EmitBranch(ContBlock);
6487
6488 // Emit code to load the value if it was passed in memory.
6489 CGF.EmitBlock(InMemBlock);
6490
6491 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006492 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6493 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6494 Address OverflowArgArea =
6495 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6496 PaddedSize);
6497 Address RawMemAddr =
6498 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6499 Address MemAddr =
6500 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006501
6502 // Update overflow_arg_area_ptr pointer
6503 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006504 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6505 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006506 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6507 CGF.EmitBranch(ContBlock);
6508
6509 // Return the appropriate result.
6510 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006511 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6512 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006513
6514 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006515 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6516 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006517
6518 return ResAddr;
6519}
6520
Ulrich Weigand47445072013-05-06 16:26:41 +00006521ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6522 if (RetTy->isVoidType())
6523 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006524 if (isVectorArgumentType(RetTy))
6525 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006526 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006527 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006528 return (isPromotableIntegerType(RetTy) ?
6529 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6530}
6531
6532ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6533 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006534 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006535 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006536
6537 // Integers and enums are extended to full register width.
6538 if (isPromotableIntegerType(Ty))
6539 return ABIArgInfo::getExtend();
6540
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006541 // Handle vector types and vector-like structure types. Note that
6542 // as opposed to float-like structure types, we do not allow any
6543 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006544 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006545 QualType SingleElementTy = GetSingleElementType(Ty);
6546 if (isVectorArgumentType(SingleElementTy) &&
6547 getContext().getTypeSize(SingleElementTy) == Size)
6548 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6549
6550 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006551 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006552 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006553
6554 // Handle small structures.
6555 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6556 // Structures with flexible arrays have variable length, so really
6557 // fail the size test above.
6558 const RecordDecl *RD = RT->getDecl();
6559 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006560 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006561
6562 // The structure is passed as an unextended integer, a float, or a double.
6563 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006564 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006565 assert(Size == 32 || Size == 64);
6566 if (Size == 32)
6567 PassTy = llvm::Type::getFloatTy(getVMContext());
6568 else
6569 PassTy = llvm::Type::getDoubleTy(getVMContext());
6570 } else
6571 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6572 return ABIArgInfo::getDirect(PassTy);
6573 }
6574
6575 // Non-structure compounds are passed indirectly.
6576 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006577 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006578
Craig Topper8a13c412014-05-21 05:09:00 +00006579 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006580}
6581
6582//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006583// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006584//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006585
6586namespace {
6587
6588class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6589public:
Chris Lattner2b037972010-07-29 02:01:43 +00006590 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6591 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006592 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006593 CodeGen::CodeGenModule &M,
6594 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006595};
6596
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006597}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006598
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006599void MSP430TargetCodeGenInfo::setTargetAttributes(
6600 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6601 ForDefinition_t IsForDefinition) const {
6602 if (!IsForDefinition)
6603 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006604 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006605 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6606 // Handle 'interrupt' attribute:
6607 llvm::Function *F = cast<llvm::Function>(GV);
6608
6609 // Step 1: Set ISR calling convention.
6610 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6611
6612 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006613 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006614
6615 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006616 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006617 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6618 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006619 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006620 }
6621}
6622
Chris Lattner0cf24192010-06-28 20:05:43 +00006623//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006624// MIPS ABI Implementation. This works for both little-endian and
6625// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006626//===----------------------------------------------------------------------===//
6627
John McCall943fae92010-05-27 06:19:26 +00006628namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006629class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006630 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006631 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6632 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006633 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006634 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006635 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006636 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006637public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006638 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006639 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006640 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006641
6642 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006643 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006644 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006645 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6646 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006647 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006648};
6649
John McCall943fae92010-05-27 06:19:26 +00006650class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006651 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006652public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006653 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6654 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006655 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006656
Craig Topper4f12f102014-03-12 06:41:41 +00006657 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006658 return 29;
6659 }
6660
Eric Christopher162c91c2015-06-05 22:03:00 +00006661 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006662 CodeGen::CodeGenModule &CGM,
6663 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006664 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006665 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006666 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006667
6668 if (FD->hasAttr<MipsLongCallAttr>())
6669 Fn->addFnAttr("long-call");
6670 else if (FD->hasAttr<MipsShortCallAttr>())
6671 Fn->addFnAttr("short-call");
6672
6673 // Other attributes do not have a meaning for declarations.
6674 if (!IsForDefinition)
6675 return;
6676
Reed Kotler3d5966f2013-03-13 20:40:30 +00006677 if (FD->hasAttr<Mips16Attr>()) {
6678 Fn->addFnAttr("mips16");
6679 }
6680 else if (FD->hasAttr<NoMips16Attr>()) {
6681 Fn->addFnAttr("nomips16");
6682 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006683
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006684 if (FD->hasAttr<MicroMipsAttr>())
6685 Fn->addFnAttr("micromips");
6686 else if (FD->hasAttr<NoMicroMipsAttr>())
6687 Fn->addFnAttr("nomicromips");
6688
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006689 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6690 if (!Attr)
6691 return;
6692
6693 const char *Kind;
6694 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006695 case MipsInterruptAttr::eic: Kind = "eic"; break;
6696 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6697 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6698 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6699 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6700 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6701 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6702 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6703 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6704 }
6705
6706 Fn->addFnAttr("interrupt", Kind);
6707
Reed Kotler373feca2013-01-16 17:10:28 +00006708 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006709
John McCall943fae92010-05-27 06:19:26 +00006710 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006711 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006712
Craig Topper4f12f102014-03-12 06:41:41 +00006713 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006714 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006715 }
John McCall943fae92010-05-27 06:19:26 +00006716};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006717}
John McCall943fae92010-05-27 06:19:26 +00006718
Eric Christopher7565e0d2015-05-29 23:09:49 +00006719void MipsABIInfo::CoerceToIntArgs(
6720 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006721 llvm::IntegerType *IntTy =
6722 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006723
6724 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6725 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6726 ArgList.push_back(IntTy);
6727
6728 // If necessary, add one more integer type to ArgList.
6729 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6730
6731 if (R)
6732 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006733}
6734
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006735// In N32/64, an aligned double precision floating point field is passed in
6736// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006737llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006738 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6739
6740 if (IsO32) {
6741 CoerceToIntArgs(TySize, ArgList);
6742 return llvm::StructType::get(getVMContext(), ArgList);
6743 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006744
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006745 if (Ty->isComplexType())
6746 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006747
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006748 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006749
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006750 // Unions/vectors are passed in integer registers.
6751 if (!RT || !RT->isStructureOrClassType()) {
6752 CoerceToIntArgs(TySize, ArgList);
6753 return llvm::StructType::get(getVMContext(), ArgList);
6754 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006755
6756 const RecordDecl *RD = RT->getDecl();
6757 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006758 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006759
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006760 uint64_t LastOffset = 0;
6761 unsigned idx = 0;
6762 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6763
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006764 // Iterate over fields in the struct/class and check if there are any aligned
6765 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006766 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6767 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006768 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006769 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6770
6771 if (!BT || BT->getKind() != BuiltinType::Double)
6772 continue;
6773
6774 uint64_t Offset = Layout.getFieldOffset(idx);
6775 if (Offset % 64) // Ignore doubles that are not aligned.
6776 continue;
6777
6778 // Add ((Offset - LastOffset) / 64) args of type i64.
6779 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6780 ArgList.push_back(I64);
6781
6782 // Add double type.
6783 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6784 LastOffset = Offset + 64;
6785 }
6786
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006787 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6788 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006789
6790 return llvm::StructType::get(getVMContext(), ArgList);
6791}
6792
Akira Hatanakaddd66342013-10-29 18:41:15 +00006793llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6794 uint64_t Offset) const {
6795 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006796 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006797
Akira Hatanakaddd66342013-10-29 18:41:15 +00006798 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006799}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006800
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006801ABIArgInfo
6802MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006803 Ty = useFirstFieldIfTransparentUnion(Ty);
6804
Akira Hatanaka1632af62012-01-09 19:31:25 +00006805 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006806 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006807 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006808
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006809 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6810 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006811 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6812 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006813
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006814 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006815 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006816 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006817 return ABIArgInfo::getIgnore();
6818
Mark Lacey3825e832013-10-06 01:33:34 +00006819 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006820 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006821 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006822 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006823
Petar Jovanovic6f4cdb82017-05-10 14:28:18 +00006824 // Use indirect if the aggregate cannot fit into registers for
6825 // passing arguments according to the ABI
6826 unsigned Threshold = IsO32 ? 16 : 64;
6827
6828 if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6829 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6830 getContext().getTypeAlign(Ty) / 8 > Align);
6831
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006832 // If we have reached here, aggregates are passed directly by coercing to
6833 // another structure type. Padding is inserted if the offset of the
6834 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006835 ABIArgInfo ArgInfo =
6836 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6837 getPaddingType(OrigOffset, CurrOffset));
6838 ArgInfo.setInReg(true);
6839 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006840 }
6841
6842 // Treat an enum type as its underlying type.
6843 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6844 Ty = EnumTy->getDecl()->getIntegerType();
6845
Daniel Sanders5b445b32014-10-24 14:42:42 +00006846 // All integral types are promoted to the GPR width.
6847 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006848 return ABIArgInfo::getExtend();
6849
Akira Hatanakaddd66342013-10-29 18:41:15 +00006850 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006851 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006852}
6853
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006854llvm::Type*
6855MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006856 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006857 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006858
Akira Hatanakab6f74432012-02-09 18:49:26 +00006859 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006860 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006861 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6862 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006863
Akira Hatanakab6f74432012-02-09 18:49:26 +00006864 // N32/64 returns struct/classes in floating point registers if the
6865 // following conditions are met:
6866 // 1. The size of the struct/class is no larger than 128-bit.
6867 // 2. The struct/class has one or two fields all of which are floating
6868 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006869 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006870 //
6871 // Any other composite results are returned in integer registers.
6872 //
6873 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6874 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6875 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006876 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006877
Akira Hatanakab6f74432012-02-09 18:49:26 +00006878 if (!BT || !BT->isFloatingPoint())
6879 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006880
David Blaikie2d7c57e2012-04-30 02:36:29 +00006881 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006882 }
6883
6884 if (b == e)
6885 return llvm::StructType::get(getVMContext(), RTList,
6886 RD->hasAttr<PackedAttr>());
6887
6888 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006889 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006890 }
6891
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006892 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006893 return llvm::StructType::get(getVMContext(), RTList);
6894}
6895
Akira Hatanakab579fe52011-06-02 00:09:17 +00006896ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006897 uint64_t Size = getContext().getTypeSize(RetTy);
6898
Daniel Sandersed39f582014-09-04 13:28:14 +00006899 if (RetTy->isVoidType())
6900 return ABIArgInfo::getIgnore();
6901
6902 // O32 doesn't treat zero-sized structs differently from other structs.
6903 // However, N32/N64 ignores zero sized return values.
6904 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006905 return ABIArgInfo::getIgnore();
6906
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006907 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006908 if (Size <= 128) {
6909 if (RetTy->isAnyComplexType())
6910 return ABIArgInfo::getDirect();
6911
Daniel Sanderse5018b62014-09-04 15:05:39 +00006912 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006913 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006914 if (!IsO32 ||
6915 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6916 ABIArgInfo ArgInfo =
6917 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6918 ArgInfo.setInReg(true);
6919 return ArgInfo;
6920 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006921 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006922
John McCall7f416cc2015-09-08 08:05:57 +00006923 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006924 }
6925
6926 // Treat an enum type as its underlying type.
6927 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6928 RetTy = EnumTy->getDecl()->getIntegerType();
6929
6930 return (RetTy->isPromotableIntegerType() ?
6931 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6932}
6933
6934void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006935 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006936 if (!getCXXABI().classifyReturnType(FI))
6937 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006938
Eric Christopher7565e0d2015-05-29 23:09:49 +00006939 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006940 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006941
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006942 for (auto &I : FI.arguments())
6943 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006944}
6945
John McCall7f416cc2015-09-08 08:05:57 +00006946Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6947 QualType OrigTy) const {
6948 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006949
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006950 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6951 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006952 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006953 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006954 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006955 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006956 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006957 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006958 DidPromote = true;
6959 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6960 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006961 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006962
John McCall7f416cc2015-09-08 08:05:57 +00006963 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006964
John McCall7f416cc2015-09-08 08:05:57 +00006965 // The alignment of things in the argument area is never larger than
6966 // StackAlignInBytes.
6967 TyInfo.second =
6968 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6969
6970 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6971 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6972
6973 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6974 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6975
6976
6977 // If there was a promotion, "unpromote" into a temporary.
6978 // TODO: can we just use a pointer into a subset of the original slot?
6979 if (DidPromote) {
6980 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6981 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6982
6983 // Truncate down to the right width.
6984 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6985 : CGF.IntPtrTy);
6986 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6987 if (OrigTy->isPointerType())
6988 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6989
6990 CGF.Builder.CreateStore(V, Temp);
6991 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006992 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006993
John McCall7f416cc2015-09-08 08:05:57 +00006994 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006995}
6996
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006997bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6998 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006999
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007000 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7001 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7002 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007003
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007004 return false;
7005}
7006
John McCall943fae92010-05-27 06:19:26 +00007007bool
7008MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7009 llvm::Value *Address) const {
7010 // This information comes from gcc's implementation, which seems to
7011 // as canonical as it gets.
7012
John McCall943fae92010-05-27 06:19:26 +00007013 // Everything on MIPS is 4 bytes. Double-precision FP registers
7014 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007015 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007016
7017 // 0-31 are the general purpose registers, $0 - $31.
7018 // 32-63 are the floating-point registers, $f0 - $f31.
7019 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7020 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007021 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007022
7023 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7024 // They are one bit wide and ignored here.
7025
7026 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7027 // (coprocessor 1 is the FP unit)
7028 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7029 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7030 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007031 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007032 return false;
7033}
7034
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007035//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007036// AVR ABI Implementation.
7037//===----------------------------------------------------------------------===//
7038
7039namespace {
7040class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7041public:
7042 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7043 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7044
7045 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007046 CodeGen::CodeGenModule &CGM,
7047 ForDefinition_t IsForDefinition) const override {
7048 if (!IsForDefinition)
7049 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007050 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7051 if (!FD) return;
7052 auto *Fn = cast<llvm::Function>(GV);
7053
7054 if (FD->getAttr<AVRInterruptAttr>())
7055 Fn->addFnAttr("interrupt");
7056
7057 if (FD->getAttr<AVRSignalAttr>())
7058 Fn->addFnAttr("signal");
7059 }
7060};
7061}
7062
7063//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007064// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007065// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007066// handling.
7067//===----------------------------------------------------------------------===//
7068
7069namespace {
7070
7071class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7072public:
7073 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7074 : DefaultTargetCodeGenInfo(CGT) {}
7075
Eric Christopher162c91c2015-06-05 22:03:00 +00007076 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007077 CodeGen::CodeGenModule &M,
7078 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007079};
7080
Eric Christopher162c91c2015-06-05 22:03:00 +00007081void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007082 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7083 ForDefinition_t IsForDefinition) const {
7084 if (!IsForDefinition)
7085 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007086 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007087 if (!FD) return;
7088
7089 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007090
David Blaikiebbafb8a2012-03-11 07:00:24 +00007091 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007092 if (FD->hasAttr<OpenCLKernelAttr>()) {
7093 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007094 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007095 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7096 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007097 // Convert the reqd_work_group_size() attributes to metadata.
7098 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007099 llvm::NamedMDNode *OpenCLMetadata =
7100 M.getModule().getOrInsertNamedMetadata(
7101 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007102
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007103 SmallVector<llvm::Metadata *, 5> Operands;
7104 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007105
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007106 Operands.push_back(
7107 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7108 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7109 Operands.push_back(
7110 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7111 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7112 Operands.push_back(
7113 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7114 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007115
Eric Christopher7565e0d2015-05-29 23:09:49 +00007116 // Add a boolean constant operand for "required" (true) or "hint"
7117 // (false) for implementing the work_group_size_hint attr later.
7118 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007119 Operands.push_back(
7120 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007121 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7122 }
7123 }
7124 }
7125}
7126
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007127}
John McCall943fae92010-05-27 06:19:26 +00007128
Tony Linthicum76329bf2011-12-12 21:14:55 +00007129//===----------------------------------------------------------------------===//
7130// Hexagon ABI Implementation
7131//===----------------------------------------------------------------------===//
7132
7133namespace {
7134
7135class HexagonABIInfo : public ABIInfo {
7136
7137
7138public:
7139 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7140
7141private:
7142
7143 ABIArgInfo classifyReturnType(QualType RetTy) const;
7144 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7145
Craig Topper4f12f102014-03-12 06:41:41 +00007146 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007147
John McCall7f416cc2015-09-08 08:05:57 +00007148 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7149 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007150};
7151
7152class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7153public:
7154 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7155 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7156
Craig Topper4f12f102014-03-12 06:41:41 +00007157 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007158 return 29;
7159 }
7160};
7161
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007162}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007163
7164void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007165 if (!getCXXABI().classifyReturnType(FI))
7166 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007167 for (auto &I : FI.arguments())
7168 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007169}
7170
7171ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7172 if (!isAggregateTypeForABI(Ty)) {
7173 // Treat an enum type as its underlying type.
7174 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7175 Ty = EnumTy->getDecl()->getIntegerType();
7176
7177 return (Ty->isPromotableIntegerType() ?
7178 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7179 }
7180
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007181 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7182 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7183
Tony Linthicum76329bf2011-12-12 21:14:55 +00007184 // Ignore empty records.
7185 if (isEmptyRecord(getContext(), Ty, true))
7186 return ABIArgInfo::getIgnore();
7187
Tony Linthicum76329bf2011-12-12 21:14:55 +00007188 uint64_t Size = getContext().getTypeSize(Ty);
7189 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007190 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007191 // Pass in the smallest viable integer type.
7192 else if (Size > 32)
7193 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7194 else if (Size > 16)
7195 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7196 else if (Size > 8)
7197 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7198 else
7199 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7200}
7201
7202ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7203 if (RetTy->isVoidType())
7204 return ABIArgInfo::getIgnore();
7205
7206 // Large vector types should be returned via memory.
7207 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007208 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007209
7210 if (!isAggregateTypeForABI(RetTy)) {
7211 // Treat an enum type as its underlying type.
7212 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7213 RetTy = EnumTy->getDecl()->getIntegerType();
7214
7215 return (RetTy->isPromotableIntegerType() ?
7216 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7217 }
7218
Tony Linthicum76329bf2011-12-12 21:14:55 +00007219 if (isEmptyRecord(getContext(), RetTy, true))
7220 return ABIArgInfo::getIgnore();
7221
7222 // Aggregates <= 8 bytes are returned in r0; other aggregates
7223 // are returned indirectly.
7224 uint64_t Size = getContext().getTypeSize(RetTy);
7225 if (Size <= 64) {
7226 // Return in the smallest viable integer type.
7227 if (Size <= 8)
7228 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7229 if (Size <= 16)
7230 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7231 if (Size <= 32)
7232 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7233 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7234 }
7235
John McCall7f416cc2015-09-08 08:05:57 +00007236 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007237}
7238
John McCall7f416cc2015-09-08 08:05:57 +00007239Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7240 QualType Ty) const {
7241 // FIXME: Someone needs to audit that this handle alignment correctly.
7242 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7243 getContext().getTypeInfoInChars(Ty),
7244 CharUnits::fromQuantity(4),
7245 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007246}
7247
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007248//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007249// Lanai ABI Implementation
7250//===----------------------------------------------------------------------===//
7251
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007252namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007253class LanaiABIInfo : public DefaultABIInfo {
7254public:
7255 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7256
7257 bool shouldUseInReg(QualType Ty, CCState &State) const;
7258
7259 void computeInfo(CGFunctionInfo &FI) const override {
7260 CCState State(FI.getCallingConvention());
7261 // Lanai uses 4 registers to pass arguments unless the function has the
7262 // regparm attribute set.
7263 if (FI.getHasRegParm()) {
7264 State.FreeRegs = FI.getRegParm();
7265 } else {
7266 State.FreeRegs = 4;
7267 }
7268
7269 if (!getCXXABI().classifyReturnType(FI))
7270 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7271 for (auto &I : FI.arguments())
7272 I.info = classifyArgumentType(I.type, State);
7273 }
7274
Jacques Pienaare74d9132016-04-26 00:09:29 +00007275 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007276 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7277};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007278} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007279
7280bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7281 unsigned Size = getContext().getTypeSize(Ty);
7282 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7283
7284 if (SizeInRegs == 0)
7285 return false;
7286
7287 if (SizeInRegs > State.FreeRegs) {
7288 State.FreeRegs = 0;
7289 return false;
7290 }
7291
7292 State.FreeRegs -= SizeInRegs;
7293
7294 return true;
7295}
7296
Jacques Pienaare74d9132016-04-26 00:09:29 +00007297ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7298 CCState &State) const {
7299 if (!ByVal) {
7300 if (State.FreeRegs) {
7301 --State.FreeRegs; // Non-byval indirects just use one pointer.
7302 return getNaturalAlignIndirectInReg(Ty);
7303 }
7304 return getNaturalAlignIndirect(Ty, false);
7305 }
7306
7307 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007308 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007309 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7310 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7311 /*Realign=*/TypeAlign >
7312 MinABIStackAlignInBytes);
7313}
7314
Jacques Pienaard964cc22016-03-28 21:02:54 +00007315ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7316 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007317 // Check with the C++ ABI first.
7318 const RecordType *RT = Ty->getAs<RecordType>();
7319 if (RT) {
7320 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7321 if (RAA == CGCXXABI::RAA_Indirect) {
7322 return getIndirectResult(Ty, /*ByVal=*/false, State);
7323 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7324 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7325 }
7326 }
7327
7328 if (isAggregateTypeForABI(Ty)) {
7329 // Structures with flexible arrays are always indirect.
7330 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7331 return getIndirectResult(Ty, /*ByVal=*/true, State);
7332
7333 // Ignore empty structs/unions.
7334 if (isEmptyRecord(getContext(), Ty, true))
7335 return ABIArgInfo::getIgnore();
7336
7337 llvm::LLVMContext &LLVMContext = getVMContext();
7338 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7339 if (SizeInRegs <= State.FreeRegs) {
7340 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7341 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7342 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7343 State.FreeRegs -= SizeInRegs;
7344 return ABIArgInfo::getDirectInReg(Result);
7345 } else {
7346 State.FreeRegs = 0;
7347 }
7348 return getIndirectResult(Ty, true, State);
7349 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007350
7351 // Treat an enum type as its underlying type.
7352 if (const auto *EnumTy = Ty->getAs<EnumType>())
7353 Ty = EnumTy->getDecl()->getIntegerType();
7354
Jacques Pienaare74d9132016-04-26 00:09:29 +00007355 bool InReg = shouldUseInReg(Ty, State);
7356 if (Ty->isPromotableIntegerType()) {
7357 if (InReg)
7358 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007359 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007360 }
7361 if (InReg)
7362 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007363 return ABIArgInfo::getDirect();
7364}
7365
7366namespace {
7367class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7368public:
7369 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7370 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7371};
7372}
7373
7374//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007375// AMDGPU ABI Implementation
7376//===----------------------------------------------------------------------===//
7377
7378namespace {
7379
Matt Arsenault88d7da02016-08-22 19:25:59 +00007380class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007381private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007382 static const unsigned MaxNumRegsForArgsRet = 16;
7383
7384 bool shouldReturnTypeInRegister(QualType Ty,
7385 ASTContext &Context) const;
7386 unsigned numRegsForType(QualType Ty) const;
7387
7388 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7389 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7390 uint64_t Members) const override;
7391
7392public:
7393 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7394 DefaultABIInfo(CGT) {}
7395
7396 ABIArgInfo classifyReturnType(QualType RetTy) const;
7397 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7398 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007399
7400 void computeInfo(CGFunctionInfo &FI) const override;
7401};
7402
Matt Arsenault3fe73952017-08-09 21:44:58 +00007403bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7404 return true;
7405}
7406
7407bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7408 const Type *Base, uint64_t Members) const {
7409 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7410
7411 // Homogeneous Aggregates may occupy at most 16 registers.
7412 return Members * NumRegs <= MaxNumRegsForArgsRet;
7413}
7414
7415/// Check whether the type is small enough to consider passing directly in
7416/// registers.
7417bool AMDGPUABIInfo::shouldReturnTypeInRegister(QualType Ty,
7418 ASTContext &Ctx) const {
7419 return ((Ctx.getTypeSize(Ty) + 31) / 32) <= MaxNumRegsForArgsRet;
7420}
7421
7422/// Estimate number of registers the type will use when passed in registers.
7423unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7424 unsigned NumRegs = 0;
7425
7426 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7427 // Compute from the number of elements. The reported size is based on the
7428 // in-memory size, which includes the padding 4th element for 3-vectors.
7429 QualType EltTy = VT->getElementType();
7430 unsigned EltSize = getContext().getTypeSize(EltTy);
7431
7432 // 16-bit element vectors should be passed as packed.
7433 if (EltSize == 16)
7434 return (VT->getNumElements() + 1) / 2;
7435
7436 unsigned EltNumRegs = (EltSize + 31) / 32;
7437 return EltNumRegs * VT->getNumElements();
7438 }
7439
7440 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7441 const RecordDecl *RD = RT->getDecl();
7442 assert(!RD->hasFlexibleArrayMember());
7443
7444 for (const FieldDecl *Field : RD->fields()) {
7445 QualType FieldTy = Field->getType();
7446 NumRegs += numRegsForType(FieldTy);
7447 }
7448
7449 return NumRegs;
7450 }
7451
7452 return (getContext().getTypeSize(Ty) + 31) / 32;
7453}
7454
Matt Arsenault88d7da02016-08-22 19:25:59 +00007455void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007456 llvm::CallingConv::ID CC = FI.getCallingConvention();
7457
Matt Arsenault88d7da02016-08-22 19:25:59 +00007458 if (!getCXXABI().classifyReturnType(FI))
7459 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7460
Matt Arsenault3fe73952017-08-09 21:44:58 +00007461 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7462 for (auto &Arg : FI.arguments()) {
7463 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7464 Arg.info = classifyKernelArgumentType(Arg.type);
7465 } else {
7466 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7467 }
7468 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007469}
7470
Matt Arsenault3fe73952017-08-09 21:44:58 +00007471ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7472 if (isAggregateTypeForABI(RetTy)) {
7473 // Records with non-trivial destructors/copy-constructors should not be
7474 // returned by value.
7475 if (!getRecordArgABI(RetTy, getCXXABI())) {
7476 // Ignore empty structs/unions.
7477 if (isEmptyRecord(getContext(), RetTy, true))
7478 return ABIArgInfo::getIgnore();
7479
7480 // Lower single-element structs to just return a regular value.
7481 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7482 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7483
7484 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7485 const RecordDecl *RD = RT->getDecl();
7486 if (RD->hasFlexibleArrayMember())
7487 return DefaultABIInfo::classifyReturnType(RetTy);
7488 }
7489
7490 // Pack aggregates <= 4 bytes into single VGPR or pair.
7491 uint64_t Size = getContext().getTypeSize(RetTy);
7492 if (Size <= 16)
7493 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7494
7495 if (Size <= 32)
7496 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7497
7498 if (Size <= 64) {
7499 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7500 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7501 }
7502
7503 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7504 return ABIArgInfo::getDirect();
7505 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007506 }
7507
Matt Arsenault3fe73952017-08-09 21:44:58 +00007508 // Otherwise just do the default thing.
7509 return DefaultABIInfo::classifyReturnType(RetTy);
7510}
7511
7512/// For kernels all parameters are really passed in a special buffer. It doesn't
7513/// make sense to pass anything byval, so everything must be direct.
7514ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7515 Ty = useFirstFieldIfTransparentUnion(Ty);
7516
7517 // TODO: Can we omit empty structs?
7518
Matt Arsenault88d7da02016-08-22 19:25:59 +00007519 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007520 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7521 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007522
7523 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7524 // individual elements, which confuses the Clover OpenCL backend; therefore we
7525 // have to set it to false here. Other args of getDirect() are just defaults.
7526 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7527}
7528
Matt Arsenault3fe73952017-08-09 21:44:58 +00007529ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7530 unsigned &NumRegsLeft) const {
7531 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7532
7533 Ty = useFirstFieldIfTransparentUnion(Ty);
7534
7535 if (isAggregateTypeForABI(Ty)) {
7536 // Records with non-trivial destructors/copy-constructors should not be
7537 // passed by value.
7538 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7539 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7540
7541 // Ignore empty structs/unions.
7542 if (isEmptyRecord(getContext(), Ty, true))
7543 return ABIArgInfo::getIgnore();
7544
7545 // Lower single-element structs to just pass a regular value. TODO: We
7546 // could do reasonable-size multiple-element structs too, using getExpand(),
7547 // though watch out for things like bitfields.
7548 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7549 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7550
7551 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7552 const RecordDecl *RD = RT->getDecl();
7553 if (RD->hasFlexibleArrayMember())
7554 return DefaultABIInfo::classifyArgumentType(Ty);
7555 }
7556
7557 // Pack aggregates <= 8 bytes into single VGPR or pair.
7558 uint64_t Size = getContext().getTypeSize(Ty);
7559 if (Size <= 64) {
7560 unsigned NumRegs = (Size + 31) / 32;
7561 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7562
7563 if (Size <= 16)
7564 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7565
7566 if (Size <= 32)
7567 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7568
7569 // XXX: Should this be i64 instead, and should the limit increase?
7570 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7571 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7572 }
7573
7574 if (NumRegsLeft > 0) {
7575 unsigned NumRegs = numRegsForType(Ty);
7576 if (NumRegsLeft >= NumRegs) {
7577 NumRegsLeft -= NumRegs;
7578 return ABIArgInfo::getDirect();
7579 }
7580 }
7581 }
7582
7583 // Otherwise just do the default thing.
7584 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7585 if (!ArgInfo.isIndirect()) {
7586 unsigned NumRegs = numRegsForType(Ty);
7587 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7588 }
7589
7590 return ArgInfo;
7591}
7592
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007593class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7594public:
7595 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007596 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007597 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007598 CodeGen::CodeGenModule &M,
7599 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007600 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007601
Yaxun Liu402804b2016-12-15 08:09:08 +00007602 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7603 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007604
7605 unsigned getASTAllocaAddressSpace() const override {
7606 return LangAS::FirstTargetAddressSpace +
7607 getABIInfo().getDataLayout().getAllocaAddrSpace();
7608 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007609 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7610 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007611 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7612 llvm::LLVMContext &C) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007613};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007614}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007615
Eric Christopher162c91c2015-06-05 22:03:00 +00007616void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007617 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7618 ForDefinition_t IsForDefinition) const {
7619 if (!IsForDefinition)
7620 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007621 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007622 if (!FD)
7623 return;
7624
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007625 llvm::Function *F = cast<llvm::Function>(GV);
7626
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007627 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7628 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7629 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7630 if (ReqdWGS || FlatWGS) {
7631 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7632 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7633 if (ReqdWGS && Min == 0 && Max == 0)
7634 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007635
7636 if (Min != 0) {
7637 assert(Min <= Max && "Min must be less than or equal Max");
7638
7639 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7640 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7641 } else
7642 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007643 }
7644
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007645 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7646 unsigned Min = Attr->getMin();
7647 unsigned Max = Attr->getMax();
7648
7649 if (Min != 0) {
7650 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7651
7652 std::string AttrVal = llvm::utostr(Min);
7653 if (Max != 0)
7654 AttrVal = AttrVal + "," + llvm::utostr(Max);
7655 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7656 } else
7657 assert(Max == 0 && "Max must be zero");
7658 }
7659
7660 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007661 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007662
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007663 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007664 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7665 }
7666
7667 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7668 uint32_t NumVGPR = Attr->getNumVGPR();
7669
7670 if (NumVGPR != 0)
7671 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007672 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007673}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007674
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007675unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7676 return llvm::CallingConv::AMDGPU_KERNEL;
7677}
7678
Yaxun Liu402804b2016-12-15 08:09:08 +00007679// Currently LLVM assumes null pointers always have value 0,
7680// which results in incorrectly transformed IR. Therefore, instead of
7681// emitting null pointers in private and local address spaces, a null
7682// pointer in generic address space is emitted which is casted to a
7683// pointer in local or private address space.
7684llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7685 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7686 QualType QT) const {
7687 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7688 return llvm::ConstantPointerNull::get(PT);
7689
7690 auto &Ctx = CGM.getContext();
7691 auto NPT = llvm::PointerType::get(PT->getElementType(),
7692 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7693 return llvm::ConstantExpr::getAddrSpaceCast(
7694 llvm::ConstantPointerNull::get(NPT), PT);
7695}
7696
Yaxun Liucbf647c2017-07-08 13:24:52 +00007697unsigned
7698AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7699 const VarDecl *D) const {
7700 assert(!CGM.getLangOpts().OpenCL &&
7701 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7702 "Address space agnostic languages only");
7703 unsigned DefaultGlobalAS =
7704 LangAS::FirstTargetAddressSpace +
7705 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7706 if (!D)
7707 return DefaultGlobalAS;
7708
7709 unsigned AddrSpace = D->getType().getAddressSpace();
7710 assert(AddrSpace == LangAS::Default ||
7711 AddrSpace >= LangAS::FirstTargetAddressSpace);
7712 if (AddrSpace != LangAS::Default)
7713 return AddrSpace;
7714
7715 if (CGM.isTypeConstant(D->getType(), false)) {
7716 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7717 return ConstAS.getValue();
7718 }
7719 return DefaultGlobalAS;
7720}
7721
Yaxun Liu39195062017-08-04 18:16:31 +00007722llvm::SyncScope::ID
7723AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7724 llvm::LLVMContext &C) const {
7725 StringRef Name;
7726 switch (S) {
7727 case SyncScope::OpenCLWorkGroup:
7728 Name = "workgroup";
7729 break;
7730 case SyncScope::OpenCLDevice:
7731 Name = "agent";
7732 break;
7733 case SyncScope::OpenCLAllSVMDevices:
7734 Name = "";
7735 break;
7736 case SyncScope::OpenCLSubGroup:
7737 Name = "subgroup";
7738 }
7739 return C.getOrInsertSyncScopeID(Name);
7740}
7741
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007742//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007743// SPARC v8 ABI Implementation.
7744// Based on the SPARC Compliance Definition version 2.4.1.
7745//
7746// Ensures that complex values are passed in registers.
7747//
7748namespace {
7749class SparcV8ABIInfo : public DefaultABIInfo {
7750public:
7751 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7752
7753private:
7754 ABIArgInfo classifyReturnType(QualType RetTy) const;
7755 void computeInfo(CGFunctionInfo &FI) const override;
7756};
7757} // end anonymous namespace
7758
7759
7760ABIArgInfo
7761SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7762 if (Ty->isAnyComplexType()) {
7763 return ABIArgInfo::getDirect();
7764 }
7765 else {
7766 return DefaultABIInfo::classifyReturnType(Ty);
7767 }
7768}
7769
7770void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7771
7772 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7773 for (auto &Arg : FI.arguments())
7774 Arg.info = classifyArgumentType(Arg.type);
7775}
7776
7777namespace {
7778class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7779public:
7780 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7781 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7782};
7783} // end anonymous namespace
7784
7785//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007786// SPARC v9 ABI Implementation.
7787// Based on the SPARC Compliance Definition version 2.4.1.
7788//
7789// Function arguments a mapped to a nominal "parameter array" and promoted to
7790// registers depending on their type. Each argument occupies 8 or 16 bytes in
7791// the array, structs larger than 16 bytes are passed indirectly.
7792//
7793// One case requires special care:
7794//
7795// struct mixed {
7796// int i;
7797// float f;
7798// };
7799//
7800// When a struct mixed is passed by value, it only occupies 8 bytes in the
7801// parameter array, but the int is passed in an integer register, and the float
7802// is passed in a floating point register. This is represented as two arguments
7803// with the LLVM IR inreg attribute:
7804//
7805// declare void f(i32 inreg %i, float inreg %f)
7806//
7807// The code generator will only allocate 4 bytes from the parameter array for
7808// the inreg arguments. All other arguments are allocated a multiple of 8
7809// bytes.
7810//
7811namespace {
7812class SparcV9ABIInfo : public ABIInfo {
7813public:
7814 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7815
7816private:
7817 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007818 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007819 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7820 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007821
7822 // Coercion type builder for structs passed in registers. The coercion type
7823 // serves two purposes:
7824 //
7825 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7826 // in registers.
7827 // 2. Expose aligned floating point elements as first-level elements, so the
7828 // code generator knows to pass them in floating point registers.
7829 //
7830 // We also compute the InReg flag which indicates that the struct contains
7831 // aligned 32-bit floats.
7832 //
7833 struct CoerceBuilder {
7834 llvm::LLVMContext &Context;
7835 const llvm::DataLayout &DL;
7836 SmallVector<llvm::Type*, 8> Elems;
7837 uint64_t Size;
7838 bool InReg;
7839
7840 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7841 : Context(c), DL(dl), Size(0), InReg(false) {}
7842
7843 // Pad Elems with integers until Size is ToSize.
7844 void pad(uint64_t ToSize) {
7845 assert(ToSize >= Size && "Cannot remove elements");
7846 if (ToSize == Size)
7847 return;
7848
7849 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007850 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007851 if (Aligned > Size && Aligned <= ToSize) {
7852 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7853 Size = Aligned;
7854 }
7855
7856 // Add whole 64-bit words.
7857 while (Size + 64 <= ToSize) {
7858 Elems.push_back(llvm::Type::getInt64Ty(Context));
7859 Size += 64;
7860 }
7861
7862 // Final in-word padding.
7863 if (Size < ToSize) {
7864 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7865 Size = ToSize;
7866 }
7867 }
7868
7869 // Add a floating point element at Offset.
7870 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7871 // Unaligned floats are treated as integers.
7872 if (Offset % Bits)
7873 return;
7874 // The InReg flag is only required if there are any floats < 64 bits.
7875 if (Bits < 64)
7876 InReg = true;
7877 pad(Offset);
7878 Elems.push_back(Ty);
7879 Size = Offset + Bits;
7880 }
7881
7882 // Add a struct type to the coercion type, starting at Offset (in bits).
7883 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7884 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7885 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7886 llvm::Type *ElemTy = StrTy->getElementType(i);
7887 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7888 switch (ElemTy->getTypeID()) {
7889 case llvm::Type::StructTyID:
7890 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7891 break;
7892 case llvm::Type::FloatTyID:
7893 addFloat(ElemOffset, ElemTy, 32);
7894 break;
7895 case llvm::Type::DoubleTyID:
7896 addFloat(ElemOffset, ElemTy, 64);
7897 break;
7898 case llvm::Type::FP128TyID:
7899 addFloat(ElemOffset, ElemTy, 128);
7900 break;
7901 case llvm::Type::PointerTyID:
7902 if (ElemOffset % 64 == 0) {
7903 pad(ElemOffset);
7904 Elems.push_back(ElemTy);
7905 Size += 64;
7906 }
7907 break;
7908 default:
7909 break;
7910 }
7911 }
7912 }
7913
7914 // Check if Ty is a usable substitute for the coercion type.
7915 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007916 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007917 }
7918
7919 // Get the coercion type as a literal struct type.
7920 llvm::Type *getType() const {
7921 if (Elems.size() == 1)
7922 return Elems.front();
7923 else
7924 return llvm::StructType::get(Context, Elems);
7925 }
7926 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007927};
7928} // end anonymous namespace
7929
7930ABIArgInfo
7931SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7932 if (Ty->isVoidType())
7933 return ABIArgInfo::getIgnore();
7934
7935 uint64_t Size = getContext().getTypeSize(Ty);
7936
7937 // Anything too big to fit in registers is passed with an explicit indirect
7938 // pointer / sret pointer.
7939 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007940 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007941
7942 // Treat an enum type as its underlying type.
7943 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7944 Ty = EnumTy->getDecl()->getIntegerType();
7945
7946 // Integer types smaller than a register are extended.
7947 if (Size < 64 && Ty->isIntegerType())
7948 return ABIArgInfo::getExtend();
7949
7950 // Other non-aggregates go in registers.
7951 if (!isAggregateTypeForABI(Ty))
7952 return ABIArgInfo::getDirect();
7953
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007954 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7955 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7956 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007957 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007958
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007959 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007960 // Build a coercion type from the LLVM struct type.
7961 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7962 if (!StrTy)
7963 return ABIArgInfo::getDirect();
7964
7965 CoerceBuilder CB(getVMContext(), getDataLayout());
7966 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007967 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007968
7969 // Try to use the original type for coercion.
7970 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7971
7972 if (CB.InReg)
7973 return ABIArgInfo::getDirectInReg(CoerceTy);
7974 else
7975 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007976}
7977
John McCall7f416cc2015-09-08 08:05:57 +00007978Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7979 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007980 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7981 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7982 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7983 AI.setCoerceToType(ArgTy);
7984
John McCall7f416cc2015-09-08 08:05:57 +00007985 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007986
John McCall7f416cc2015-09-08 08:05:57 +00007987 CGBuilderTy &Builder = CGF.Builder;
7988 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7989 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7990
7991 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7992
7993 Address ArgAddr = Address::invalid();
7994 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007995 switch (AI.getKind()) {
7996 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007997 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007998 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007999 llvm_unreachable("Unsupported ABI kind for va_arg");
8000
John McCall7f416cc2015-09-08 08:05:57 +00008001 case ABIArgInfo::Extend: {
8002 Stride = SlotSize;
8003 CharUnits Offset = SlotSize - TypeInfo.first;
8004 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008005 break;
John McCall7f416cc2015-09-08 08:05:57 +00008006 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008007
John McCall7f416cc2015-09-08 08:05:57 +00008008 case ABIArgInfo::Direct: {
8009 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008010 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008011 ArgAddr = Addr;
8012 break;
John McCall7f416cc2015-09-08 08:05:57 +00008013 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008014
8015 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008016 Stride = SlotSize;
8017 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8018 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8019 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008020 break;
8021
8022 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008023 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008024 }
8025
8026 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008027 llvm::Value *NextPtr =
8028 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8029 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008030
John McCall7f416cc2015-09-08 08:05:57 +00008031 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008032}
8033
8034void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8035 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008036 for (auto &I : FI.arguments())
8037 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008038}
8039
8040namespace {
8041class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8042public:
8043 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8044 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008045
Craig Topper4f12f102014-03-12 06:41:41 +00008046 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008047 return 14;
8048 }
8049
8050 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008051 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008052};
8053} // end anonymous namespace
8054
Roman Divackyf02c9942014-02-24 18:46:27 +00008055bool
8056SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8057 llvm::Value *Address) const {
8058 // This is calculated from the LLVM and GCC tables and verified
8059 // against gcc output. AFAIK all ABIs use the same encoding.
8060
8061 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8062
8063 llvm::IntegerType *i8 = CGF.Int8Ty;
8064 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8065 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8066
8067 // 0-31: the 8-byte general-purpose registers
8068 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8069
8070 // 32-63: f0-31, the 4-byte floating-point registers
8071 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8072
8073 // Y = 64
8074 // PSR = 65
8075 // WIM = 66
8076 // TBR = 67
8077 // PC = 68
8078 // NPC = 69
8079 // FSR = 70
8080 // CSR = 71
8081 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008082
Roman Divackyf02c9942014-02-24 18:46:27 +00008083 // 72-87: d0-15, the 8-byte floating-point registers
8084 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8085
8086 return false;
8087}
8088
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008089
Robert Lytton0e076492013-08-13 09:43:10 +00008090//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008091// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008092//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008093
Robert Lytton0e076492013-08-13 09:43:10 +00008094namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008095
8096/// A SmallStringEnc instance is used to build up the TypeString by passing
8097/// it by reference between functions that append to it.
8098typedef llvm::SmallString<128> SmallStringEnc;
8099
8100/// TypeStringCache caches the meta encodings of Types.
8101///
8102/// The reason for caching TypeStrings is two fold:
8103/// 1. To cache a type's encoding for later uses;
8104/// 2. As a means to break recursive member type inclusion.
8105///
8106/// A cache Entry can have a Status of:
8107/// NonRecursive: The type encoding is not recursive;
8108/// Recursive: The type encoding is recursive;
8109/// Incomplete: An incomplete TypeString;
8110/// IncompleteUsed: An incomplete TypeString that has been used in a
8111/// Recursive type encoding.
8112///
8113/// A NonRecursive entry will have all of its sub-members expanded as fully
8114/// as possible. Whilst it may contain types which are recursive, the type
8115/// itself is not recursive and thus its encoding may be safely used whenever
8116/// the type is encountered.
8117///
8118/// A Recursive entry will have all of its sub-members expanded as fully as
8119/// possible. The type itself is recursive and it may contain other types which
8120/// are recursive. The Recursive encoding must not be used during the expansion
8121/// of a recursive type's recursive branch. For simplicity the code uses
8122/// IncompleteCount to reject all usage of Recursive encodings for member types.
8123///
8124/// An Incomplete entry is always a RecordType and only encodes its
8125/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8126/// are placed into the cache during type expansion as a means to identify and
8127/// handle recursive inclusion of types as sub-members. If there is recursion
8128/// the entry becomes IncompleteUsed.
8129///
8130/// During the expansion of a RecordType's members:
8131///
8132/// If the cache contains a NonRecursive encoding for the member type, the
8133/// cached encoding is used;
8134///
8135/// If the cache contains a Recursive encoding for the member type, the
8136/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8137///
8138/// If the member is a RecordType, an Incomplete encoding is placed into the
8139/// cache to break potential recursive inclusion of itself as a sub-member;
8140///
8141/// Once a member RecordType has been expanded, its temporary incomplete
8142/// entry is removed from the cache. If a Recursive encoding was swapped out
8143/// it is swapped back in;
8144///
8145/// If an incomplete entry is used to expand a sub-member, the incomplete
8146/// entry is marked as IncompleteUsed. The cache keeps count of how many
8147/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8148///
8149/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8150/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8151/// Else the member is part of a recursive type and thus the recursion has
8152/// been exited too soon for the encoding to be correct for the member.
8153///
8154class TypeStringCache {
8155 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8156 struct Entry {
8157 std::string Str; // The encoded TypeString for the type.
8158 enum Status State; // Information about the encoding in 'Str'.
8159 std::string Swapped; // A temporary place holder for a Recursive encoding
8160 // during the expansion of RecordType's members.
8161 };
8162 std::map<const IdentifierInfo *, struct Entry> Map;
8163 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8164 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8165public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008166 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008167 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8168 bool removeIncomplete(const IdentifierInfo *ID);
8169 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8170 bool IsRecursive);
8171 StringRef lookupStr(const IdentifierInfo *ID);
8172};
8173
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008174/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008175/// FieldEncoding is a helper for this ordering process.
8176class FieldEncoding {
8177 bool HasName;
8178 std::string Enc;
8179public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008180 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008181 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008182 bool operator<(const FieldEncoding &rhs) const {
8183 if (HasName != rhs.HasName) return HasName;
8184 return Enc < rhs.Enc;
8185 }
8186};
8187
Robert Lytton7d1db152013-08-19 09:46:39 +00008188class XCoreABIInfo : public DefaultABIInfo {
8189public:
8190 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008191 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8192 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008193};
8194
Robert Lyttond21e2d72014-03-03 13:45:29 +00008195class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008196 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008197public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008198 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008199 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008200 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8201 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008202};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008203
Robert Lytton2d196952013-10-11 10:29:34 +00008204} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008205
James Y Knight29b5f082016-02-24 02:59:33 +00008206// TODO: this implementation is likely now redundant with the default
8207// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008208Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8209 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008210 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008211
Robert Lytton2d196952013-10-11 10:29:34 +00008212 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008213 CharUnits SlotSize = CharUnits::fromQuantity(4);
8214 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008215
Robert Lytton2d196952013-10-11 10:29:34 +00008216 // Handle the argument.
8217 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008218 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008219 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8220 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8221 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008222 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008223
8224 Address Val = Address::invalid();
8225 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008226 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008227 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008228 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008229 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008230 llvm_unreachable("Unsupported ABI kind for va_arg");
8231 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008232 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8233 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008234 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008235 case ABIArgInfo::Extend:
8236 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008237 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8238 ArgSize = CharUnits::fromQuantity(
8239 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008240 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008241 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008242 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008243 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8244 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8245 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008246 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008247 }
Robert Lytton2d196952013-10-11 10:29:34 +00008248
8249 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008250 if (!ArgSize.isZero()) {
8251 llvm::Value *APN =
8252 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8253 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008254 }
John McCall7f416cc2015-09-08 08:05:57 +00008255
Robert Lytton2d196952013-10-11 10:29:34 +00008256 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008257}
Robert Lytton0e076492013-08-13 09:43:10 +00008258
Robert Lytton844aeeb2014-05-02 09:33:20 +00008259/// During the expansion of a RecordType, an incomplete TypeString is placed
8260/// into the cache as a means to identify and break recursion.
8261/// If there is a Recursive encoding in the cache, it is swapped out and will
8262/// be reinserted by removeIncomplete().
8263/// All other types of encoding should have been used rather than arriving here.
8264void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8265 std::string StubEnc) {
8266 if (!ID)
8267 return;
8268 Entry &E = Map[ID];
8269 assert( (E.Str.empty() || E.State == Recursive) &&
8270 "Incorrectly use of addIncomplete");
8271 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8272 E.Swapped.swap(E.Str); // swap out the Recursive
8273 E.Str.swap(StubEnc);
8274 E.State = Incomplete;
8275 ++IncompleteCount;
8276}
8277
8278/// Once the RecordType has been expanded, the temporary incomplete TypeString
8279/// must be removed from the cache.
8280/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8281/// Returns true if the RecordType was defined recursively.
8282bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8283 if (!ID)
8284 return false;
8285 auto I = Map.find(ID);
8286 assert(I != Map.end() && "Entry not present");
8287 Entry &E = I->second;
8288 assert( (E.State == Incomplete ||
8289 E.State == IncompleteUsed) &&
8290 "Entry must be an incomplete type");
8291 bool IsRecursive = false;
8292 if (E.State == IncompleteUsed) {
8293 // We made use of our Incomplete encoding, thus we are recursive.
8294 IsRecursive = true;
8295 --IncompleteUsedCount;
8296 }
8297 if (E.Swapped.empty())
8298 Map.erase(I);
8299 else {
8300 // Swap the Recursive back.
8301 E.Swapped.swap(E.Str);
8302 E.Swapped.clear();
8303 E.State = Recursive;
8304 }
8305 --IncompleteCount;
8306 return IsRecursive;
8307}
8308
8309/// Add the encoded TypeString to the cache only if it is NonRecursive or
8310/// Recursive (viz: all sub-members were expanded as fully as possible).
8311void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8312 bool IsRecursive) {
8313 if (!ID || IncompleteUsedCount)
8314 return; // No key or it is is an incomplete sub-type so don't add.
8315 Entry &E = Map[ID];
8316 if (IsRecursive && !E.Str.empty()) {
8317 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8318 "This is not the same Recursive entry");
8319 // The parent container was not recursive after all, so we could have used
8320 // this Recursive sub-member entry after all, but we assumed the worse when
8321 // we started viz: IncompleteCount!=0.
8322 return;
8323 }
8324 assert(E.Str.empty() && "Entry already present");
8325 E.Str = Str.str();
8326 E.State = IsRecursive? Recursive : NonRecursive;
8327}
8328
8329/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8330/// are recursively expanding a type (IncompleteCount != 0) and the cached
8331/// encoding is Recursive, return an empty StringRef.
8332StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8333 if (!ID)
8334 return StringRef(); // We have no key.
8335 auto I = Map.find(ID);
8336 if (I == Map.end())
8337 return StringRef(); // We have no encoding.
8338 Entry &E = I->second;
8339 if (E.State == Recursive && IncompleteCount)
8340 return StringRef(); // We don't use Recursive encodings for member types.
8341
8342 if (E.State == Incomplete) {
8343 // The incomplete type is being used to break out of recursion.
8344 E.State = IncompleteUsed;
8345 ++IncompleteUsedCount;
8346 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008347 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008348}
8349
8350/// The XCore ABI includes a type information section that communicates symbol
8351/// type information to the linker. The linker uses this information to verify
8352/// safety/correctness of things such as array bound and pointers et al.
8353/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8354/// This type information (TypeString) is emitted into meta data for all global
8355/// symbols: definitions, declarations, functions & variables.
8356///
8357/// The TypeString carries type, qualifier, name, size & value details.
8358/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008359/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008360/// The output is tested by test/CodeGen/xcore-stringtype.c.
8361///
8362static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8363 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8364
8365/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8366void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8367 CodeGen::CodeGenModule &CGM) const {
8368 SmallStringEnc Enc;
8369 if (getTypeString(Enc, D, CGM, TSC)) {
8370 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008371 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8372 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008373 llvm::NamedMDNode *MD =
8374 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8375 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8376 }
8377}
8378
Xiuli Pan972bea82016-03-24 03:57:17 +00008379//===----------------------------------------------------------------------===//
8380// SPIR ABI Implementation
8381//===----------------------------------------------------------------------===//
8382
8383namespace {
8384class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8385public:
8386 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8387 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008388 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008389};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008390
Xiuli Pan972bea82016-03-24 03:57:17 +00008391} // End anonymous namespace.
8392
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008393namespace clang {
8394namespace CodeGen {
8395void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8396 DefaultABIInfo SPIRABI(CGM.getTypes());
8397 SPIRABI.computeInfo(FI);
8398}
8399}
8400}
8401
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008402unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8403 return llvm::CallingConv::SPIR_KERNEL;
8404}
8405
Robert Lytton844aeeb2014-05-02 09:33:20 +00008406static bool appendType(SmallStringEnc &Enc, QualType QType,
8407 const CodeGen::CodeGenModule &CGM,
8408 TypeStringCache &TSC);
8409
8410/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008411/// Builds a SmallVector containing the encoded field types in declaration
8412/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008413static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8414 const RecordDecl *RD,
8415 const CodeGen::CodeGenModule &CGM,
8416 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008417 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008418 SmallStringEnc Enc;
8419 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008420 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008421 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008422 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008423 Enc += "b(";
8424 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008425 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008426 Enc += ':';
8427 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008428 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008429 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008430 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008431 Enc += ')';
8432 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008433 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008434 }
8435 return true;
8436}
8437
8438/// Appends structure and union types to Enc and adds encoding to cache.
8439/// Recursively calls appendType (via extractFieldType) for each field.
8440/// Union types have their fields ordered according to the ABI.
8441static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8442 const CodeGen::CodeGenModule &CGM,
8443 TypeStringCache &TSC, const IdentifierInfo *ID) {
8444 // Append the cached TypeString if we have one.
8445 StringRef TypeString = TSC.lookupStr(ID);
8446 if (!TypeString.empty()) {
8447 Enc += TypeString;
8448 return true;
8449 }
8450
8451 // Start to emit an incomplete TypeString.
8452 size_t Start = Enc.size();
8453 Enc += (RT->isUnionType()? 'u' : 's');
8454 Enc += '(';
8455 if (ID)
8456 Enc += ID->getName();
8457 Enc += "){";
8458
8459 // We collect all encoded fields and order as necessary.
8460 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008461 const RecordDecl *RD = RT->getDecl()->getDefinition();
8462 if (RD && !RD->field_empty()) {
8463 // An incomplete TypeString stub is placed in the cache for this RecordType
8464 // so that recursive calls to this RecordType will use it whilst building a
8465 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008466 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008467 std::string StubEnc(Enc.substr(Start).str());
8468 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8469 TSC.addIncomplete(ID, std::move(StubEnc));
8470 if (!extractFieldType(FE, RD, CGM, TSC)) {
8471 (void) TSC.removeIncomplete(ID);
8472 return false;
8473 }
8474 IsRecursive = TSC.removeIncomplete(ID);
8475 // The ABI requires unions to be sorted but not structures.
8476 // See FieldEncoding::operator< for sort algorithm.
8477 if (RT->isUnionType())
8478 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008479 // We can now complete the TypeString.
8480 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008481 for (unsigned I = 0; I != E; ++I) {
8482 if (I)
8483 Enc += ',';
8484 Enc += FE[I].str();
8485 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008486 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008487 Enc += '}';
8488 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8489 return true;
8490}
8491
8492/// Appends enum types to Enc and adds the encoding to the cache.
8493static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8494 TypeStringCache &TSC,
8495 const IdentifierInfo *ID) {
8496 // Append the cached TypeString if we have one.
8497 StringRef TypeString = TSC.lookupStr(ID);
8498 if (!TypeString.empty()) {
8499 Enc += TypeString;
8500 return true;
8501 }
8502
8503 size_t Start = Enc.size();
8504 Enc += "e(";
8505 if (ID)
8506 Enc += ID->getName();
8507 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008508
8509 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008510 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008511 SmallVector<FieldEncoding, 16> FE;
8512 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8513 ++I) {
8514 SmallStringEnc EnumEnc;
8515 EnumEnc += "m(";
8516 EnumEnc += I->getName();
8517 EnumEnc += "){";
8518 I->getInitVal().toString(EnumEnc);
8519 EnumEnc += '}';
8520 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8521 }
8522 std::sort(FE.begin(), FE.end());
8523 unsigned E = FE.size();
8524 for (unsigned I = 0; I != E; ++I) {
8525 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008526 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008527 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008528 }
8529 }
8530 Enc += '}';
8531 TSC.addIfComplete(ID, Enc.substr(Start), false);
8532 return true;
8533}
8534
8535/// Appends type's qualifier to Enc.
8536/// This is done prior to appending the type's encoding.
8537static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8538 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008539 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008540 int Lookup = 0;
8541 if (QT.isConstQualified())
8542 Lookup += 1<<0;
8543 if (QT.isRestrictQualified())
8544 Lookup += 1<<1;
8545 if (QT.isVolatileQualified())
8546 Lookup += 1<<2;
8547 Enc += Table[Lookup];
8548}
8549
8550/// Appends built-in types to Enc.
8551static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8552 const char *EncType;
8553 switch (BT->getKind()) {
8554 case BuiltinType::Void:
8555 EncType = "0";
8556 break;
8557 case BuiltinType::Bool:
8558 EncType = "b";
8559 break;
8560 case BuiltinType::Char_U:
8561 EncType = "uc";
8562 break;
8563 case BuiltinType::UChar:
8564 EncType = "uc";
8565 break;
8566 case BuiltinType::SChar:
8567 EncType = "sc";
8568 break;
8569 case BuiltinType::UShort:
8570 EncType = "us";
8571 break;
8572 case BuiltinType::Short:
8573 EncType = "ss";
8574 break;
8575 case BuiltinType::UInt:
8576 EncType = "ui";
8577 break;
8578 case BuiltinType::Int:
8579 EncType = "si";
8580 break;
8581 case BuiltinType::ULong:
8582 EncType = "ul";
8583 break;
8584 case BuiltinType::Long:
8585 EncType = "sl";
8586 break;
8587 case BuiltinType::ULongLong:
8588 EncType = "ull";
8589 break;
8590 case BuiltinType::LongLong:
8591 EncType = "sll";
8592 break;
8593 case BuiltinType::Float:
8594 EncType = "ft";
8595 break;
8596 case BuiltinType::Double:
8597 EncType = "d";
8598 break;
8599 case BuiltinType::LongDouble:
8600 EncType = "ld";
8601 break;
8602 default:
8603 return false;
8604 }
8605 Enc += EncType;
8606 return true;
8607}
8608
8609/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8610static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8611 const CodeGen::CodeGenModule &CGM,
8612 TypeStringCache &TSC) {
8613 Enc += "p(";
8614 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8615 return false;
8616 Enc += ')';
8617 return true;
8618}
8619
8620/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008621static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8622 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008623 const CodeGen::CodeGenModule &CGM,
8624 TypeStringCache &TSC, StringRef NoSizeEnc) {
8625 if (AT->getSizeModifier() != ArrayType::Normal)
8626 return false;
8627 Enc += "a(";
8628 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8629 CAT->getSize().toStringUnsigned(Enc);
8630 else
8631 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8632 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008633 // The Qualifiers should be attached to the type rather than the array.
8634 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008635 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8636 return false;
8637 Enc += ')';
8638 return true;
8639}
8640
8641/// Appends a function encoding to Enc, calling appendType for the return type
8642/// and the arguments.
8643static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8644 const CodeGen::CodeGenModule &CGM,
8645 TypeStringCache &TSC) {
8646 Enc += "f{";
8647 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8648 return false;
8649 Enc += "}(";
8650 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8651 // N.B. we are only interested in the adjusted param types.
8652 auto I = FPT->param_type_begin();
8653 auto E = FPT->param_type_end();
8654 if (I != E) {
8655 do {
8656 if (!appendType(Enc, *I, CGM, TSC))
8657 return false;
8658 ++I;
8659 if (I != E)
8660 Enc += ',';
8661 } while (I != E);
8662 if (FPT->isVariadic())
8663 Enc += ",va";
8664 } else {
8665 if (FPT->isVariadic())
8666 Enc += "va";
8667 else
8668 Enc += '0';
8669 }
8670 }
8671 Enc += ')';
8672 return true;
8673}
8674
8675/// Handles the type's qualifier before dispatching a call to handle specific
8676/// type encodings.
8677static bool appendType(SmallStringEnc &Enc, QualType QType,
8678 const CodeGen::CodeGenModule &CGM,
8679 TypeStringCache &TSC) {
8680
8681 QualType QT = QType.getCanonicalType();
8682
Robert Lytton6adb20f2014-06-05 09:06:21 +00008683 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8684 // The Qualifiers should be attached to the type rather than the array.
8685 // Thus we don't call appendQualifier() here.
8686 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8687
Robert Lytton844aeeb2014-05-02 09:33:20 +00008688 appendQualifier(Enc, QT);
8689
8690 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8691 return appendBuiltinType(Enc, BT);
8692
Robert Lytton844aeeb2014-05-02 09:33:20 +00008693 if (const PointerType *PT = QT->getAs<PointerType>())
8694 return appendPointerType(Enc, PT, CGM, TSC);
8695
8696 if (const EnumType *ET = QT->getAs<EnumType>())
8697 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8698
8699 if (const RecordType *RT = QT->getAsStructureType())
8700 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8701
8702 if (const RecordType *RT = QT->getAsUnionType())
8703 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8704
8705 if (const FunctionType *FT = QT->getAs<FunctionType>())
8706 return appendFunctionType(Enc, FT, CGM, TSC);
8707
8708 return false;
8709}
8710
8711static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8712 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8713 if (!D)
8714 return false;
8715
8716 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8717 if (FD->getLanguageLinkage() != CLanguageLinkage)
8718 return false;
8719 return appendType(Enc, FD->getType(), CGM, TSC);
8720 }
8721
8722 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8723 if (VD->getLanguageLinkage() != CLanguageLinkage)
8724 return false;
8725 QualType QT = VD->getType().getCanonicalType();
8726 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8727 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008728 // The Qualifiers should be attached to the type rather than the array.
8729 // Thus we don't call appendQualifier() here.
8730 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008731 }
8732 return appendType(Enc, QT, CGM, TSC);
8733 }
8734 return false;
8735}
8736
8737
Robert Lytton0e076492013-08-13 09:43:10 +00008738//===----------------------------------------------------------------------===//
8739// Driver code
8740//===----------------------------------------------------------------------===//
8741
Rafael Espindola9f834732014-09-19 01:54:22 +00008742bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008743 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008744}
8745
Chris Lattner2b037972010-07-29 02:01:43 +00008746const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008747 if (TheTargetCodeGenInfo)
8748 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008749
Reid Kleckner9305fd12016-04-13 23:37:17 +00008750 // Helper to set the unique_ptr while still keeping the return value.
8751 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8752 this->TheTargetCodeGenInfo.reset(P);
8753 return *P;
8754 };
8755
John McCallc8e01702013-04-16 22:48:15 +00008756 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008757 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008758 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008759 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008760
Derek Schuff09338a22012-09-06 17:37:28 +00008761 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008762 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008763 case llvm::Triple::mips:
8764 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008765 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008766 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8767 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008768
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008769 case llvm::Triple::mips64:
8770 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008771 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008772
Dylan McKaye8232d72017-02-08 05:09:26 +00008773 case llvm::Triple::avr:
8774 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8775
Tim Northover25e8a672014-05-24 12:51:25 +00008776 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008777 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008778 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008779 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008780 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008781 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008782 return SetCGInfo(
8783 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008784
Reid Kleckner9305fd12016-04-13 23:37:17 +00008785 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008786 }
8787
Dan Gohmanc2853072015-09-03 22:51:53 +00008788 case llvm::Triple::wasm32:
8789 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008790 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008791
Daniel Dunbard59655c2009-09-12 00:59:49 +00008792 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008793 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008794 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008795 case llvm::Triple::thumbeb: {
8796 if (Triple.getOS() == llvm::Triple::Win32) {
8797 return SetCGInfo(
8798 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008799 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008800
Reid Kleckner9305fd12016-04-13 23:37:17 +00008801 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8802 StringRef ABIStr = getTarget().getABI();
8803 if (ABIStr == "apcs-gnu")
8804 Kind = ARMABIInfo::APCS;
8805 else if (ABIStr == "aapcs16")
8806 Kind = ARMABIInfo::AAPCS16_VFP;
8807 else if (CodeGenOpts.FloatABI == "hard" ||
8808 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008809 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008810 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008811 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008812 Kind = ARMABIInfo::AAPCS_VFP;
8813
8814 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8815 }
8816
John McCallea8d8bb2010-03-11 00:10:12 +00008817 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008818 return SetCGInfo(
8819 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008820 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008821 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008822 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008823 if (getTarget().getABI() == "elfv2")
8824 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008825 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008826 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008827
Hal Finkel415c2a32016-10-02 02:10:45 +00008828 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8829 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008830 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008831 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008832 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008833 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008834 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008835 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008836 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008837 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008838 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008839
Hal Finkel415c2a32016-10-02 02:10:45 +00008840 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8841 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008842 }
John McCallea8d8bb2010-03-11 00:10:12 +00008843
Peter Collingbournec947aae2012-05-20 23:28:41 +00008844 case llvm::Triple::nvptx:
8845 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008846 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008847
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008848 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008849 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008850
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008851 case llvm::Triple::systemz: {
8852 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008853 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008854 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008855
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008856 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008857 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008858 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008859
Eli Friedman33465822011-07-08 23:31:17 +00008860 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008861 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008862 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008863 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008864 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008865
John McCall1fe2a8c2013-06-18 02:46:29 +00008866 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008867 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8868 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8869 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008870 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008871 return SetCGInfo(new X86_32TargetCodeGenInfo(
8872 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8873 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8874 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008875 }
Eli Friedman33465822011-07-08 23:31:17 +00008876 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008877
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008878 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008879 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008880 X86AVXABILevel AVXLevel =
8881 (ABI == "avx512"
8882 ? X86AVXABILevel::AVX512
8883 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008884
Chris Lattner04dc9572010-08-31 16:44:54 +00008885 switch (Triple.getOS()) {
8886 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008887 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008888 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008889 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008890 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008891 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008892 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008893 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008894 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008895 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008896 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008897 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008898 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008899 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008900 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008901 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008902 case llvm::Triple::sparc:
8903 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008904 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008905 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008906 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008907 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008908 case llvm::Triple::spir:
8909 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008910 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008911 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008912}