blob: 4ebbef7dfb5b9adc2b3c389167afc0c3c40b2890 [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 {
401 return llvm::CallingConv::C;
402}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000403
Yaxun Liu402804b2016-12-15 08:09:08 +0000404llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
405 llvm::PointerType *T, QualType QT) const {
406 return llvm::ConstantPointerNull::get(T);
407}
408
409llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
410 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, QualType SrcTy,
411 QualType DestTy) const {
412 // Since target may map different address spaces in AST to the same address
413 // space, an address space conversion may end up as a bitcast.
414 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src,
415 CGF.ConvertType(DestTy));
416}
417
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000418static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000419
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000420/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000421/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000422static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
423 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424 if (FD->isUnnamedBitfield())
425 return true;
426
427 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428
Eli Friedman0b3f2012011-11-18 03:47:20 +0000429 // Constant arrays of empty records count as empty, strip them off.
430 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000431 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000432 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
433 if (AT->getSize() == 0)
434 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000435 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000436 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000437
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000438 const RecordType *RT = FT->getAs<RecordType>();
439 if (!RT)
440 return false;
441
442 // C++ record fields are never empty, at least in the Itanium ABI.
443 //
444 // FIXME: We should use a predicate for whether this behavior is true in the
445 // current ABI.
446 if (isa<CXXRecordDecl>(RT->getDecl()))
447 return false;
448
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000449 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000450}
451
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000452/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000453/// fields. Note that a structure with a flexible array member is not
454/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000455static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000456 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000458 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000459 const RecordDecl *RD = RT->getDecl();
460 if (RD->hasFlexibleArrayMember())
461 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000462
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000463 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000464 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000465 for (const auto &I : CXXRD->bases())
466 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000467 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000468
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000469 for (const auto *I : RD->fields())
470 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 return false;
472 return true;
473}
474
475/// isSingleElementStruct - Determine if a structure is a "single
476/// element struct", i.e. it has exactly one non-empty field or
477/// exactly one field which is itself a single element
478/// struct. Structures with flexible array members are never
479/// considered single element structs.
480///
481/// \return The field declaration for the single non-empty field, if
482/// it exists.
483static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000484 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000485 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000486 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000487
488 const RecordDecl *RD = RT->getDecl();
489 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000490 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491
Craig Topper8a13c412014-05-21 05:09:00 +0000492 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000493
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000494 // If this is a C++ record, check the bases first.
495 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000496 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000497 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000498 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000499 continue;
500
501 // If we already found an element then this isn't a single-element struct.
502 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000503 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000504
505 // If this is non-empty and not a single element struct, the composite
506 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000507 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000508 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000509 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000510 }
511 }
512
513 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000514 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000515 QualType FT = FD->getType();
516
517 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000518 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000519 continue;
520
521 // If we already found an element then this isn't a single-element
522 // struct.
523 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000524 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525
526 // Treat single element arrays as the element.
527 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
528 if (AT->getSize().getZExtValue() != 1)
529 break;
530 FT = AT->getElementType();
531 }
532
John McCalla1dee5302010-08-22 10:59:02 +0000533 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000534 Found = FT.getTypePtr();
535 } else {
536 Found = isSingleElementStruct(FT, Context);
537 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000538 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000539 }
540 }
541
Eli Friedmanee945342011-11-18 01:25:50 +0000542 // We don't consider a struct a single-element struct if it has
543 // padding beyond the element type.
544 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000545 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000546
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000547 return Found;
548}
549
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000550namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000551Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
552 const ABIArgInfo &AI) {
553 // This default implementation defers to the llvm backend's va_arg
554 // instruction. It can handle only passing arguments directly
555 // (typically only handled in the backend for primitive types), or
556 // aggregates passed indirectly by pointer (NOTE: if the "byval"
557 // flag has ABI impact in the callee, this implementation cannot
558 // work.)
559
560 // Only a few cases are covered here at the moment -- those needed
561 // by the default abi.
562 llvm::Value *Val;
563
564 if (AI.isIndirect()) {
565 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000566 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000567 assert(
568 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000569 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000570
571 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
572 CharUnits TyAlignForABI = TyInfo.second;
573
574 llvm::Type *BaseTy =
575 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
576 llvm::Value *Addr =
577 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
578 return Address(Addr, TyAlignForABI);
579 } else {
580 assert((AI.isDirect() || AI.isExtend()) &&
581 "Unexpected ArgInfo Kind in generic VAArg emitter!");
582
583 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000584 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000585 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000586 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000587 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000588 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000589 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000590 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000591
592 Address Temp = CGF.CreateMemTemp(Ty, "varet");
593 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
594 CGF.Builder.CreateStore(Val, Temp);
595 return Temp;
596 }
597}
598
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000599/// DefaultABIInfo - The default implementation for ABI specific
600/// details. This implementation provides information which results in
601/// self-consistent and sensible LLVM IR generation, but does not
602/// conform to any particular ABI.
603class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000604public:
605 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000606
Chris Lattner458b2aa2010-07-29 02:16:43 +0000607 ABIArgInfo classifyReturnType(QualType RetTy) const;
608 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000609
Craig Topper4f12f102014-03-12 06:41:41 +0000610 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000611 if (!getCXXABI().classifyReturnType(FI))
612 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000613 for (auto &I : FI.arguments())
614 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000615 }
616
John McCall7f416cc2015-09-08 08:05:57 +0000617 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000618 QualType Ty) const override {
619 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
620 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000621};
622
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000623class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
624public:
Chris Lattner2b037972010-07-29 02:01:43 +0000625 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
626 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000627};
628
Chris Lattner458b2aa2010-07-29 02:16:43 +0000629ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000630 Ty = useFirstFieldIfTransparentUnion(Ty);
631
632 if (isAggregateTypeForABI(Ty)) {
633 // Records with non-trivial destructors/copy-constructors should not be
634 // passed by value.
635 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000636 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000637
John McCall7f416cc2015-09-08 08:05:57 +0000638 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000639 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000640
Chris Lattner9723d6c2010-03-11 18:19:55 +0000641 // Treat an enum type as its underlying type.
642 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
643 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000644
Chris Lattner9723d6c2010-03-11 18:19:55 +0000645 return (Ty->isPromotableIntegerType() ?
646 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000647}
648
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000649ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
650 if (RetTy->isVoidType())
651 return ABIArgInfo::getIgnore();
652
653 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000654 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000655
656 // Treat an enum type as its underlying type.
657 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
658 RetTy = EnumTy->getDecl()->getIntegerType();
659
660 return (RetTy->isPromotableIntegerType() ?
661 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
662}
663
Derek Schuff09338a22012-09-06 17:37:28 +0000664//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000665// WebAssembly ABI Implementation
666//
667// This is a very simple ABI that relies a lot on DefaultABIInfo.
668//===----------------------------------------------------------------------===//
669
670class WebAssemblyABIInfo final : public DefaultABIInfo {
671public:
672 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
673 : DefaultABIInfo(CGT) {}
674
675private:
676 ABIArgInfo classifyReturnType(QualType RetTy) const;
677 ABIArgInfo classifyArgumentType(QualType Ty) const;
678
679 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000680 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000681 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000682 void computeInfo(CGFunctionInfo &FI) const override {
683 if (!getCXXABI().classifyReturnType(FI))
684 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
685 for (auto &Arg : FI.arguments())
686 Arg.info = classifyArgumentType(Arg.type);
687 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000688
689 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
690 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000691};
692
693class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
694public:
695 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
696 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
697};
698
699/// \brief Classify argument of given type \p Ty.
700ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
701 Ty = useFirstFieldIfTransparentUnion(Ty);
702
703 if (isAggregateTypeForABI(Ty)) {
704 // Records with non-trivial destructors/copy-constructors should not be
705 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000706 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000707 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000708 // Ignore empty structs/unions.
709 if (isEmptyRecord(getContext(), Ty, true))
710 return ABIArgInfo::getIgnore();
711 // Lower single-element structs to just pass a regular value. TODO: We
712 // could do reasonable-size multiple-element structs too, using getExpand(),
713 // though watch out for things like bitfields.
714 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
715 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000716 }
717
718 // Otherwise just do the default thing.
719 return DefaultABIInfo::classifyArgumentType(Ty);
720}
721
722ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
723 if (isAggregateTypeForABI(RetTy)) {
724 // Records with non-trivial destructors/copy-constructors should not be
725 // returned by value.
726 if (!getRecordArgABI(RetTy, getCXXABI())) {
727 // Ignore empty structs/unions.
728 if (isEmptyRecord(getContext(), RetTy, true))
729 return ABIArgInfo::getIgnore();
730 // Lower single-element structs to just return a regular value. TODO: We
731 // could do reasonable-size multiple-element structs too, using
732 // ABIArgInfo::getDirect().
733 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
734 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
735 }
736 }
737
738 // Otherwise just do the default thing.
739 return DefaultABIInfo::classifyReturnType(RetTy);
740}
741
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000742Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
743 QualType Ty) const {
744 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
745 getContext().getTypeInfoInChars(Ty),
746 CharUnits::fromQuantity(4),
747 /*AllowHigherAlign=*/ true);
748}
749
Dan Gohmanc2853072015-09-03 22:51:53 +0000750//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000751// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000752//
753// This is a simplified version of the x86_32 ABI. Arguments and return values
754// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000755//===----------------------------------------------------------------------===//
756
757class PNaClABIInfo : public ABIInfo {
758 public:
759 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
760
761 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000762 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000763
Craig Topper4f12f102014-03-12 06:41:41 +0000764 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000765 Address EmitVAArg(CodeGenFunction &CGF,
766 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000767};
768
769class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
770 public:
771 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
772 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
773};
774
775void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000776 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000777 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
778
Reid Kleckner40ca9132014-05-13 22:05:45 +0000779 for (auto &I : FI.arguments())
780 I.info = classifyArgumentType(I.type);
781}
Derek Schuff09338a22012-09-06 17:37:28 +0000782
John McCall7f416cc2015-09-08 08:05:57 +0000783Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
784 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000785 // The PNaCL ABI is a bit odd, in that varargs don't use normal
786 // function classification. Structs get passed directly for varargs
787 // functions, through a rewriting transform in
788 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
789 // this target to actually support a va_arg instructions with an
790 // aggregate type, unlike other targets.
791 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000792}
793
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000794/// \brief Classify argument of given type \p Ty.
795ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000796 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000797 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000798 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
799 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000800 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
801 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000802 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000803 } else if (Ty->isFloatingType()) {
804 // Floating-point types don't go inreg.
805 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000806 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000807
808 return (Ty->isPromotableIntegerType() ?
809 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000810}
811
812ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
813 if (RetTy->isVoidType())
814 return ABIArgInfo::getIgnore();
815
Eli Benderskye20dad62013-04-04 22:49:35 +0000816 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000817 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000818 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000819
820 // Treat an enum type as its underlying type.
821 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
822 RetTy = EnumTy->getDecl()->getIntegerType();
823
824 return (RetTy->isPromotableIntegerType() ?
825 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
826}
827
Chad Rosier651c1832013-03-25 21:00:27 +0000828/// IsX86_MMXType - Return true if this is an MMX type.
829bool IsX86_MMXType(llvm::Type *IRType) {
830 // 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 +0000831 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
832 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
833 IRType->getScalarSizeInBits() != 64;
834}
835
Jay Foad7c57be32011-07-11 09:56:20 +0000836static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000837 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000838 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000839 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
840 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
841 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000842 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000843 }
844
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000845 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000846 }
847
848 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000849 return Ty;
850}
851
Reid Kleckner80944df2014-10-31 22:00:51 +0000852/// Returns true if this type can be passed in SSE registers with the
853/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
854static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
855 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
856 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
857 return true;
858 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
859 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
860 // registers specially.
861 unsigned VecSize = Context.getTypeSize(VT);
862 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
863 return true;
864 }
865 return false;
866}
867
868/// Returns true if this aggregate is small enough to be passed in SSE registers
869/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
870static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
871 return NumMembers <= 4;
872}
873
Erich Keane521ed962017-01-05 00:20:51 +0000874/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
875static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
876 auto AI = ABIArgInfo::getDirect(T);
877 AI.setInReg(true);
878 AI.setCanBeFlattened(false);
879 return AI;
880}
881
Chris Lattner0cf24192010-06-28 20:05:43 +0000882//===----------------------------------------------------------------------===//
883// X86-32 ABI Implementation
884//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000885
Reid Kleckner661f35b2014-01-18 01:12:41 +0000886/// \brief Similar to llvm::CCState, but for Clang.
887struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000888 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000889
890 unsigned CC;
891 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000892 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000893};
894
Erich Keane521ed962017-01-05 00:20:51 +0000895enum {
896 // Vectorcall only allows the first 6 parameters to be passed in registers.
897 VectorcallMaxParamNumAsReg = 6
898};
899
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000900/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000901class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000902 enum Class {
903 Integer,
904 Float
905 };
906
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000907 static const unsigned MinABIStackAlignInBytes = 4;
908
David Chisnallde3a0692009-08-17 23:08:21 +0000909 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000910 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000911 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000912 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000913 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000914 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915
916 static bool isRegisterSize(unsigned Size) {
917 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
918 }
919
Reid Kleckner80944df2014-10-31 22:00:51 +0000920 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
921 // FIXME: Assumes vectorcall is in use.
922 return isX86VectorTypeForVectorCall(getContext(), Ty);
923 }
924
925 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
926 uint64_t NumMembers) const override {
927 // FIXME: Assumes vectorcall is in use.
928 return isX86VectorCallAggregateSmallEnough(NumMembers);
929 }
930
Reid Kleckner40ca9132014-05-13 22:05:45 +0000931 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932
Daniel Dunbar557893d2010-04-21 19:10:51 +0000933 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
934 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000935 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
936
John McCall7f416cc2015-09-08 08:05:57 +0000937 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000938
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000939 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000940 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000941
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000942 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000943 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane521ed962017-01-05 00:20:51 +0000945 ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State,
946 const ABIArgInfo& current) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000947 /// \brief Updates the number of available free registers, returns
948 /// true if any registers were allocated.
949 bool updateFreeRegs(QualType Ty, CCState &State) const;
950
951 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
952 bool &NeedsPadding) const;
953 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000954
Reid Kleckner04046052016-05-02 17:41:07 +0000955 bool canExpandIndirectArgument(QualType Ty) const;
956
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000957 /// \brief Rewrite the function info so that all memory arguments use
958 /// inalloca.
959 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
960
961 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000962 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000963 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +0000964 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
965 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000966
Rafael Espindola75419dc2012-07-23 23:30:29 +0000967public:
968
Craig Topper4f12f102014-03-12 06:41:41 +0000969 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000970 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
971 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000972
Michael Kupersteindc745202015-10-19 07:52:25 +0000973 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
974 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000975 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000976 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000977 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
978 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000979 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000980 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000981 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000982
983 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
984 ArrayRef<llvm::Type*> scalars,
985 bool asReturnValue) const override {
986 // LLVM's x86-32 lowering currently only assigns up to three
987 // integer registers and three fp registers. Oddly, it'll use up to
988 // four vector registers for vectors, but those can overlap with the
989 // scalar registers.
990 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
991 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +0000992
993 bool isSwiftErrorInRegister() const override {
994 // x86-32 lowering does not support passing swifterror in a register.
995 return false;
996 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000997};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000998
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000999class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1000public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001001 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1002 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001003 unsigned NumRegisterParameters, bool SoftFloatABI)
1004 : TargetCodeGenInfo(new X86_32ABIInfo(
1005 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1006 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001007
John McCall1fe2a8c2013-06-18 02:46:29 +00001008 static bool isStructReturnInRegABI(
1009 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1010
Eric Christopher162c91c2015-06-05 22:03:00 +00001011 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00001012 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001013
Craig Topper4f12f102014-03-12 06:41:41 +00001014 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001015 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001016 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001017 return 4;
1018 }
1019
1020 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001021 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001022
Jay Foad7c57be32011-07-11 09:56:20 +00001023 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001024 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001025 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001026 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1027 }
1028
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001029 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1030 std::string &Constraints,
1031 std::vector<llvm::Type *> &ResultRegTypes,
1032 std::vector<llvm::Type *> &ResultTruncRegTypes,
1033 std::vector<LValue> &ResultRegDests,
1034 std::string &AsmString,
1035 unsigned NumOutputs) const override;
1036
Craig Topper4f12f102014-03-12 06:41:41 +00001037 llvm::Constant *
1038 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001039 unsigned Sig = (0xeb << 0) | // jmp rel8
1040 (0x06 << 8) | // .+0x08
1041 ('F' << 16) |
1042 ('T' << 24);
1043 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1044 }
John McCall01391782016-02-05 21:37:38 +00001045
1046 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1047 return "movl\t%ebp, %ebp"
1048 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1049 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001050};
1051
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001052}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001054/// Rewrite input constraint references after adding some output constraints.
1055/// In the case where there is one output and one input and we add one output,
1056/// we need to replace all operand references greater than or equal to 1:
1057/// mov $0, $1
1058/// mov eax, $1
1059/// The result will be:
1060/// mov $0, $2
1061/// mov eax, $2
1062static void rewriteInputConstraintReferences(unsigned FirstIn,
1063 unsigned NumNewOuts,
1064 std::string &AsmString) {
1065 std::string Buf;
1066 llvm::raw_string_ostream OS(Buf);
1067 size_t Pos = 0;
1068 while (Pos < AsmString.size()) {
1069 size_t DollarStart = AsmString.find('$', Pos);
1070 if (DollarStart == std::string::npos)
1071 DollarStart = AsmString.size();
1072 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1073 if (DollarEnd == std::string::npos)
1074 DollarEnd = AsmString.size();
1075 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1076 Pos = DollarEnd;
1077 size_t NumDollars = DollarEnd - DollarStart;
1078 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1079 // We have an operand reference.
1080 size_t DigitStart = Pos;
1081 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1082 if (DigitEnd == std::string::npos)
1083 DigitEnd = AsmString.size();
1084 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1085 unsigned OperandIndex;
1086 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1087 if (OperandIndex >= FirstIn)
1088 OperandIndex += NumNewOuts;
1089 OS << OperandIndex;
1090 } else {
1091 OS << OperandStr;
1092 }
1093 Pos = DigitEnd;
1094 }
1095 }
1096 AsmString = std::move(OS.str());
1097}
1098
1099/// Add output constraints for EAX:EDX because they are return registers.
1100void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1101 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1102 std::vector<llvm::Type *> &ResultRegTypes,
1103 std::vector<llvm::Type *> &ResultTruncRegTypes,
1104 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1105 unsigned NumOutputs) const {
1106 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1107
1108 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1109 // larger.
1110 if (!Constraints.empty())
1111 Constraints += ',';
1112 if (RetWidth <= 32) {
1113 Constraints += "={eax}";
1114 ResultRegTypes.push_back(CGF.Int32Ty);
1115 } else {
1116 // Use the 'A' constraint for EAX:EDX.
1117 Constraints += "=A";
1118 ResultRegTypes.push_back(CGF.Int64Ty);
1119 }
1120
1121 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1122 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1123 ResultTruncRegTypes.push_back(CoerceTy);
1124
1125 // Coerce the integer by bitcasting the return slot pointer.
1126 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1127 CoerceTy->getPointerTo()));
1128 ResultRegDests.push_back(ReturnSlot);
1129
1130 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1131}
1132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001133/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001134/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001135bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1136 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001137 uint64_t Size = Context.getTypeSize(Ty);
1138
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001139 // For i386, type must be register sized.
1140 // For the MCU ABI, it only needs to be <= 8-byte
1141 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1142 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001143
1144 if (Ty->isVectorType()) {
1145 // 64- and 128- bit vectors inside structures are not returned in
1146 // registers.
1147 if (Size == 64 || Size == 128)
1148 return false;
1149
1150 return true;
1151 }
1152
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001153 // If this is a builtin, pointer, enum, complex type, member pointer, or
1154 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001155 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001156 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001157 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001158 return true;
1159
1160 // Arrays are treated like records.
1161 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001162 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001163
1164 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001165 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001166 if (!RT) return false;
1167
Anders Carlsson40446e82010-01-27 03:25:19 +00001168 // FIXME: Traverse bases here too.
1169
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001170 // Structure types are passed in register if all fields would be
1171 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001172 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001173 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001174 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001175 continue;
1176
1177 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001178 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001179 return false;
1180 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181 return true;
1182}
1183
Reid Kleckner04046052016-05-02 17:41:07 +00001184static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1185 // Treat complex types as the element type.
1186 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1187 Ty = CTy->getElementType();
1188
1189 // Check for a type which we know has a simple scalar argument-passing
1190 // convention without any padding. (We're specifically looking for 32
1191 // and 64-bit integer and integer-equivalents, float, and double.)
1192 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1193 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1194 return false;
1195
1196 uint64_t Size = Context.getTypeSize(Ty);
1197 return Size == 32 || Size == 64;
1198}
1199
Reid Kleckner791bbf62017-01-13 17:18:19 +00001200static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1201 uint64_t &Size) {
1202 for (const auto *FD : RD->fields()) {
1203 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1204 // argument is smaller than 32-bits, expanding the struct will create
1205 // alignment padding.
1206 if (!is32Or64BitBasicType(FD->getType(), Context))
1207 return false;
1208
1209 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1210 // how to expand them yet, and the predicate for telling if a bitfield still
1211 // counts as "basic" is more complicated than what we were doing previously.
1212 if (FD->isBitField())
1213 return false;
1214
1215 Size += Context.getTypeSize(FD->getType());
1216 }
1217 return true;
1218}
1219
1220static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1221 uint64_t &Size) {
1222 // Don't do this if there are any non-empty bases.
1223 for (const CXXBaseSpecifier &Base : RD->bases()) {
1224 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1225 Size))
1226 return false;
1227 }
1228 if (!addFieldSizes(Context, RD, Size))
1229 return false;
1230 return true;
1231}
1232
Reid Kleckner04046052016-05-02 17:41:07 +00001233/// Test whether an argument type which is to be passed indirectly (on the
1234/// stack) would have the equivalent layout if it was expanded into separate
1235/// arguments. If so, we prefer to do the latter to avoid inhibiting
1236/// optimizations.
1237bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1238 // We can only expand structure types.
1239 const RecordType *RT = Ty->getAs<RecordType>();
1240 if (!RT)
1241 return false;
1242 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001243 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001244 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001245 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001246 // On non-Windows, we have to conservatively match our old bitcode
1247 // prototypes in order to be ABI-compatible at the bitcode level.
1248 if (!CXXRD->isCLike())
1249 return false;
1250 } else {
1251 // Don't do this for dynamic classes.
1252 if (CXXRD->isDynamicClass())
1253 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001254 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001255 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001256 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001257 } else {
1258 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001259 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001260 }
1261
1262 // We can do this if there was no alignment padding.
1263 return Size == getContext().getTypeSize(Ty);
1264}
1265
John McCall7f416cc2015-09-08 08:05:57 +00001266ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001267 // If the return value is indirect, then the hidden argument is consuming one
1268 // integer register.
1269 if (State.FreeRegs) {
1270 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001271 if (!IsMCUABI)
1272 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001273 }
John McCall7f416cc2015-09-08 08:05:57 +00001274 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001275}
1276
Eric Christopher7565e0d2015-05-29 23:09:49 +00001277ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1278 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001279 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001280 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001281
Reid Kleckner80944df2014-10-31 22:00:51 +00001282 const Type *Base = nullptr;
1283 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001284 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1285 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001286 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1287 // The LLVM struct type for such an aggregate should lower properly.
1288 return ABIArgInfo::getDirect();
1289 }
1290
Chris Lattner458b2aa2010-07-29 02:16:43 +00001291 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001293 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001294 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295
1296 // 128-bit vectors are a special case; they are returned in
1297 // registers and we need to make sure to pick a type the LLVM
1298 // backend will like.
1299 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001300 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001301 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001302
1303 // Always return in register if it fits in a general purpose
1304 // register, or if it is 64 bits and has a single element.
1305 if ((Size == 8 || Size == 16 || Size == 32) ||
1306 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001307 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001308 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001309
John McCall7f416cc2015-09-08 08:05:57 +00001310 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001311 }
1312
1313 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001314 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001315
John McCalla1dee5302010-08-22 10:59:02 +00001316 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001317 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001318 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001319 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001320 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001321 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001322
David Chisnallde3a0692009-08-17 23:08:21 +00001323 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001324 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001325 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001326
Denis Zobnin380b2242016-02-11 11:26:03 +00001327 // Ignore empty structs/unions.
1328 if (isEmptyRecord(getContext(), RetTy, true))
1329 return ABIArgInfo::getIgnore();
1330
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001331 // Small structures which are register sized are generally returned
1332 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001333 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001334 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001335
1336 // As a special-case, if the struct is a "single-element" struct, and
1337 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001338 // floating-point register. (MSVC does not apply this special case.)
1339 // We apply a similar transformation for pointer types to improve the
1340 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001341 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001342 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001343 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001344 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1345
1346 // FIXME: We should be able to narrow this integer in cases with dead
1347 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001348 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001349 }
1350
John McCall7f416cc2015-09-08 08:05:57 +00001351 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001352 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001353
Chris Lattner458b2aa2010-07-29 02:16:43 +00001354 // Treat an enum type as its underlying type.
1355 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1356 RetTy = EnumTy->getDecl()->getIntegerType();
1357
1358 return (RetTy->isPromotableIntegerType() ?
1359 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360}
1361
Eli Friedman7919bea2012-06-05 19:40:46 +00001362static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1363 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1364}
1365
Daniel Dunbared23de32010-09-16 20:42:00 +00001366static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1367 const RecordType *RT = Ty->getAs<RecordType>();
1368 if (!RT)
1369 return 0;
1370 const RecordDecl *RD = RT->getDecl();
1371
1372 // If this is a C++ record, check the bases first.
1373 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001374 for (const auto &I : CXXRD->bases())
1375 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001376 return false;
1377
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001378 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001379 QualType FT = i->getType();
1380
Eli Friedman7919bea2012-06-05 19:40:46 +00001381 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001382 return true;
1383
1384 if (isRecordWithSSEVectorType(Context, FT))
1385 return true;
1386 }
1387
1388 return false;
1389}
1390
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001391unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1392 unsigned Align) const {
1393 // Otherwise, if the alignment is less than or equal to the minimum ABI
1394 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001395 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001396 return 0; // Use default alignment.
1397
1398 // On non-Darwin, the stack type alignment is always 4.
1399 if (!IsDarwinVectorABI) {
1400 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001401 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001402 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001403
Daniel Dunbared23de32010-09-16 20:42:00 +00001404 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001405 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1406 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001407 return 16;
1408
1409 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001410}
1411
Rafael Espindola703c47f2012-10-19 05:04:37 +00001412ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001413 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001414 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001415 if (State.FreeRegs) {
1416 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001417 if (!IsMCUABI)
1418 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001419 }
John McCall7f416cc2015-09-08 08:05:57 +00001420 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001421 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001422
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001423 // Compute the byval alignment.
1424 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1425 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1426 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001427 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001428
1429 // If the stack alignment is less than the type alignment, realign the
1430 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001431 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001432 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1433 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001434}
1435
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001436X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1437 const Type *T = isSingleElementStruct(Ty, getContext());
1438 if (!T)
1439 T = Ty.getTypePtr();
1440
1441 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1442 BuiltinType::Kind K = BT->getKind();
1443 if (K == BuiltinType::Float || K == BuiltinType::Double)
1444 return Float;
1445 }
1446 return Integer;
1447}
1448
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001449bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001450 if (!IsSoftFloatABI) {
1451 Class C = classify(Ty);
1452 if (C == Float)
1453 return false;
1454 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001455
Rafael Espindola077dd592012-10-24 01:58:58 +00001456 unsigned Size = getContext().getTypeSize(Ty);
1457 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001458
1459 if (SizeInRegs == 0)
1460 return false;
1461
Michael Kuperstein68901882015-10-25 08:18:20 +00001462 if (!IsMCUABI) {
1463 if (SizeInRegs > State.FreeRegs) {
1464 State.FreeRegs = 0;
1465 return false;
1466 }
1467 } else {
1468 // The MCU psABI allows passing parameters in-reg even if there are
1469 // earlier parameters that are passed on the stack. Also,
1470 // it does not allow passing >8-byte structs in-register,
1471 // even if there are 3 free registers available.
1472 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1473 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001474 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001475
Reid Kleckner661f35b2014-01-18 01:12:41 +00001476 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001477 return true;
1478}
1479
1480bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1481 bool &InReg,
1482 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001483 // On Windows, aggregates other than HFAs are never passed in registers, and
1484 // they do not consume register slots. Homogenous floating-point aggregates
1485 // (HFAs) have already been dealt with at this point.
1486 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1487 return false;
1488
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001489 NeedsPadding = false;
1490 InReg = !IsMCUABI;
1491
1492 if (!updateFreeRegs(Ty, State))
1493 return false;
1494
1495 if (IsMCUABI)
1496 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001497
Reid Kleckner80944df2014-10-31 22:00:51 +00001498 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001499 State.CC == llvm::CallingConv::X86_VectorCall ||
1500 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001501 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001502 NeedsPadding = true;
1503
Rafael Espindola077dd592012-10-24 01:58:58 +00001504 return false;
1505 }
1506
Rafael Espindola703c47f2012-10-19 05:04:37 +00001507 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001508}
1509
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001510bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1511 if (!updateFreeRegs(Ty, State))
1512 return false;
1513
1514 if (IsMCUABI)
1515 return false;
1516
1517 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001518 State.CC == llvm::CallingConv::X86_VectorCall ||
1519 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001520 if (getContext().getTypeSize(Ty) > 32)
1521 return false;
1522
1523 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1524 Ty->isReferenceType());
1525 }
1526
1527 return true;
1528}
1529
Erich Keane521ed962017-01-05 00:20:51 +00001530ABIArgInfo
1531X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State,
1532 const ABIArgInfo &current) const {
1533 // Assumes vectorCall calling convention.
1534 const Type *Base = nullptr;
1535 uint64_t NumElts = 0;
1536
1537 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
1538 isHomogeneousAggregate(Ty, Base, NumElts)) {
1539 if (State.FreeSSERegs >= NumElts) {
1540 // HVA types get passed directly in registers if there is room.
1541 State.FreeSSERegs -= NumElts;
1542 return getDirectX86Hva();
1543 }
1544 // If there's no room, the HVA gets passed as normal indirect
1545 // structure.
1546 return getIndirectResult(Ty, /*ByVal=*/false, State);
1547 }
1548 return current;
1549}
1550
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001551ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1552 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001553 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001554
Reid Klecknerb1be6832014-11-15 01:41:41 +00001555 Ty = useFirstFieldIfTransparentUnion(Ty);
1556
Reid Kleckner80944df2014-10-31 22:00:51 +00001557 // Check with the C++ ABI first.
1558 const RecordType *RT = Ty->getAs<RecordType>();
1559 if (RT) {
1560 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1561 if (RAA == CGCXXABI::RAA_Indirect) {
1562 return getIndirectResult(Ty, false, State);
1563 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1564 // The field index doesn't matter, we'll fix it up later.
1565 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1566 }
1567 }
1568
1569 // vectorcall adds the concept of a homogenous vector aggregate, similar
Erich Keane521ed962017-01-05 00:20:51 +00001570 // to other targets, regcall uses some of the HVA rules.
Reid Kleckner80944df2014-10-31 22:00:51 +00001571 const Type *Base = nullptr;
1572 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001573 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1574 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001575 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001576
1577 if (State.CC == llvm::CallingConv::X86_RegCall) {
1578 if (State.FreeSSERegs >= NumElts) {
1579 State.FreeSSERegs -= NumElts;
1580 if (Ty->isBuiltinType() || Ty->isVectorType())
1581 return ABIArgInfo::getDirect();
1582 return ABIArgInfo::getExpand();
1583
1584 }
1585 return getIndirectResult(Ty, /*ByVal=*/false, State);
1586 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1587 if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) {
1588 // Actual floating-point types get registers first time through if
1589 // there is registers available
1590 State.FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00001591 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00001592 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
1593 // HVA Types only get registers after everything else has been
1594 // set, so it gets set as indirect for now.
1595 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty));
1596 }
Reid Kleckner80944df2014-10-31 22:00:51 +00001597 }
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 }
1599
1600 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001601 // Structures with flexible arrays are always indirect.
1602 // FIXME: This should not be byval!
1603 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1604 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001605
Reid Kleckner04046052016-05-02 17:41:07 +00001606 // Ignore empty structs/unions on non-Windows.
1607 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001608 return ABIArgInfo::getIgnore();
1609
Rafael Espindolafad28de2012-10-24 01:59:00 +00001610 llvm::LLVMContext &LLVMContext = getVMContext();
1611 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001612 bool NeedsPadding = false;
1613 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001614 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001615 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001616 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001617 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001618 if (InReg)
1619 return ABIArgInfo::getDirectInReg(Result);
1620 else
1621 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001622 }
Craig Topper8a13c412014-05-21 05:09:00 +00001623 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001624
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001625 // Expand small (<= 128-bit) record types when we know that the stack layout
1626 // of those arguments will match the struct. This is important because the
1627 // LLVM backend isn't smart enough to remove byval, which inhibits many
1628 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001629 // Don't do this for the MCU if there are still free integer registers
1630 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001631 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1632 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001633 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001634 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001635 State.CC == llvm::CallingConv::X86_VectorCall ||
1636 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001637 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001638
Reid Kleckner661f35b2014-01-18 01:12:41 +00001639 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001640 }
1641
Chris Lattnerd774ae92010-08-26 20:05:13 +00001642 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001643 // On Darwin, some vectors are passed in memory, we handle this by passing
1644 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001645 if (IsDarwinVectorABI) {
1646 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001647 if ((Size == 8 || Size == 16 || Size == 32) ||
1648 (Size == 64 && VT->getNumElements() == 1))
1649 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1650 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001651 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001652
Chad Rosier651c1832013-03-25 21:00:27 +00001653 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1654 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001655
Chris Lattnerd774ae92010-08-26 20:05:13 +00001656 return ABIArgInfo::getDirect();
1657 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001658
1659
Chris Lattner458b2aa2010-07-29 02:16:43 +00001660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1661 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001662
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001663 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001664
1665 if (Ty->isPromotableIntegerType()) {
1666 if (InReg)
1667 return ABIArgInfo::getExtendInReg();
1668 return ABIArgInfo::getExtend();
1669 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001670
Rafael Espindola703c47f2012-10-19 05:04:37 +00001671 if (InReg)
1672 return ABIArgInfo::getDirectInReg();
1673 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001674}
1675
Erich Keane521ed962017-01-05 00:20:51 +00001676void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1677 bool &UsedInAlloca) const {
1678 // Vectorcall only allows the first 6 parameters to be passed in registers,
1679 // and homogeneous vector aggregates are only put into registers as a second
1680 // priority.
1681 unsigned Count = 0;
1682 CCState ZeroState = State;
1683 ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0;
1684 // HVAs must be done as a second priority for registers, so the deferred
1685 // items are dealt with by going through the pattern a second time.
1686 for (auto &I : FI.arguments()) {
1687 if (Count < VectorcallMaxParamNumAsReg)
1688 I.info = classifyArgumentType(I.type, State);
1689 else
1690 // Parameters after the 6th cannot be passed in registers,
1691 // so pretend there are no registers left for them.
1692 I.info = classifyArgumentType(I.type, ZeroState);
1693 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1694 ++Count;
1695 }
1696 Count = 0;
1697 // Go through the arguments a second time to get HVAs registers if there
1698 // are still some available.
1699 for (auto &I : FI.arguments()) {
1700 if (Count < VectorcallMaxParamNumAsReg)
1701 I.info = reclassifyHvaArgType(I.type, State, I.info);
1702 ++Count;
1703 }
1704}
1705
Rafael Espindolaa6472962012-07-24 00:01:07 +00001706void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001707 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001708 if (IsMCUABI)
1709 State.FreeRegs = 3;
1710 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001711 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001712 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1713 State.FreeRegs = 2;
1714 State.FreeSSERegs = 6;
1715 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001716 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001717 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1718 State.FreeRegs = 5;
1719 State.FreeSSERegs = 8;
1720 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001721 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001722
Reid Kleckner677539d2014-07-10 01:58:55 +00001723 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001724 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001725 } else if (FI.getReturnInfo().isIndirect()) {
1726 // The C++ ABI is not aware of register usage, so we have to check if the
1727 // return value was sret and put it in a register ourselves if appropriate.
1728 if (State.FreeRegs) {
1729 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001730 if (!IsMCUABI)
1731 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001732 }
1733 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001734
Peter Collingbournef7706832014-12-12 23:41:25 +00001735 // The chain argument effectively gives us another free register.
1736 if (FI.isChainCall())
1737 ++State.FreeRegs;
1738
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001739 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001740 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1741 computeVectorCallArgs(FI, State, UsedInAlloca);
1742 } else {
1743 // If not vectorcall, revert to normal behavior.
1744 for (auto &I : FI.arguments()) {
1745 I.info = classifyArgumentType(I.type, State);
1746 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1747 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001748 }
1749
1750 // If we needed to use inalloca for any argument, do a second pass and rewrite
1751 // all the memory arguments to use inalloca.
1752 if (UsedInAlloca)
1753 rewriteWithInAlloca(FI);
1754}
1755
1756void
1757X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001758 CharUnits &StackOffset, ABIArgInfo &Info,
1759 QualType Type) const {
1760 // Arguments are always 4-byte-aligned.
1761 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1762
1763 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001764 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1765 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001766 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001767
John McCall7f416cc2015-09-08 08:05:57 +00001768 // Insert padding bytes to respect alignment.
1769 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001770 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001771 if (StackOffset != FieldEnd) {
1772 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001774 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001775 FrameFields.push_back(Ty);
1776 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001777}
1778
Reid Kleckner852361d2014-07-26 00:12:26 +00001779static bool isArgInAlloca(const ABIArgInfo &Info) {
1780 // Leave ignored and inreg arguments alone.
1781 switch (Info.getKind()) {
1782 case ABIArgInfo::InAlloca:
1783 return true;
1784 case ABIArgInfo::Indirect:
1785 assert(Info.getIndirectByVal());
1786 return true;
1787 case ABIArgInfo::Ignore:
1788 return false;
1789 case ABIArgInfo::Direct:
1790 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001791 if (Info.getInReg())
1792 return false;
1793 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001794 case ABIArgInfo::Expand:
1795 case ABIArgInfo::CoerceAndExpand:
1796 // These are aggregate types which are never passed in registers when
1797 // inalloca is involved.
1798 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001799 }
1800 llvm_unreachable("invalid enum");
1801}
1802
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001803void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1804 assert(IsWin32StructABI && "inalloca only supported on win32");
1805
1806 // Build a packed struct type for all of the arguments in memory.
1807 SmallVector<llvm::Type *, 6> FrameFields;
1808
John McCall7f416cc2015-09-08 08:05:57 +00001809 // The stack alignment is always 4.
1810 CharUnits StackAlign = CharUnits::fromQuantity(4);
1811
1812 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001813 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1814
1815 // Put 'this' into the struct before 'sret', if necessary.
1816 bool IsThisCall =
1817 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1818 ABIArgInfo &Ret = FI.getReturnInfo();
1819 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1820 isArgInAlloca(I->info)) {
1821 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1822 ++I;
1823 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001824
1825 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001826 if (Ret.isIndirect() && !Ret.getInReg()) {
1827 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1828 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001829 // On Windows, the hidden sret parameter is always returned in eax.
1830 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001831 }
1832
1833 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001834 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001835 ++I;
1836
1837 // Put arguments passed in memory into the struct.
1838 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001839 if (isArgInAlloca(I->info))
1840 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001841 }
1842
1843 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001844 /*isPacked=*/true),
1845 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001846}
1847
John McCall7f416cc2015-09-08 08:05:57 +00001848Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1849 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001850
John McCall7f416cc2015-09-08 08:05:57 +00001851 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001852
John McCall7f416cc2015-09-08 08:05:57 +00001853 // x86-32 changes the alignment of certain arguments on the stack.
1854 //
1855 // Just messing with TypeInfo like this works because we never pass
1856 // anything indirectly.
1857 TypeInfo.second = CharUnits::fromQuantity(
1858 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001859
John McCall7f416cc2015-09-08 08:05:57 +00001860 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1861 TypeInfo, CharUnits::fromQuantity(4),
1862 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001863}
1864
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001865bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1866 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1867 assert(Triple.getArch() == llvm::Triple::x86);
1868
1869 switch (Opts.getStructReturnConvention()) {
1870 case CodeGenOptions::SRCK_Default:
1871 break;
1872 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1873 return false;
1874 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1875 return true;
1876 }
1877
Michael Kupersteind749f232015-10-27 07:46:22 +00001878 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001879 return true;
1880
1881 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001882 case llvm::Triple::DragonFly:
1883 case llvm::Triple::FreeBSD:
1884 case llvm::Triple::OpenBSD:
1885 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001886 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001887 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001888 default:
1889 return false;
1890 }
1891}
1892
Eric Christopher162c91c2015-06-05 22:03:00 +00001893void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001894 llvm::GlobalValue *GV,
1895 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001896 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001897 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1898 // Get the LLVM function.
1899 llvm::Function *Fn = cast<llvm::Function>(GV);
1900
1901 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001902 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001903 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001904 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001905 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001906 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1907 llvm::Function *Fn = cast<llvm::Function>(GV);
1908 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1909 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001910 }
1911}
1912
John McCallbeec5a02010-03-06 00:35:14 +00001913bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1914 CodeGen::CodeGenFunction &CGF,
1915 llvm::Value *Address) const {
1916 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001917
Chris Lattnerece04092012-02-07 00:39:47 +00001918 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001919
John McCallbeec5a02010-03-06 00:35:14 +00001920 // 0-7 are the eight integer registers; the order is different
1921 // on Darwin (for EH), but the range is the same.
1922 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001923 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001924
John McCallc8e01702013-04-16 22:48:15 +00001925 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001926 // 12-16 are st(0..4). Not sure why we stop at 4.
1927 // These have size 16, which is sizeof(long double) on
1928 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001929 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001930 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001931
John McCallbeec5a02010-03-06 00:35:14 +00001932 } else {
1933 // 9 is %eflags, which doesn't get a size on Darwin for some
1934 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001935 Builder.CreateAlignedStore(
1936 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1937 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001938
1939 // 11-16 are st(0..5). Not sure why we stop at 5.
1940 // These have size 12, which is sizeof(long double) on
1941 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001942 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001943 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1944 }
John McCallbeec5a02010-03-06 00:35:14 +00001945
1946 return false;
1947}
1948
Chris Lattner0cf24192010-06-28 20:05:43 +00001949//===----------------------------------------------------------------------===//
1950// X86-64 ABI Implementation
1951//===----------------------------------------------------------------------===//
1952
1953
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001955/// The AVX ABI level for X86 targets.
1956enum class X86AVXABILevel {
1957 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001958 AVX,
1959 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001960};
1961
1962/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1963static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1964 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001965 case X86AVXABILevel::AVX512:
1966 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001967 case X86AVXABILevel::AVX:
1968 return 256;
1969 case X86AVXABILevel::None:
1970 return 128;
1971 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001972 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001973}
1974
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001975/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001976class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001977 enum Class {
1978 Integer = 0,
1979 SSE,
1980 SSEUp,
1981 X87,
1982 X87Up,
1983 ComplexX87,
1984 NoClass,
1985 Memory
1986 };
1987
1988 /// merge - Implement the X86_64 ABI merging algorithm.
1989 ///
1990 /// Merge an accumulating classification \arg Accum with a field
1991 /// classification \arg Field.
1992 ///
1993 /// \param Accum - The accumulating classification. This should
1994 /// always be either NoClass or the result of a previous merge
1995 /// call. In addition, this should never be Memory (the caller
1996 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001997 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001998
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001999 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2000 ///
2001 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2002 /// final MEMORY or SSE classes when necessary.
2003 ///
2004 /// \param AggregateSize - The size of the current aggregate in
2005 /// the classification process.
2006 ///
2007 /// \param Lo - The classification for the parts of the type
2008 /// residing in the low word of the containing object.
2009 ///
2010 /// \param Hi - The classification for the parts of the type
2011 /// residing in the higher words of the containing object.
2012 ///
2013 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2014
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002015 /// classify - Determine the x86_64 register classes in which the
2016 /// given type T should be passed.
2017 ///
2018 /// \param Lo - The classification for the parts of the type
2019 /// residing in the low word of the containing object.
2020 ///
2021 /// \param Hi - The classification for the parts of the type
2022 /// residing in the high word of the containing object.
2023 ///
2024 /// \param OffsetBase - The bit offset of this type in the
2025 /// containing object. Some parameters are classified different
2026 /// depending on whether they straddle an eightbyte boundary.
2027 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002028 /// \param isNamedArg - Whether the argument in question is a "named"
2029 /// argument, as used in AMD64-ABI 3.5.7.
2030 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002031 /// If a word is unused its result will be NoClass; if a type should
2032 /// be passed in Memory then at least the classification of \arg Lo
2033 /// will be Memory.
2034 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002035 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002036 ///
2037 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2038 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002039 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2040 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002041
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002042 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002043 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2044 unsigned IROffset, QualType SourceTy,
2045 unsigned SourceOffset) const;
2046 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2047 unsigned IROffset, QualType SourceTy,
2048 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002049
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002050 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002051 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002052 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002053
2054 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002055 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002056 ///
2057 /// \param freeIntRegs - The number of free integer registers remaining
2058 /// available.
2059 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002060
Chris Lattner458b2aa2010-07-29 02:16:43 +00002061 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002062
Erich Keane757d3172016-11-02 18:29:35 +00002063 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2064 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002065 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002066
Erich Keane757d3172016-11-02 18:29:35 +00002067 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2068 unsigned &NeededSSE) const;
2069
2070 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2071 unsigned &NeededSSE) const;
2072
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002073 bool IsIllegalVectorType(QualType Ty) const;
2074
John McCalle0fda732011-04-21 01:20:55 +00002075 /// The 0.98 ABI revision clarified a lot of ambiguities,
2076 /// unfortunately in ways that were not always consistent with
2077 /// certain previous compilers. In particular, platforms which
2078 /// required strict binary compatibility with older versions of GCC
2079 /// may need to exempt themselves.
2080 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002081 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002082 }
2083
David Majnemere2ae2282016-03-04 05:26:16 +00002084 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2085 // compilers require us to classify it as INTEGER.
2086 bool classifyIntegerMMXAsSSE() const {
2087 const llvm::Triple &Triple = getTarget().getTriple();
2088 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2089 return false;
2090 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2091 return false;
2092 return true;
2093 }
2094
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002095 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002096 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2097 // 64-bit hardware.
2098 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002099
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002100public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002101 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002102 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002103 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002104 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002105
John McCalla729c622012-02-17 03:33:10 +00002106 bool isPassedUsingAVXType(QualType type) const {
2107 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002108 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002109 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2110 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002111 if (info.isDirect()) {
2112 llvm::Type *ty = info.getCoerceToType();
2113 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2114 return (vectorTy->getBitWidth() > 128);
2115 }
2116 return false;
2117 }
2118
Craig Topper4f12f102014-03-12 06:41:41 +00002119 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002120
John McCall7f416cc2015-09-08 08:05:57 +00002121 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2122 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002123 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2124 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002125
2126 bool has64BitPointers() const {
2127 return Has64BitPointers;
2128 }
John McCall12f23522016-04-04 18:33:08 +00002129
2130 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2131 ArrayRef<llvm::Type*> scalars,
2132 bool asReturnValue) const override {
2133 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2134 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002135 bool isSwiftErrorInRegister() const override {
2136 return true;
2137 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002138};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002139
Chris Lattner04dc9572010-08-31 16:44:54 +00002140/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002141class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002142public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002143 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002144 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002145 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002146
Craig Topper4f12f102014-03-12 06:41:41 +00002147 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002148
John McCall7f416cc2015-09-08 08:05:57 +00002149 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2150 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002151
2152 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2153 // FIXME: Assumes vectorcall is in use.
2154 return isX86VectorTypeForVectorCall(getContext(), Ty);
2155 }
2156
2157 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2158 uint64_t NumMembers) const override {
2159 // FIXME: Assumes vectorcall is in use.
2160 return isX86VectorCallAggregateSmallEnough(NumMembers);
2161 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002162
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002163 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2164 ArrayRef<llvm::Type *> scalars,
2165 bool asReturnValue) const override {
2166 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2167 }
2168
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002169 bool isSwiftErrorInRegister() const override {
2170 return true;
2171 }
2172
Reid Kleckner11a17192015-10-28 22:29:52 +00002173private:
Erich Keane521ed962017-01-05 00:20:51 +00002174 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2175 bool IsVectorCall, bool IsRegCall) const;
2176 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2177 const ABIArgInfo &current) const;
2178 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2179 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002180
Erich Keane521ed962017-01-05 00:20:51 +00002181 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002182};
2183
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002184class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2185public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002186 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002187 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002188
John McCalla729c622012-02-17 03:33:10 +00002189 const X86_64ABIInfo &getABIInfo() const {
2190 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2191 }
2192
Craig Topper4f12f102014-03-12 06:41:41 +00002193 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002194 return 7;
2195 }
2196
2197 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002198 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002199 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002200
John McCall943fae92010-05-27 06:19:26 +00002201 // 0-15 are the 16 integer registers.
2202 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002203 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002204 return false;
2205 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002206
Jay Foad7c57be32011-07-11 09:56:20 +00002207 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002208 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002209 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002210 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2211 }
2212
John McCalla729c622012-02-17 03:33:10 +00002213 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002214 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002215 // The default CC on x86-64 sets %al to the number of SSA
2216 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002217 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002218 // that when AVX types are involved: the ABI explicitly states it is
2219 // undefined, and it doesn't work in practice because of how the ABI
2220 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002221 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002222 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002223 for (CallArgList::const_iterator
2224 it = args.begin(), ie = args.end(); it != ie; ++it) {
2225 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2226 HasAVXType = true;
2227 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002228 }
2229 }
John McCalla729c622012-02-17 03:33:10 +00002230
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002231 if (!HasAVXType)
2232 return true;
2233 }
John McCallcbc038a2011-09-21 08:08:30 +00002234
John McCalla729c622012-02-17 03:33:10 +00002235 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002236 }
2237
Craig Topper4f12f102014-03-12 06:41:41 +00002238 llvm::Constant *
2239 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002240 unsigned Sig;
2241 if (getABIInfo().has64BitPointers())
2242 Sig = (0xeb << 0) | // jmp rel8
2243 (0x0a << 8) | // .+0x0c
2244 ('F' << 16) |
2245 ('T' << 24);
2246 else
2247 Sig = (0xeb << 0) | // jmp rel8
2248 (0x06 << 8) | // .+0x08
2249 ('F' << 16) |
2250 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002251 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2252 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002253
2254 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2255 CodeGen::CodeGenModule &CGM) const override {
2256 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2257 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2258 llvm::Function *Fn = cast<llvm::Function>(GV);
2259 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2260 }
2261 }
2262 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002263};
2264
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002265class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2266public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002267 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2268 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002269
2270 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002271 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002272 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002273 // If the argument contains a space, enclose it in quotes.
2274 if (Lib.find(" ") != StringRef::npos)
2275 Opt += "\"" + Lib.str() + "\"";
2276 else
2277 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002278 }
2279};
2280
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002281static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002282 // If the argument does not end in .lib, automatically add the suffix.
2283 // If the argument contains a space, enclose it in quotes.
2284 // This matches the behavior of MSVC.
2285 bool Quote = (Lib.find(" ") != StringRef::npos);
2286 std::string ArgStr = Quote ? "\"" : "";
2287 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002288 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002289 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002290 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002291 return ArgStr;
2292}
2293
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002294class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2295public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002296 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002297 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2298 unsigned NumRegisterParameters)
2299 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002300 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002301
Eric Christopher162c91c2015-06-05 22:03:00 +00002302 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002303 CodeGen::CodeGenModule &CGM) const override;
2304
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002305 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002306 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002307 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002308 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002309 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002310
2311 void getDetectMismatchOption(llvm::StringRef Name,
2312 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002313 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002314 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002315 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002316};
2317
Hans Wennborg77dc2362015-01-20 19:45:50 +00002318static void addStackProbeSizeTargetAttribute(const Decl *D,
2319 llvm::GlobalValue *GV,
2320 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002321 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002322 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2323 llvm::Function *Fn = cast<llvm::Function>(GV);
2324
Eric Christopher7565e0d2015-05-29 23:09:49 +00002325 Fn->addFnAttr("stack-probe-size",
2326 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002327 }
2328 }
2329}
2330
Eric Christopher162c91c2015-06-05 22:03:00 +00002331void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002332 llvm::GlobalValue *GV,
2333 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002334 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002335
2336 addStackProbeSizeTargetAttribute(D, GV, CGM);
2337}
2338
Chris Lattner04dc9572010-08-31 16:44:54 +00002339class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2340public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002341 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2342 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002343 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002344
Eric Christopher162c91c2015-06-05 22:03:00 +00002345 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002346 CodeGen::CodeGenModule &CGM) const override;
2347
Craig Topper4f12f102014-03-12 06:41:41 +00002348 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002349 return 7;
2350 }
2351
2352 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002353 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002354 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002355
Chris Lattner04dc9572010-08-31 16:44:54 +00002356 // 0-15 are the 16 integer registers.
2357 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002358 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002359 return false;
2360 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002361
2362 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002363 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002364 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002365 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002366 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002367
2368 void getDetectMismatchOption(llvm::StringRef Name,
2369 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002370 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002371 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002372 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002373};
2374
Eric Christopher162c91c2015-06-05 22:03:00 +00002375void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002376 llvm::GlobalValue *GV,
2377 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002378 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002379
Alexey Bataevd51e9932016-01-15 04:06:31 +00002380 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2381 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2382 llvm::Function *Fn = cast<llvm::Function>(GV);
2383 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2384 }
2385 }
2386
Hans Wennborg77dc2362015-01-20 19:45:50 +00002387 addStackProbeSizeTargetAttribute(D, GV, CGM);
2388}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002389}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002390
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002391void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2392 Class &Hi) const {
2393 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2394 //
2395 // (a) If one of the classes is Memory, the whole argument is passed in
2396 // memory.
2397 //
2398 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2399 // memory.
2400 //
2401 // (c) If the size of the aggregate exceeds two eightbytes and the first
2402 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2403 // argument is passed in memory. NOTE: This is necessary to keep the
2404 // ABI working for processors that don't support the __m256 type.
2405 //
2406 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2407 //
2408 // Some of these are enforced by the merging logic. Others can arise
2409 // only with unions; for example:
2410 // union { _Complex double; unsigned; }
2411 //
2412 // Note that clauses (b) and (c) were added in 0.98.
2413 //
2414 if (Hi == Memory)
2415 Lo = Memory;
2416 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2417 Lo = Memory;
2418 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2419 Lo = Memory;
2420 if (Hi == SSEUp && Lo != SSE)
2421 Hi = SSE;
2422}
2423
Chris Lattnerd776fb12010-06-28 21:43:59 +00002424X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2426 // classified recursively so that always two fields are
2427 // considered. The resulting class is calculated according to
2428 // the classes of the fields in the eightbyte:
2429 //
2430 // (a) If both classes are equal, this is the resulting class.
2431 //
2432 // (b) If one of the classes is NO_CLASS, the resulting class is
2433 // the other class.
2434 //
2435 // (c) If one of the classes is MEMORY, the result is the MEMORY
2436 // class.
2437 //
2438 // (d) If one of the classes is INTEGER, the result is the
2439 // INTEGER.
2440 //
2441 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2442 // MEMORY is used as class.
2443 //
2444 // (f) Otherwise class SSE is used.
2445
2446 // Accum should never be memory (we should have returned) or
2447 // ComplexX87 (because this cannot be passed in a structure).
2448 assert((Accum != Memory && Accum != ComplexX87) &&
2449 "Invalid accumulated classification during merge.");
2450 if (Accum == Field || Field == NoClass)
2451 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002452 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002453 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002454 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002455 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002456 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002458 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2459 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002460 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002461 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002462}
2463
Chris Lattner5c740f12010-06-30 19:14:05 +00002464void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002465 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002466 // FIXME: This code can be simplified by introducing a simple value class for
2467 // Class pairs with appropriate constructor methods for the various
2468 // situations.
2469
2470 // FIXME: Some of the split computations are wrong; unaligned vectors
2471 // shouldn't be passed in registers for example, so there is no chance they
2472 // can straddle an eightbyte. Verify & simplify.
2473
2474 Lo = Hi = NoClass;
2475
2476 Class &Current = OffsetBase < 64 ? Lo : Hi;
2477 Current = Memory;
2478
John McCall9dd450b2009-09-21 23:43:11 +00002479 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002480 BuiltinType::Kind k = BT->getKind();
2481
2482 if (k == BuiltinType::Void) {
2483 Current = NoClass;
2484 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2485 Lo = Integer;
2486 Hi = Integer;
2487 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2488 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002489 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002490 Current = SSE;
2491 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002492 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002493 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002494 Lo = SSE;
2495 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002496 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002497 Lo = X87;
2498 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002499 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002500 Current = SSE;
2501 } else
2502 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002503 }
2504 // FIXME: _Decimal32 and _Decimal64 are SSE.
2505 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002506 return;
2507 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002508
Chris Lattnerd776fb12010-06-28 21:43:59 +00002509 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002511 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002512 return;
2513 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002514
Chris Lattnerd776fb12010-06-28 21:43:59 +00002515 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002517 return;
2518 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002519
Chris Lattnerd776fb12010-06-28 21:43:59 +00002520 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002521 if (Ty->isMemberFunctionPointerType()) {
2522 if (Has64BitPointers) {
2523 // If Has64BitPointers, this is an {i64, i64}, so classify both
2524 // Lo and Hi now.
2525 Lo = Hi = Integer;
2526 } else {
2527 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2528 // straddles an eightbyte boundary, Hi should be classified as well.
2529 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2530 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2531 if (EB_FuncPtr != EB_ThisAdj) {
2532 Lo = Hi = Integer;
2533 } else {
2534 Current = Integer;
2535 }
2536 }
2537 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002538 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002539 }
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 VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002544 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002545 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2546 // gcc passes the following as integer:
2547 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2548 // 2 bytes - <2 x char>, <1 x short>
2549 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002550 Current = Integer;
2551
2552 // If this type crosses an eightbyte boundary, it should be
2553 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002554 uint64_t EB_Lo = (OffsetBase) / 64;
2555 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2556 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 Hi = Lo;
2558 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002559 QualType ElementType = VT->getElementType();
2560
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002561 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002562 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002563 return;
2564
David Majnemere2ae2282016-03-04 05:26:16 +00002565 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2566 // pass them as integer. For platforms where clang is the de facto
2567 // platform compiler, we must continue to use integer.
2568 if (!classifyIntegerMMXAsSSE() &&
2569 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2570 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2571 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2572 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573 Current = Integer;
2574 else
2575 Current = SSE;
2576
2577 // If this type crosses an eightbyte boundary, it should be
2578 // split.
2579 if (OffsetBase && OffsetBase != 64)
2580 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002581 } else if (Size == 128 ||
2582 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002583 // Arguments of 256-bits are split into four eightbyte chunks. The
2584 // least significant one belongs to class SSE and all the others to class
2585 // SSEUP. The original Lo and Hi design considers that types can't be
2586 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2587 // This design isn't correct for 256-bits, but since there're no cases
2588 // where the upper parts would need to be inspected, avoid adding
2589 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002590 //
2591 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2592 // registers if they are "named", i.e. not part of the "..." of a
2593 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002594 //
2595 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2596 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002597 Lo = SSE;
2598 Hi = SSEUp;
2599 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002600 return;
2601 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002602
Chris Lattnerd776fb12010-06-28 21:43:59 +00002603 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002604 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605
Chris Lattner2b037972010-07-29 02:01:43 +00002606 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002607 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608 if (Size <= 64)
2609 Current = Integer;
2610 else if (Size <= 128)
2611 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002612 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002614 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002616 } else if (ET == getContext().LongDoubleTy) {
2617 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002618 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002619 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002620 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002621 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002622 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002623 Lo = Hi = SSE;
2624 else
2625 llvm_unreachable("unexpected long double representation!");
2626 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627
2628 // If this complex type crosses an eightbyte boundary then it
2629 // should be split.
2630 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002631 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 if (Hi == NoClass && EB_Real != EB_Imag)
2633 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002634
Chris Lattnerd776fb12010-06-28 21:43:59 +00002635 return;
2636 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002637
Chris Lattner2b037972010-07-29 02:01:43 +00002638 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 // Arrays are treated like structures.
2640
Chris Lattner2b037972010-07-29 02:01:43 +00002641 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642
2643 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002644 // than eight eightbytes, ..., it has class MEMORY.
2645 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646 return;
2647
2648 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2649 // fields, it has class MEMORY.
2650 //
2651 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002652 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 return;
2654
2655 // Otherwise implement simplified merge. We could be smarter about
2656 // this, but it isn't worth it and would be harder to verify.
2657 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002658 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002659 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002660
2661 // The only case a 256-bit wide vector could be used is when the array
2662 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2663 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002664 //
2665 if (Size > 128 &&
2666 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002667 return;
2668
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002669 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2670 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002671 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672 Lo = merge(Lo, FieldLo);
2673 Hi = merge(Hi, FieldHi);
2674 if (Lo == Memory || Hi == Memory)
2675 break;
2676 }
2677
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002678 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002680 return;
2681 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002682
Chris Lattnerd776fb12010-06-28 21:43:59 +00002683 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002684 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685
2686 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002687 // than eight eightbytes, ..., it has class MEMORY.
2688 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002689 return;
2690
Anders Carlsson20759ad2009-09-16 15:53:40 +00002691 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2692 // copy constructor or a non-trivial destructor, it is passed by invisible
2693 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002694 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002695 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002696
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697 const RecordDecl *RD = RT->getDecl();
2698
2699 // Assume variable sized types are passed in memory.
2700 if (RD->hasFlexibleArrayMember())
2701 return;
2702
Chris Lattner2b037972010-07-29 02:01:43 +00002703 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704
2705 // Reset Lo class, this will be recomputed.
2706 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002707
2708 // If this is a C++ record, classify the bases first.
2709 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002710 for (const auto &I : CXXRD->bases()) {
2711 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002712 "Unexpected base class!");
2713 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002714 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002715
2716 // Classify this field.
2717 //
2718 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2719 // single eightbyte, each is classified separately. Each eightbyte gets
2720 // initialized to class NO_CLASS.
2721 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002722 uint64_t Offset =
2723 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002724 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002725 Lo = merge(Lo, FieldLo);
2726 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002727 if (Lo == Memory || Hi == Memory) {
2728 postMerge(Size, Lo, Hi);
2729 return;
2730 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002731 }
2732 }
2733
2734 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002736 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002737 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2739 bool BitField = i->isBitField();
2740
David Majnemerb439dfe2016-08-15 07:20:40 +00002741 // Ignore padding bit-fields.
2742 if (BitField && i->isUnnamedBitfield())
2743 continue;
2744
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002745 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2746 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002748 // The only case a 256-bit wide vector could be used is when the struct
2749 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2750 // to work for sizes wider than 128, early check and fallback to memory.
2751 //
David Majnemerb229cb02016-08-15 06:39:18 +00002752 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2753 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002754 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002755 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002756 return;
2757 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002758 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002759 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002760 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002761 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002762 return;
2763 }
2764
2765 // Classify this field.
2766 //
2767 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2768 // exceeds a single eightbyte, each is classified
2769 // separately. Each eightbyte gets initialized to class
2770 // NO_CLASS.
2771 Class FieldLo, FieldHi;
2772
2773 // Bit-fields require special handling, they do not force the
2774 // structure to be passed in memory even if unaligned, and
2775 // therefore they can straddle an eightbyte.
2776 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002777 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002778 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002779 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002780
2781 uint64_t EB_Lo = Offset / 64;
2782 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002783
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002784 if (EB_Lo) {
2785 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2786 FieldLo = NoClass;
2787 FieldHi = Integer;
2788 } else {
2789 FieldLo = Integer;
2790 FieldHi = EB_Hi ? Integer : NoClass;
2791 }
2792 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002793 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 Lo = merge(Lo, FieldLo);
2795 Hi = merge(Hi, FieldHi);
2796 if (Lo == Memory || Hi == Memory)
2797 break;
2798 }
2799
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002800 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002801 }
2802}
2803
Chris Lattner22a931e2010-06-29 06:01:59 +00002804ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002805 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2806 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002807 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002808 // Treat an enum type as its underlying type.
2809 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2810 Ty = EnumTy->getDecl()->getIntegerType();
2811
2812 return (Ty->isPromotableIntegerType() ?
2813 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2814 }
2815
John McCall7f416cc2015-09-08 08:05:57 +00002816 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002817}
2818
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002819bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2820 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2821 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002822 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002823 if (Size <= 64 || Size > LargestVector)
2824 return true;
2825 }
2826
2827 return false;
2828}
2829
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002830ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2831 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002832 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2833 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002834 //
2835 // This assumption is optimistic, as there could be free registers available
2836 // when we need to pass this argument in memory, and LLVM could try to pass
2837 // the argument in the free register. This does not seem to happen currently,
2838 // but this code would be much safer if we could mark the argument with
2839 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002840 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002841 // Treat an enum type as its underlying type.
2842 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2843 Ty = EnumTy->getDecl()->getIntegerType();
2844
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002845 return (Ty->isPromotableIntegerType() ?
2846 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002847 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002848
Mark Lacey3825e832013-10-06 01:33:34 +00002849 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002850 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002851
Chris Lattner44c2b902011-05-22 23:21:23 +00002852 // Compute the byval alignment. We specify the alignment of the byval in all
2853 // cases so that the mid-level optimizer knows the alignment of the byval.
2854 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002855
2856 // Attempt to avoid passing indirect results using byval when possible. This
2857 // is important for good codegen.
2858 //
2859 // We do this by coercing the value into a scalar type which the backend can
2860 // handle naturally (i.e., without using byval).
2861 //
2862 // For simplicity, we currently only do this when we have exhausted all of the
2863 // free integer registers. Doing this when there are free integer registers
2864 // would require more care, as we would have to ensure that the coerced value
2865 // did not claim the unused register. That would require either reording the
2866 // arguments to the function (so that any subsequent inreg values came first),
2867 // or only doing this optimization when there were no following arguments that
2868 // might be inreg.
2869 //
2870 // We currently expect it to be rare (particularly in well written code) for
2871 // arguments to be passed on the stack when there are still free integer
2872 // registers available (this would typically imply large structs being passed
2873 // by value), so this seems like a fair tradeoff for now.
2874 //
2875 // We can revisit this if the backend grows support for 'onstack' parameter
2876 // attributes. See PR12193.
2877 if (freeIntRegs == 0) {
2878 uint64_t Size = getContext().getTypeSize(Ty);
2879
2880 // If this type fits in an eightbyte, coerce it into the matching integral
2881 // type, which will end up on the stack (with alignment 8).
2882 if (Align == 8 && Size <= 64)
2883 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2884 Size));
2885 }
2886
John McCall7f416cc2015-09-08 08:05:57 +00002887 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002888}
2889
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002890/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2891/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002892llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002893 // Wrapper structs/arrays that only contain vectors are passed just like
2894 // vectors; strip them off if present.
2895 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2896 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002897
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002898 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002899 if (isa<llvm::VectorType>(IRType) ||
2900 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002901 return IRType;
2902
2903 // We couldn't find the preferred IR vector type for 'Ty'.
2904 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002905 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002906
2907 // Return a LLVM IR vector type based on the size of 'Ty'.
2908 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2909 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002910}
2911
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002912/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2913/// is known to either be off the end of the specified type or being in
2914/// alignment padding. The user type specified is known to be at most 128 bits
2915/// in size, and have passed through X86_64ABIInfo::classify with a successful
2916/// classification that put one of the two halves in the INTEGER class.
2917///
2918/// It is conservatively correct to return false.
2919static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2920 unsigned EndBit, ASTContext &Context) {
2921 // If the bytes being queried are off the end of the type, there is no user
2922 // data hiding here. This handles analysis of builtins, vectors and other
2923 // types that don't contain interesting padding.
2924 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2925 if (TySize <= StartBit)
2926 return true;
2927
Chris Lattner98076a22010-07-29 07:43:55 +00002928 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2929 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2930 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2931
2932 // Check each element to see if the element overlaps with the queried range.
2933 for (unsigned i = 0; i != NumElts; ++i) {
2934 // If the element is after the span we care about, then we're done..
2935 unsigned EltOffset = i*EltSize;
2936 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002937
Chris Lattner98076a22010-07-29 07:43:55 +00002938 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2939 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2940 EndBit-EltOffset, Context))
2941 return false;
2942 }
2943 // If it overlaps no elements, then it is safe to process as padding.
2944 return true;
2945 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002946
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002947 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2948 const RecordDecl *RD = RT->getDecl();
2949 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002950
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002951 // If this is a C++ record, check the bases first.
2952 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002953 for (const auto &I : CXXRD->bases()) {
2954 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002955 "Unexpected base class!");
2956 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002957 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002958
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002959 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002960 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002961 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002962
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002963 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002964 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002965 EndBit-BaseOffset, Context))
2966 return false;
2967 }
2968 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002969
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002970 // Verify that no field has data that overlaps the region of interest. Yes
2971 // this could be sped up a lot by being smarter about queried fields,
2972 // however we're only looking at structs up to 16 bytes, so we don't care
2973 // much.
2974 unsigned idx = 0;
2975 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2976 i != e; ++i, ++idx) {
2977 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002978
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002979 // If we found a field after the region we care about, then we're done.
2980 if (FieldOffset >= EndBit) break;
2981
2982 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2983 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2984 Context))
2985 return false;
2986 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002987
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002988 // If nothing in this record overlapped the area of interest, then we're
2989 // clean.
2990 return true;
2991 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002992
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002993 return false;
2994}
2995
Chris Lattnere556a712010-07-29 18:39:32 +00002996/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2997/// float member at the specified offset. For example, {int,{float}} has a
2998/// float at offset 4. It is conservatively correct for this routine to return
2999/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003000static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003001 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003002 // Base case if we find a float.
3003 if (IROffset == 0 && IRType->isFloatTy())
3004 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003005
Chris Lattnere556a712010-07-29 18:39:32 +00003006 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003007 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003008 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3009 unsigned Elt = SL->getElementContainingOffset(IROffset);
3010 IROffset -= SL->getElementOffset(Elt);
3011 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3012 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003013
Chris Lattnere556a712010-07-29 18:39:32 +00003014 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003015 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3016 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003017 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3018 IROffset -= IROffset/EltSize*EltSize;
3019 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3020 }
3021
3022 return false;
3023}
3024
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003025
3026/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3027/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003028llvm::Type *X86_64ABIInfo::
3029GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003030 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003031 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003032 // pass as float if the last 4 bytes is just padding. This happens for
3033 // structs that contain 3 floats.
3034 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3035 SourceOffset*8+64, getContext()))
3036 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003037
Chris Lattnere556a712010-07-29 18:39:32 +00003038 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3039 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3040 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003041 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3042 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003043 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003044
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003045 return llvm::Type::getDoubleTy(getVMContext());
3046}
3047
3048
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003049/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3050/// an 8-byte GPR. This means that we either have a scalar or we are talking
3051/// about the high or low part of an up-to-16-byte struct. This routine picks
3052/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003053/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3054/// etc).
3055///
3056/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3057/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3058/// the 8-byte value references. PrefType may be null.
3059///
Alp Toker9907f082014-07-09 14:06:35 +00003060/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003061/// an offset into this that we're processing (which is always either 0 or 8).
3062///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003063llvm::Type *X86_64ABIInfo::
3064GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003065 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003066 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3067 // returning an 8-byte unit starting with it. See if we can safely use it.
3068 if (IROffset == 0) {
3069 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003070 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3071 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003072 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003073
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003074 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3075 // goodness in the source type is just tail padding. This is allowed to
3076 // kick in for struct {double,int} on the int, but not on
3077 // struct{double,int,int} because we wouldn't return the second int. We
3078 // have to do this analysis on the source type because we can't depend on
3079 // unions being lowered a specific way etc.
3080 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003081 IRType->isIntegerTy(32) ||
3082 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3083 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3084 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003085
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003086 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3087 SourceOffset*8+64, getContext()))
3088 return IRType;
3089 }
3090 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003091
Chris Lattner2192fe52011-07-18 04:24:23 +00003092 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003093 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003094 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003095 if (IROffset < SL->getSizeInBytes()) {
3096 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3097 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003098
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003099 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3100 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003101 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003102 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003103
Chris Lattner2192fe52011-07-18 04:24:23 +00003104 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003105 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003106 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003107 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003108 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3109 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003110 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003111
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003112 // Okay, we don't have any better idea of what to pass, so we pass this in an
3113 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003114 unsigned TySizeInBytes =
3115 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003116
Chris Lattner3f763422010-07-29 17:34:39 +00003117 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003118
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003119 // It is always safe to classify this as an integer type up to i64 that
3120 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003121 return llvm::IntegerType::get(getVMContext(),
3122 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003123}
3124
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003125
3126/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3127/// be used as elements of a two register pair to pass or return, return a
3128/// first class aggregate to represent them. For example, if the low part of
3129/// a by-value argument should be passed as i32* and the high part as float,
3130/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003131static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003132GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003133 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003134 // In order to correctly satisfy the ABI, we need to the high part to start
3135 // at offset 8. If the high and low parts we inferred are both 4-byte types
3136 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3137 // the second element at offset 8. Check for this:
3138 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3139 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003140 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003141 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003142
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003143 // To handle this, we have to increase the size of the low part so that the
3144 // second element will start at an 8 byte offset. We can't increase the size
3145 // of the second element because it might make us access off the end of the
3146 // struct.
3147 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003148 // There are usually two sorts of types the ABI generation code can produce
3149 // for the low part of a pair that aren't 8 bytes in size: float or
3150 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3151 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003152 // Promote these to a larger type.
3153 if (Lo->isFloatTy())
3154 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3155 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003156 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3157 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003158 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3159 }
3160 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003161
Reid Kleckneree7cf842014-12-01 22:02:27 +00003162 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003163
3164
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003165 // Verify that the second element is at an 8-byte offset.
3166 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3167 "Invalid x86-64 argument pair!");
3168 return Result;
3169}
3170
Chris Lattner31faff52010-07-28 23:06:14 +00003171ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003172classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003173 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3174 // classification algorithm.
3175 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003176 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003177
3178 // Check some invariants.
3179 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003180 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3181
Craig Topper8a13c412014-05-21 05:09:00 +00003182 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003183 switch (Lo) {
3184 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003185 if (Hi == NoClass)
3186 return ABIArgInfo::getIgnore();
3187 // If the low part is just padding, it takes no register, leave ResType
3188 // null.
3189 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3190 "Unknown missing lo part");
3191 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003192
3193 case SSEUp:
3194 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003195 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003196
3197 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3198 // hidden argument.
3199 case Memory:
3200 return getIndirectReturnResult(RetTy);
3201
3202 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3203 // available register of the sequence %rax, %rdx is used.
3204 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003205 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003206
Chris Lattner1f3a0632010-07-29 21:42:50 +00003207 // If we have a sign or zero extended integer, make sure to return Extend
3208 // so that the parameter gets the right LLVM IR attributes.
3209 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3210 // Treat an enum type as its underlying type.
3211 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3212 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003213
Chris Lattner1f3a0632010-07-29 21:42:50 +00003214 if (RetTy->isIntegralOrEnumerationType() &&
3215 RetTy->isPromotableIntegerType())
3216 return ABIArgInfo::getExtend();
3217 }
Chris Lattner31faff52010-07-28 23:06:14 +00003218 break;
3219
3220 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3221 // available SSE register of the sequence %xmm0, %xmm1 is used.
3222 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003223 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003224 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003225
3226 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3227 // returned on the X87 stack in %st0 as 80-bit x87 number.
3228 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003229 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003230 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003231
3232 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3233 // part of the value is returned in %st0 and the imaginary part in
3234 // %st1.
3235 case ComplexX87:
3236 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003237 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003238 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003239 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003240 break;
3241 }
3242
Craig Topper8a13c412014-05-21 05:09:00 +00003243 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003244 switch (Hi) {
3245 // Memory was handled previously and X87 should
3246 // never occur as a hi class.
3247 case Memory:
3248 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003249 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003250
3251 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003252 case NoClass:
3253 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003254
Chris Lattner52b3c132010-09-01 00:20:33 +00003255 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003256 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003257 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3258 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003259 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003260 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003261 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003262 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3263 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003264 break;
3265
3266 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003267 // is passed in the next available eightbyte chunk if the last used
3268 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003269 //
Chris Lattner57540c52011-04-15 05:22:18 +00003270 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003271 case SSEUp:
3272 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003273 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003274 break;
3275
3276 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3277 // returned together with the previous X87 value in %st0.
3278 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003279 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003280 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003281 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003282 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003283 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003284 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003285 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3286 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003287 }
Chris Lattner31faff52010-07-28 23:06:14 +00003288 break;
3289 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003290
Chris Lattner52b3c132010-09-01 00:20:33 +00003291 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003292 // known to pass in the high eightbyte of the result. We do this by forming a
3293 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003294 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003295 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003296
Chris Lattner1f3a0632010-07-29 21:42:50 +00003297 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003298}
3299
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003300ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003301 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3302 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003303 const
3304{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003305 Ty = useFirstFieldIfTransparentUnion(Ty);
3306
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003307 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003308 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003309
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003310 // Check some invariants.
3311 // FIXME: Enforce these by construction.
3312 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003313 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3314
3315 neededInt = 0;
3316 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003317 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003318 switch (Lo) {
3319 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003320 if (Hi == NoClass)
3321 return ABIArgInfo::getIgnore();
3322 // If the low part is just padding, it takes no register, leave ResType
3323 // null.
3324 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3325 "Unknown missing lo part");
3326 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003327
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003328 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3329 // on the stack.
3330 case Memory:
3331
3332 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3333 // COMPLEX_X87, it is passed in memory.
3334 case X87:
3335 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003336 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003337 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003338 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003339
3340 case SSEUp:
3341 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003342 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003343
3344 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3345 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3346 // and %r9 is used.
3347 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003348 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003349
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003350 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003351 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003352
3353 // If we have a sign or zero extended integer, make sure to return Extend
3354 // so that the parameter gets the right LLVM IR attributes.
3355 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3356 // Treat an enum type as its underlying type.
3357 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3358 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003359
Chris Lattner1f3a0632010-07-29 21:42:50 +00003360 if (Ty->isIntegralOrEnumerationType() &&
3361 Ty->isPromotableIntegerType())
3362 return ABIArgInfo::getExtend();
3363 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003364
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003365 break;
3366
3367 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3368 // available SSE register is used, the registers are taken in the
3369 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003370 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003371 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003372 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003373 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374 break;
3375 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003376 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377
Craig Topper8a13c412014-05-21 05:09:00 +00003378 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003379 switch (Hi) {
3380 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003381 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 // which is passed in memory.
3383 case Memory:
3384 case X87:
3385 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003386 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003387
3388 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003389
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003390 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003391 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003392 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003393 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003394
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003395 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3396 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003397 break;
3398
3399 // X87Up generally doesn't occur here (long double is passed in
3400 // memory), except in situations involving unions.
3401 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003402 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003403 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003404
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003405 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3406 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003407
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003408 ++neededSSE;
3409 break;
3410
3411 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3412 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003413 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003414 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003415 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003416 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417 break;
3418 }
3419
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003420 // If a high part was specified, merge it together with the low part. It is
3421 // known to pass in the high eightbyte of the result. We do this by forming a
3422 // first class struct aggregate with the high and low part: {low, high}
3423 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003424 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003425
Chris Lattner1f3a0632010-07-29 21:42:50 +00003426 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003427}
3428
Erich Keane757d3172016-11-02 18:29:35 +00003429ABIArgInfo
3430X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3431 unsigned &NeededSSE) const {
3432 auto RT = Ty->getAs<RecordType>();
3433 assert(RT && "classifyRegCallStructType only valid with struct types");
3434
3435 if (RT->getDecl()->hasFlexibleArrayMember())
3436 return getIndirectReturnResult(Ty);
3437
3438 // Sum up bases
3439 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3440 if (CXXRD->isDynamicClass()) {
3441 NeededInt = NeededSSE = 0;
3442 return getIndirectReturnResult(Ty);
3443 }
3444
3445 for (const auto &I : CXXRD->bases())
3446 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3447 .isIndirect()) {
3448 NeededInt = NeededSSE = 0;
3449 return getIndirectReturnResult(Ty);
3450 }
3451 }
3452
3453 // Sum up members
3454 for (const auto *FD : RT->getDecl()->fields()) {
3455 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3456 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3457 .isIndirect()) {
3458 NeededInt = NeededSSE = 0;
3459 return getIndirectReturnResult(Ty);
3460 }
3461 } else {
3462 unsigned LocalNeededInt, LocalNeededSSE;
3463 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3464 LocalNeededSSE, true)
3465 .isIndirect()) {
3466 NeededInt = NeededSSE = 0;
3467 return getIndirectReturnResult(Ty);
3468 }
3469 NeededInt += LocalNeededInt;
3470 NeededSSE += LocalNeededSSE;
3471 }
3472 }
3473
3474 return ABIArgInfo::getDirect();
3475}
3476
3477ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3478 unsigned &NeededInt,
3479 unsigned &NeededSSE) const {
3480
3481 NeededInt = 0;
3482 NeededSSE = 0;
3483
3484 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3485}
3486
Chris Lattner22326a12010-07-29 02:31:05 +00003487void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003488
Erich Keane757d3172016-11-02 18:29:35 +00003489 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003490
3491 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003492 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3493 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3494 unsigned NeededInt, NeededSSE;
3495
3496 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3497 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3498 FI.getReturnInfo() =
3499 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3500 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3501 FreeIntRegs -= NeededInt;
3502 FreeSSERegs -= NeededSSE;
3503 } else {
3504 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3505 }
3506 } else if (!getCXXABI().classifyReturnType(FI))
3507 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003508
3509 // If the return value is indirect, then the hidden argument is consuming one
3510 // integer register.
3511 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003512 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003513
Peter Collingbournef7706832014-12-12 23:41:25 +00003514 // The chain argument effectively gives us another free register.
3515 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003516 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003517
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003518 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003519 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3520 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003521 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003522 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003523 it != ie; ++it, ++ArgNo) {
3524 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003525
Erich Keane757d3172016-11-02 18:29:35 +00003526 if (IsRegCall && it->type->isStructureOrClassType())
3527 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3528 else
3529 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3530 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003531
3532 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3533 // eightbyte of an argument, the whole argument is passed on the
3534 // stack. If registers have already been assigned for some
3535 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003536 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3537 FreeIntRegs -= NeededInt;
3538 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003539 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003540 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003541 }
3542 }
3543}
3544
John McCall7f416cc2015-09-08 08:05:57 +00003545static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3546 Address VAListAddr, QualType Ty) {
3547 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3548 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003549 llvm::Value *overflow_arg_area =
3550 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3551
3552 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3553 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003554 // It isn't stated explicitly in the standard, but in practice we use
3555 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003556 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3557 if (Align > CharUnits::fromQuantity(8)) {
3558 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3559 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003560 }
3561
3562 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003563 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003564 llvm::Value *Res =
3565 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003566 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567
3568 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3569 // l->overflow_arg_area + sizeof(type).
3570 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3571 // an 8 byte boundary.
3572
3573 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003574 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003575 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003576 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3577 "overflow_arg_area.next");
3578 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3579
3580 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003581 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003582}
3583
John McCall7f416cc2015-09-08 08:05:57 +00003584Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3585 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003586 // Assume that va_list type is correct; should be pointer to LLVM type:
3587 // struct {
3588 // i32 gp_offset;
3589 // i32 fp_offset;
3590 // i8* overflow_arg_area;
3591 // i8* reg_save_area;
3592 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003593 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003594
John McCall7f416cc2015-09-08 08:05:57 +00003595 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003596 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003597 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003598
3599 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3600 // in the registers. If not go to step 7.
3601 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003602 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003603
3604 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3605 // general purpose registers needed to pass type and num_fp to hold
3606 // the number of floating point registers needed.
3607
3608 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3609 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3610 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3611 //
3612 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3613 // register save space).
3614
Craig Topper8a13c412014-05-21 05:09:00 +00003615 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003616 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3617 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003618 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003619 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003620 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3621 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003622 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003623 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3624 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003625 }
3626
3627 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003628 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003629 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3630 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003631 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3632 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003633 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3634 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003635 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3636 }
3637
3638 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3639 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3640 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3641 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3642
3643 // Emit code to load the value if it was passed in registers.
3644
3645 CGF.EmitBlock(InRegBlock);
3646
3647 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3648 // an offset of l->gp_offset and/or l->fp_offset. This may require
3649 // copying to a temporary location in case the parameter is passed
3650 // in different register classes or requires an alignment greater
3651 // than 8 for general purpose registers and 16 for XMM registers.
3652 //
3653 // FIXME: This really results in shameful code when we end up needing to
3654 // collect arguments from different places; often what should result in a
3655 // simple assembling of a structure from scattered addresses has many more
3656 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003657 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003658 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3659 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3660 "reg_save_area");
3661
3662 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003663 if (neededInt && neededSSE) {
3664 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003665 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003666 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003667 Address Tmp = CGF.CreateMemTemp(Ty);
3668 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003669 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003670 llvm::Type *TyLo = ST->getElementType(0);
3671 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003672 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003673 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003674 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3675 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003676 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3677 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003678 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3679 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003680
John McCall7f416cc2015-09-08 08:05:57 +00003681 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003682 // FIXME: Our choice of alignment here and below is probably pessimistic.
3683 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3684 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3685 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003686 CGF.Builder.CreateStore(V,
3687 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3688
3689 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003690 V = CGF.Builder.CreateAlignedLoad(
3691 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3692 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003693 CharUnits Offset = CharUnits::fromQuantity(
3694 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3695 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3696
3697 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003698 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003699 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3700 CharUnits::fromQuantity(8));
3701 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003702
3703 // Copy to a temporary if necessary to ensure the appropriate alignment.
3704 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003705 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003706 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003707 CharUnits TyAlign = SizeAlign.second;
3708
3709 // Copy into a temporary if the type is more aligned than the
3710 // register save area.
3711 if (TyAlign.getQuantity() > 8) {
3712 Address Tmp = CGF.CreateMemTemp(Ty);
3713 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003714 RegAddr = Tmp;
3715 }
John McCall7f416cc2015-09-08 08:05:57 +00003716
Chris Lattner0cf24192010-06-28 20:05:43 +00003717 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003718 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3719 CharUnits::fromQuantity(16));
3720 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003721 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003722 assert(neededSSE == 2 && "Invalid number of needed registers!");
3723 // SSE registers are spaced 16 bytes apart in the register save
3724 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003725 // The ABI isn't explicit about this, but it seems reasonable
3726 // to assume that the slots are 16-byte aligned, since the stack is
3727 // naturally 16-byte aligned and the prologue is expected to store
3728 // all the SSE registers to the RSA.
3729 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3730 CharUnits::fromQuantity(16));
3731 Address RegAddrHi =
3732 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3733 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003734 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003735 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003736 llvm::Value *V;
3737 Address Tmp = CGF.CreateMemTemp(Ty);
3738 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3739 V = CGF.Builder.CreateLoad(
3740 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3741 CGF.Builder.CreateStore(V,
3742 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3743 V = CGF.Builder.CreateLoad(
3744 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3745 CGF.Builder.CreateStore(V,
3746 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3747
3748 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003749 }
3750
3751 // AMD64-ABI 3.5.7p5: Step 5. Set:
3752 // l->gp_offset = l->gp_offset + num_gp * 8
3753 // l->fp_offset = l->fp_offset + num_fp * 16.
3754 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003755 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003756 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3757 gp_offset_p);
3758 }
3759 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003760 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003761 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3762 fp_offset_p);
3763 }
3764 CGF.EmitBranch(ContBlock);
3765
3766 // Emit code to load the value if it was passed in memory.
3767
3768 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003769 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003770
3771 // Return the appropriate result.
3772
3773 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003774 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3775 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003776 return ResAddr;
3777}
3778
Charles Davisc7d5c942015-09-17 20:55:33 +00003779Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3780 QualType Ty) const {
3781 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3782 CGF.getContext().getTypeInfoInChars(Ty),
3783 CharUnits::fromQuantity(8),
3784 /*allowHigherAlign*/ false);
3785}
3786
Erich Keane521ed962017-01-05 00:20:51 +00003787ABIArgInfo
3788WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3789 const ABIArgInfo &current) const {
3790 // Assumes vectorCall calling convention.
3791 const Type *Base = nullptr;
3792 uint64_t NumElts = 0;
3793
3794 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3795 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3796 FreeSSERegs -= NumElts;
3797 return getDirectX86Hva();
3798 }
3799 return current;
3800}
3801
Reid Kleckner80944df2014-10-31 22:00:51 +00003802ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003803 bool IsReturnType, bool IsVectorCall,
3804 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003805
3806 if (Ty->isVoidType())
3807 return ABIArgInfo::getIgnore();
3808
3809 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3810 Ty = EnumTy->getDecl()->getIntegerType();
3811
Reid Kleckner80944df2014-10-31 22:00:51 +00003812 TypeInfo Info = getContext().getTypeInfo(Ty);
3813 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003814 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003815
Reid Kleckner9005f412014-05-02 00:51:20 +00003816 const RecordType *RT = Ty->getAs<RecordType>();
3817 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003818 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003819 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003820 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003821 }
3822
3823 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003824 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003825
Reid Kleckner9005f412014-05-02 00:51:20 +00003826 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003827
Reid Kleckner80944df2014-10-31 22:00:51 +00003828 const Type *Base = nullptr;
3829 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003830 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3831 // other targets.
3832 if ((IsVectorCall || IsRegCall) &&
3833 isHomogeneousAggregate(Ty, Base, NumElts)) {
3834 if (IsRegCall) {
3835 if (FreeSSERegs >= NumElts) {
3836 FreeSSERegs -= NumElts;
3837 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3838 return ABIArgInfo::getDirect();
3839 return ABIArgInfo::getExpand();
3840 }
3841 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3842 } else if (IsVectorCall) {
3843 if (FreeSSERegs >= NumElts &&
3844 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3845 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003846 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003847 } else if (IsReturnType) {
3848 return ABIArgInfo::getExpand();
3849 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3850 // HVAs are delayed and reclassified in the 2nd step.
3851 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3852 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003853 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003854 }
3855
Reid Klecknerec87fec2014-05-02 01:17:12 +00003856 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003857 // If the member pointer is represented by an LLVM int or ptr, pass it
3858 // directly.
3859 llvm::Type *LLTy = CGT.ConvertType(Ty);
3860 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3861 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003862 }
3863
Michael Kuperstein4f818702015-02-24 09:35:58 +00003864 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003865 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3866 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003867 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003868 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003869
Reid Kleckner9005f412014-05-02 00:51:20 +00003870 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003871 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003872 }
3873
Julien Lerouge10dcff82014-08-27 00:36:55 +00003874 // Bool type is always extended to the ABI, other builtin types are not
3875 // extended.
3876 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3877 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003878 return ABIArgInfo::getExtend();
3879
Reid Kleckner11a17192015-10-28 22:29:52 +00003880 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3881 // passes them indirectly through memory.
3882 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3883 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003884 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003885 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3886 }
3887
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003888 return ABIArgInfo::getDirect();
3889}
3890
Erich Keane521ed962017-01-05 00:20:51 +00003891void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3892 unsigned FreeSSERegs,
3893 bool IsVectorCall,
3894 bool IsRegCall) const {
3895 unsigned Count = 0;
3896 for (auto &I : FI.arguments()) {
3897 if (Count < VectorcallMaxParamNumAsReg)
3898 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3899 else {
3900 // Since these cannot be passed in registers, pretend no registers
3901 // are left.
3902 unsigned ZeroSSERegsAvail = 0;
3903 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3904 IsVectorCall, IsRegCall);
3905 }
3906 ++Count;
3907 }
3908
3909 Count = 0;
3910 for (auto &I : FI.arguments()) {
3911 if (Count < VectorcallMaxParamNumAsReg)
3912 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3913 ++Count;
3914 }
3915}
3916
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003917void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003918 bool IsVectorCall =
3919 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003920 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003921
Erich Keane757d3172016-11-02 18:29:35 +00003922 unsigned FreeSSERegs = 0;
3923 if (IsVectorCall) {
3924 // We can use up to 4 SSE return registers with vectorcall.
3925 FreeSSERegs = 4;
3926 } else if (IsRegCall) {
3927 // RegCall gives us 16 SSE registers.
3928 FreeSSERegs = 16;
3929 }
3930
Reid Kleckner80944df2014-10-31 22:00:51 +00003931 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003932 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3933 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003934
Erich Keane757d3172016-11-02 18:29:35 +00003935 if (IsVectorCall) {
3936 // We can use up to 6 SSE register parameters with vectorcall.
3937 FreeSSERegs = 6;
3938 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003939 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003940 FreeSSERegs = 16;
3941 }
3942
Erich Keane521ed962017-01-05 00:20:51 +00003943 if (IsVectorCall) {
3944 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3945 } else {
3946 for (auto &I : FI.arguments())
3947 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3948 }
3949
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003950}
3951
John McCall7f416cc2015-09-08 08:05:57 +00003952Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3953 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003954
3955 bool IsIndirect = false;
3956
3957 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3958 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3959 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3960 uint64_t Width = getContext().getTypeSize(Ty);
3961 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3962 }
3963
3964 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003965 CGF.getContext().getTypeInfoInChars(Ty),
3966 CharUnits::fromQuantity(8),
3967 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003968}
Chris Lattner0cf24192010-06-28 20:05:43 +00003969
John McCallea8d8bb2010-03-11 00:10:12 +00003970// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003971namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003972/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3973class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003974bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003975public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003976 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3977 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003978
John McCall7f416cc2015-09-08 08:05:57 +00003979 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3980 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003981};
3982
3983class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3984public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003985 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3986 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003987
Craig Topper4f12f102014-03-12 06:41:41 +00003988 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003989 // This is recovered from gcc output.
3990 return 1; // r1 is the dedicated stack pointer
3991 }
3992
3993 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003994 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003995};
3996
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003997}
John McCallea8d8bb2010-03-11 00:10:12 +00003998
James Y Knight29b5f082016-02-24 02:59:33 +00003999// TODO: this implementation is now likely redundant with
4000// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004001Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4002 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004003 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004004 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4005 // TODO: Implement this. For now ignore.
4006 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004007 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004008 }
4009
John McCall7f416cc2015-09-08 08:05:57 +00004010 // struct __va_list_tag {
4011 // unsigned char gpr;
4012 // unsigned char fpr;
4013 // unsigned short reserved;
4014 // void *overflow_arg_area;
4015 // void *reg_save_area;
4016 // };
4017
Roman Divacky8a12d842014-11-03 18:32:54 +00004018 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004019 bool isInt =
4020 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004021 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004022
4023 // All aggregates are passed indirectly? That doesn't seem consistent
4024 // with the argument-lowering code.
4025 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004026
4027 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004028
4029 // The calling convention either uses 1-2 GPRs or 1 FPR.
4030 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004031 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004032 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4033 } else {
4034 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004035 }
John McCall7f416cc2015-09-08 08:05:57 +00004036
4037 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4038
4039 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004040 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004041 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4042 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4043 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004044
Eric Christopher7565e0d2015-05-29 23:09:49 +00004045 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004046 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004047
4048 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4049 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4050 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4051
4052 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4053
John McCall7f416cc2015-09-08 08:05:57 +00004054 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4055 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004056
John McCall7f416cc2015-09-08 08:05:57 +00004057 // Case 1: consume registers.
4058 Address RegAddr = Address::invalid();
4059 {
4060 CGF.EmitBlock(UsingRegs);
4061
4062 Address RegSaveAreaPtr =
4063 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4064 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4065 CharUnits::fromQuantity(8));
4066 assert(RegAddr.getElementType() == CGF.Int8Ty);
4067
4068 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004069 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004070 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4071 CharUnits::fromQuantity(32));
4072 }
4073
4074 // Get the address of the saved value by scaling the number of
4075 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004076 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004077 llvm::Value *RegOffset =
4078 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4079 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4080 RegAddr.getPointer(), RegOffset),
4081 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4082 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4083
4084 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004085 NumRegs =
4086 Builder.CreateAdd(NumRegs,
4087 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004088 Builder.CreateStore(NumRegs, NumRegsAddr);
4089
4090 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004091 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004092
John McCall7f416cc2015-09-08 08:05:57 +00004093 // Case 2: consume space in the overflow area.
4094 Address MemAddr = Address::invalid();
4095 {
4096 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004097
Roman Divacky039b9702016-02-20 08:31:24 +00004098 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4099
John McCall7f416cc2015-09-08 08:05:57 +00004100 // Everything in the overflow area is rounded up to a size of at least 4.
4101 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4102
4103 CharUnits Size;
4104 if (!isIndirect) {
4105 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004106 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004107 } else {
4108 Size = CGF.getPointerSize();
4109 }
4110
4111 Address OverflowAreaAddr =
4112 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004113 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004114 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004115 // Round up address of argument to alignment
4116 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4117 if (Align > OverflowAreaAlign) {
4118 llvm::Value *Ptr = OverflowArea.getPointer();
4119 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4120 Align);
4121 }
4122
John McCall7f416cc2015-09-08 08:05:57 +00004123 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4124
4125 // Increase the overflow area.
4126 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4127 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4128 CGF.EmitBranch(Cont);
4129 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004130
4131 CGF.EmitBlock(Cont);
4132
John McCall7f416cc2015-09-08 08:05:57 +00004133 // Merge the cases with a phi.
4134 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4135 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004136
John McCall7f416cc2015-09-08 08:05:57 +00004137 // Load the pointer if the argument was passed indirectly.
4138 if (isIndirect) {
4139 Result = Address(Builder.CreateLoad(Result, "aggr"),
4140 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004141 }
4142
4143 return Result;
4144}
4145
John McCallea8d8bb2010-03-11 00:10:12 +00004146bool
4147PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4148 llvm::Value *Address) const {
4149 // This is calculated from the LLVM and GCC tables and verified
4150 // against gcc output. AFAIK all ABIs use the same encoding.
4151
4152 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004153
Chris Lattnerece04092012-02-07 00:39:47 +00004154 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004155 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4156 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4157 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4158
4159 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004160 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004161
4162 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004163 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004164
4165 // 64-76 are various 4-byte special-purpose registers:
4166 // 64: mq
4167 // 65: lr
4168 // 66: ctr
4169 // 67: ap
4170 // 68-75 cr0-7
4171 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004172 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004173
4174 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004175 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004176
4177 // 109: vrsave
4178 // 110: vscr
4179 // 111: spe_acc
4180 // 112: spefscr
4181 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004182 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004183
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004184 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004185}
4186
Roman Divackyd966e722012-05-09 18:22:46 +00004187// PowerPC-64
4188
4189namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004190/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004191class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004192public:
4193 enum ABIKind {
4194 ELFv1 = 0,
4195 ELFv2
4196 };
4197
4198private:
4199 static const unsigned GPRBits = 64;
4200 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004201 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004202 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004203
4204 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4205 // will be passed in a QPX register.
4206 bool IsQPXVectorTy(const Type *Ty) const {
4207 if (!HasQPX)
4208 return false;
4209
4210 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4211 unsigned NumElements = VT->getNumElements();
4212 if (NumElements == 1)
4213 return false;
4214
4215 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4216 if (getContext().getTypeSize(Ty) <= 256)
4217 return true;
4218 } else if (VT->getElementType()->
4219 isSpecificBuiltinType(BuiltinType::Float)) {
4220 if (getContext().getTypeSize(Ty) <= 128)
4221 return true;
4222 }
4223 }
4224
4225 return false;
4226 }
4227
4228 bool IsQPXVectorTy(QualType Ty) const {
4229 return IsQPXVectorTy(Ty.getTypePtr());
4230 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004231
4232public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004233 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4234 bool SoftFloatABI)
4235 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4236 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004237
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004238 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004239 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004240
4241 ABIArgInfo classifyReturnType(QualType RetTy) const;
4242 ABIArgInfo classifyArgumentType(QualType Ty) const;
4243
Reid Klecknere9f6a712014-10-31 17:10:41 +00004244 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4245 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4246 uint64_t Members) const override;
4247
Bill Schmidt84d37792012-10-12 19:26:17 +00004248 // TODO: We can add more logic to computeInfo to improve performance.
4249 // Example: For aggregate arguments that fit in a register, we could
4250 // use getDirectInReg (as is done below for structs containing a single
4251 // floating-point value) to avoid pushing them to memory on function
4252 // entry. This would require changing the logic in PPCISelLowering
4253 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004254 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004255 if (!getCXXABI().classifyReturnType(FI))
4256 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004257 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004258 // We rely on the default argument classification for the most part.
4259 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004260 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004261 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004262 if (T) {
4263 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004264 if (IsQPXVectorTy(T) ||
4265 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004266 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004267 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004268 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004269 continue;
4270 }
4271 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004272 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004273 }
4274 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004275
John McCall7f416cc2015-09-08 08:05:57 +00004276 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4277 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004278};
4279
4280class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004281
Bill Schmidt25cb3492012-10-03 19:18:57 +00004282public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004283 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004284 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4285 bool SoftFloatABI)
4286 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4287 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004288
Craig Topper4f12f102014-03-12 06:41:41 +00004289 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004290 // This is recovered from gcc output.
4291 return 1; // r1 is the dedicated stack pointer
4292 }
4293
4294 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004295 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004296};
4297
Roman Divackyd966e722012-05-09 18:22:46 +00004298class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4299public:
4300 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4301
Craig Topper4f12f102014-03-12 06:41:41 +00004302 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004303 // This is recovered from gcc output.
4304 return 1; // r1 is the dedicated stack pointer
4305 }
4306
4307 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004308 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004309};
4310
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004311}
Roman Divackyd966e722012-05-09 18:22:46 +00004312
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004313// Return true if the ABI requires Ty to be passed sign- or zero-
4314// extended to 64 bits.
4315bool
4316PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4317 // Treat an enum type as its underlying type.
4318 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4319 Ty = EnumTy->getDecl()->getIntegerType();
4320
4321 // Promotable integer types are required to be promoted by the ABI.
4322 if (Ty->isPromotableIntegerType())
4323 return true;
4324
4325 // In addition to the usual promotable integer types, we also need to
4326 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4327 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4328 switch (BT->getKind()) {
4329 case BuiltinType::Int:
4330 case BuiltinType::UInt:
4331 return true;
4332 default:
4333 break;
4334 }
4335
4336 return false;
4337}
4338
John McCall7f416cc2015-09-08 08:05:57 +00004339/// isAlignedParamType - Determine whether a type requires 16-byte or
4340/// higher alignment in the parameter area. Always returns at least 8.
4341CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004342 // Complex types are passed just like their elements.
4343 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4344 Ty = CTy->getElementType();
4345
4346 // Only vector types of size 16 bytes need alignment (larger types are
4347 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004348 if (IsQPXVectorTy(Ty)) {
4349 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004350 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004351
John McCall7f416cc2015-09-08 08:05:57 +00004352 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004353 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004354 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004355 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004356
4357 // For single-element float/vector structs, we consider the whole type
4358 // to have the same alignment requirements as its single element.
4359 const Type *AlignAsType = nullptr;
4360 const Type *EltType = isSingleElementStruct(Ty, getContext());
4361 if (EltType) {
4362 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004363 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004364 getContext().getTypeSize(EltType) == 128) ||
4365 (BT && BT->isFloatingPoint()))
4366 AlignAsType = EltType;
4367 }
4368
Ulrich Weigandb7122372014-07-21 00:48:09 +00004369 // Likewise for ELFv2 homogeneous aggregates.
4370 const Type *Base = nullptr;
4371 uint64_t Members = 0;
4372 if (!AlignAsType && Kind == ELFv2 &&
4373 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4374 AlignAsType = Base;
4375
Ulrich Weigand581badc2014-07-10 17:20:07 +00004376 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004377 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4378 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004379 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004380
John McCall7f416cc2015-09-08 08:05:57 +00004381 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004382 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004383 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004384 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004385
4386 // Otherwise, we only need alignment for any aggregate type that
4387 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004388 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4389 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004390 return CharUnits::fromQuantity(32);
4391 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004392 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004393
John McCall7f416cc2015-09-08 08:05:57 +00004394 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004395}
4396
Ulrich Weigandb7122372014-07-21 00:48:09 +00004397/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4398/// aggregate. Base is set to the base element type, and Members is set
4399/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004400bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4401 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004402 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4403 uint64_t NElements = AT->getSize().getZExtValue();
4404 if (NElements == 0)
4405 return false;
4406 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4407 return false;
4408 Members *= NElements;
4409 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4410 const RecordDecl *RD = RT->getDecl();
4411 if (RD->hasFlexibleArrayMember())
4412 return false;
4413
4414 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004415
4416 // If this is a C++ record, check the bases first.
4417 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4418 for (const auto &I : CXXRD->bases()) {
4419 // Ignore empty records.
4420 if (isEmptyRecord(getContext(), I.getType(), true))
4421 continue;
4422
4423 uint64_t FldMembers;
4424 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4425 return false;
4426
4427 Members += FldMembers;
4428 }
4429 }
4430
Ulrich Weigandb7122372014-07-21 00:48:09 +00004431 for (const auto *FD : RD->fields()) {
4432 // Ignore (non-zero arrays of) empty records.
4433 QualType FT = FD->getType();
4434 while (const ConstantArrayType *AT =
4435 getContext().getAsConstantArrayType(FT)) {
4436 if (AT->getSize().getZExtValue() == 0)
4437 return false;
4438 FT = AT->getElementType();
4439 }
4440 if (isEmptyRecord(getContext(), FT, true))
4441 continue;
4442
4443 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4444 if (getContext().getLangOpts().CPlusPlus &&
4445 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4446 continue;
4447
4448 uint64_t FldMembers;
4449 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4450 return false;
4451
4452 Members = (RD->isUnion() ?
4453 std::max(Members, FldMembers) : Members + FldMembers);
4454 }
4455
4456 if (!Base)
4457 return false;
4458
4459 // Ensure there is no padding.
4460 if (getContext().getTypeSize(Base) * Members !=
4461 getContext().getTypeSize(Ty))
4462 return false;
4463 } else {
4464 Members = 1;
4465 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4466 Members = 2;
4467 Ty = CT->getElementType();
4468 }
4469
Reid Klecknere9f6a712014-10-31 17:10:41 +00004470 // Most ABIs only support float, double, and some vector type widths.
4471 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004472 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004473
4474 // The base type must be the same for all members. Types that
4475 // agree in both total size and mode (float vs. vector) are
4476 // treated as being equivalent here.
4477 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004478 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004479 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004480 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4481 // so make sure to widen it explicitly.
4482 if (const VectorType *VT = Base->getAs<VectorType>()) {
4483 QualType EltTy = VT->getElementType();
4484 unsigned NumElements =
4485 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4486 Base = getContext()
4487 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4488 .getTypePtr();
4489 }
4490 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004491
4492 if (Base->isVectorType() != TyPtr->isVectorType() ||
4493 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4494 return false;
4495 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004496 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4497}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004498
Reid Klecknere9f6a712014-10-31 17:10:41 +00004499bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4500 // Homogeneous aggregates for ELFv2 must have base types of float,
4501 // double, long double, or 128-bit vectors.
4502 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4503 if (BT->getKind() == BuiltinType::Float ||
4504 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004505 BT->getKind() == BuiltinType::LongDouble) {
4506 if (IsSoftFloatABI)
4507 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004508 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004509 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004510 }
4511 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004512 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004513 return true;
4514 }
4515 return false;
4516}
4517
4518bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4519 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004520 // Vector types require one register, floating point types require one
4521 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004522 uint32_t NumRegs =
4523 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004524
4525 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004526 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004527}
4528
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004529ABIArgInfo
4530PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004531 Ty = useFirstFieldIfTransparentUnion(Ty);
4532
Bill Schmidt90b22c92012-11-27 02:46:43 +00004533 if (Ty->isAnyComplexType())
4534 return ABIArgInfo::getDirect();
4535
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004536 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4537 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004538 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004539 uint64_t Size = getContext().getTypeSize(Ty);
4540 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004541 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004542 else if (Size < 128) {
4543 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4544 return ABIArgInfo::getDirect(CoerceTy);
4545 }
4546 }
4547
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004548 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004549 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004550 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004551
John McCall7f416cc2015-09-08 08:05:57 +00004552 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4553 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004554
4555 // ELFv2 homogeneous aggregates are passed as array types.
4556 const Type *Base = nullptr;
4557 uint64_t Members = 0;
4558 if (Kind == ELFv2 &&
4559 isHomogeneousAggregate(Ty, Base, Members)) {
4560 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4561 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4562 return ABIArgInfo::getDirect(CoerceTy);
4563 }
4564
Ulrich Weigand601957f2014-07-21 00:56:36 +00004565 // If an aggregate may end up fully in registers, we do not
4566 // use the ByVal method, but pass the aggregate as array.
4567 // This is usually beneficial since we avoid forcing the
4568 // back-end to store the argument to memory.
4569 uint64_t Bits = getContext().getTypeSize(Ty);
4570 if (Bits > 0 && Bits <= 8 * GPRBits) {
4571 llvm::Type *CoerceTy;
4572
4573 // Types up to 8 bytes are passed as integer type (which will be
4574 // properly aligned in the argument save area doubleword).
4575 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004576 CoerceTy =
4577 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004578 // Larger types are passed as arrays, with the base type selected
4579 // according to the required alignment in the save area.
4580 else {
4581 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004582 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004583 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4584 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4585 }
4586
4587 return ABIArgInfo::getDirect(CoerceTy);
4588 }
4589
Ulrich Weigandb7122372014-07-21 00:48:09 +00004590 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004591 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4592 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004593 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004594 }
4595
4596 return (isPromotableTypeForABI(Ty) ?
4597 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4598}
4599
4600ABIArgInfo
4601PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4602 if (RetTy->isVoidType())
4603 return ABIArgInfo::getIgnore();
4604
Bill Schmidta3d121c2012-12-17 04:20:17 +00004605 if (RetTy->isAnyComplexType())
4606 return ABIArgInfo::getDirect();
4607
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004608 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4609 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004610 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004611 uint64_t Size = getContext().getTypeSize(RetTy);
4612 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004613 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004614 else if (Size < 128) {
4615 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4616 return ABIArgInfo::getDirect(CoerceTy);
4617 }
4618 }
4619
Ulrich Weigandb7122372014-07-21 00:48:09 +00004620 if (isAggregateTypeForABI(RetTy)) {
4621 // ELFv2 homogeneous aggregates are returned as array types.
4622 const Type *Base = nullptr;
4623 uint64_t Members = 0;
4624 if (Kind == ELFv2 &&
4625 isHomogeneousAggregate(RetTy, Base, Members)) {
4626 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4627 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4628 return ABIArgInfo::getDirect(CoerceTy);
4629 }
4630
4631 // ELFv2 small aggregates are returned in up to two registers.
4632 uint64_t Bits = getContext().getTypeSize(RetTy);
4633 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4634 if (Bits == 0)
4635 return ABIArgInfo::getIgnore();
4636
4637 llvm::Type *CoerceTy;
4638 if (Bits > GPRBits) {
4639 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004640 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004641 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004642 CoerceTy =
4643 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004644 return ABIArgInfo::getDirect(CoerceTy);
4645 }
4646
4647 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004648 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004649 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004650
4651 return (isPromotableTypeForABI(RetTy) ?
4652 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4653}
4654
Bill Schmidt25cb3492012-10-03 19:18:57 +00004655// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004656Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4657 QualType Ty) const {
4658 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4659 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004660
John McCall7f416cc2015-09-08 08:05:57 +00004661 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004662
Bill Schmidt924c4782013-01-14 17:45:36 +00004663 // If we have a complex type and the base type is smaller than 8 bytes,
4664 // the ABI calls for the real and imaginary parts to be right-adjusted
4665 // in separate doublewords. However, Clang expects us to produce a
4666 // pointer to a structure with the two parts packed tightly. So generate
4667 // loads of the real and imaginary parts relative to the va_list pointer,
4668 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004669 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4670 CharUnits EltSize = TypeInfo.first / 2;
4671 if (EltSize < SlotSize) {
4672 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4673 SlotSize * 2, SlotSize,
4674 SlotSize, /*AllowHigher*/ true);
4675
4676 Address RealAddr = Addr;
4677 Address ImagAddr = RealAddr;
4678 if (CGF.CGM.getDataLayout().isBigEndian()) {
4679 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4680 SlotSize - EltSize);
4681 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4682 2 * SlotSize - EltSize);
4683 } else {
4684 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4685 }
4686
4687 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4688 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4689 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4690 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4691 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4692
4693 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4694 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4695 /*init*/ true);
4696 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004697 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004698 }
4699
John McCall7f416cc2015-09-08 08:05:57 +00004700 // Otherwise, just use the general rule.
4701 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4702 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004703}
4704
4705static bool
4706PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4707 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004708 // This is calculated from the LLVM and GCC tables and verified
4709 // against gcc output. AFAIK all ABIs use the same encoding.
4710
4711 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4712
4713 llvm::IntegerType *i8 = CGF.Int8Ty;
4714 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4715 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4716 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4717
4718 // 0-31: r0-31, the 8-byte general-purpose registers
4719 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4720
4721 // 32-63: fp0-31, the 8-byte floating-point registers
4722 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4723
Hal Finkel84832a72016-08-30 02:38:34 +00004724 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004725 // 64: mq
4726 // 65: lr
4727 // 66: ctr
4728 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004729 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4730
4731 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004732 // 68-75 cr0-7
4733 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004734 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004735
4736 // 77-108: v0-31, the 16-byte vector registers
4737 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4738
4739 // 109: vrsave
4740 // 110: vscr
4741 // 111: spe_acc
4742 // 112: spefscr
4743 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004744 // 114: tfhar
4745 // 115: tfiar
4746 // 116: texasr
4747 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004748
4749 return false;
4750}
John McCallea8d8bb2010-03-11 00:10:12 +00004751
Bill Schmidt25cb3492012-10-03 19:18:57 +00004752bool
4753PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4754 CodeGen::CodeGenFunction &CGF,
4755 llvm::Value *Address) const {
4756
4757 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4758}
4759
4760bool
4761PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4762 llvm::Value *Address) const {
4763
4764 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4765}
4766
Chris Lattner0cf24192010-06-28 20:05:43 +00004767//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004768// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004769//===----------------------------------------------------------------------===//
4770
4771namespace {
4772
John McCall12f23522016-04-04 18:33:08 +00004773class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004774public:
4775 enum ABIKind {
4776 AAPCS = 0,
4777 DarwinPCS
4778 };
4779
4780private:
4781 ABIKind Kind;
4782
4783public:
John McCall12f23522016-04-04 18:33:08 +00004784 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4785 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004786
4787private:
4788 ABIKind getABIKind() const { return Kind; }
4789 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4790
4791 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004792 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004793 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4794 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4795 uint64_t Members) const override;
4796
Tim Northovera2ee4332014-03-29 15:09:45 +00004797 bool isIllegalVectorType(QualType Ty) const;
4798
David Blaikie1cbb9712014-11-14 19:09:44 +00004799 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004800 if (!getCXXABI().classifyReturnType(FI))
4801 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004802
Tim Northoverb047bfa2014-11-27 21:02:49 +00004803 for (auto &it : FI.arguments())
4804 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004805 }
4806
John McCall7f416cc2015-09-08 08:05:57 +00004807 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4808 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004809
John McCall7f416cc2015-09-08 08:05:57 +00004810 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4811 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004812
John McCall7f416cc2015-09-08 08:05:57 +00004813 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4814 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004815 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4816 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4817 }
John McCall12f23522016-04-04 18:33:08 +00004818
4819 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4820 ArrayRef<llvm::Type*> scalars,
4821 bool asReturnValue) const override {
4822 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4823 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004824 bool isSwiftErrorInRegister() const override {
4825 return true;
4826 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004827};
4828
Tim Northover573cbee2014-05-24 12:52:07 +00004829class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004830public:
Tim Northover573cbee2014-05-24 12:52:07 +00004831 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4832 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004833
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004834 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Saleem Abdulrasool40db4772017-02-11 23:03:13 +00004835 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004836 }
4837
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004838 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4839 return 31;
4840 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004841
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004842 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004843};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004844}
Tim Northovera2ee4332014-03-29 15:09:45 +00004845
Tim Northoverb047bfa2014-11-27 21:02:49 +00004846ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004847 Ty = useFirstFieldIfTransparentUnion(Ty);
4848
Tim Northovera2ee4332014-03-29 15:09:45 +00004849 // Handle illegal vector types here.
4850 if (isIllegalVectorType(Ty)) {
4851 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004852 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004853 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004854 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4855 return ABIArgInfo::getDirect(ResType);
4856 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004857 if (Size <= 32) {
4858 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004859 return ABIArgInfo::getDirect(ResType);
4860 }
4861 if (Size == 64) {
4862 llvm::Type *ResType =
4863 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004864 return ABIArgInfo::getDirect(ResType);
4865 }
4866 if (Size == 128) {
4867 llvm::Type *ResType =
4868 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004869 return ABIArgInfo::getDirect(ResType);
4870 }
John McCall7f416cc2015-09-08 08:05:57 +00004871 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004872 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004873
4874 if (!isAggregateTypeForABI(Ty)) {
4875 // Treat an enum type as its underlying type.
4876 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4877 Ty = EnumTy->getDecl()->getIntegerType();
4878
Tim Northovera2ee4332014-03-29 15:09:45 +00004879 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4880 ? ABIArgInfo::getExtend()
4881 : ABIArgInfo::getDirect());
4882 }
4883
4884 // Structures with either a non-trivial destructor or a non-trivial
4885 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004886 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004887 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4888 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004889 }
4890
4891 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4892 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004893 uint64_t Size = getContext().getTypeSize(Ty);
4894 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4895 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004896 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4897 return ABIArgInfo::getIgnore();
4898
Tim Northover23bcad22017-05-05 22:36:06 +00004899 // GNU C mode. The only argument that gets ignored is an empty one with size
4900 // 0.
4901 if (IsEmpty && Size == 0)
4902 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004903 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4904 }
4905
4906 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004907 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004908 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004909 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004910 return ABIArgInfo::getDirect(
4911 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004912 }
4913
4914 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00004915 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004916 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4917 // same size and alignment.
4918 if (getTarget().isRenderScriptTarget()) {
4919 return coerceToIntArray(Ty, getContext(), getVMContext());
4920 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004921 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00004922 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004923
Tim Northovera2ee4332014-03-29 15:09:45 +00004924 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4925 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004926 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004927 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4928 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4929 }
4930 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4931 }
4932
John McCall7f416cc2015-09-08 08:05:57 +00004933 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004934}
4935
Tim Northover573cbee2014-05-24 12:52:07 +00004936ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004937 if (RetTy->isVoidType())
4938 return ABIArgInfo::getIgnore();
4939
4940 // Large vector types should be returned via memory.
4941 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004942 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004943
4944 if (!isAggregateTypeForABI(RetTy)) {
4945 // Treat an enum type as its underlying type.
4946 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4947 RetTy = EnumTy->getDecl()->getIntegerType();
4948
Tim Northover4dab6982014-04-18 13:46:08 +00004949 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4950 ? ABIArgInfo::getExtend()
4951 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004952 }
4953
Tim Northover23bcad22017-05-05 22:36:06 +00004954 uint64_t Size = getContext().getTypeSize(RetTy);
4955 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00004956 return ABIArgInfo::getIgnore();
4957
Craig Topper8a13c412014-05-21 05:09:00 +00004958 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004959 uint64_t Members = 0;
4960 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004961 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4962 return ABIArgInfo::getDirect();
4963
4964 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00004965 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004966 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4967 // same size and alignment.
4968 if (getTarget().isRenderScriptTarget()) {
4969 return coerceToIntArray(RetTy, getContext(), getVMContext());
4970 }
Pete Cooper635b5092015-04-17 22:16:24 +00004971 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00004972 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004973
4974 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4975 // For aggregates with 16-byte alignment, we use i128.
4976 if (Alignment < 128 && Size == 128) {
4977 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4978 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4979 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004980 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4981 }
4982
John McCall7f416cc2015-09-08 08:05:57 +00004983 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004984}
4985
Tim Northover573cbee2014-05-24 12:52:07 +00004986/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4987bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004988 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4989 // Check whether VT is legal.
4990 unsigned NumElements = VT->getNumElements();
4991 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004992 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004993 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004994 return true;
4995 return Size != 64 && (Size != 128 || NumElements == 1);
4996 }
4997 return false;
4998}
4999
Reid Klecknere9f6a712014-10-31 17:10:41 +00005000bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5001 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5002 // point type or a short-vector type. This is the same as the 32-bit ABI,
5003 // but with the difference that any floating-point type is allowed,
5004 // including __fp16.
5005 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5006 if (BT->isFloatingPoint())
5007 return true;
5008 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5009 unsigned VecSize = getContext().getTypeSize(VT);
5010 if (VecSize == 64 || VecSize == 128)
5011 return true;
5012 }
5013 return false;
5014}
5015
5016bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5017 uint64_t Members) const {
5018 return Members <= 4;
5019}
5020
John McCall7f416cc2015-09-08 08:05:57 +00005021Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005022 QualType Ty,
5023 CodeGenFunction &CGF) const {
5024 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005025 bool IsIndirect = AI.isIndirect();
5026
Tim Northoverb047bfa2014-11-27 21:02:49 +00005027 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5028 if (IsIndirect)
5029 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5030 else if (AI.getCoerceToType())
5031 BaseTy = AI.getCoerceToType();
5032
5033 unsigned NumRegs = 1;
5034 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5035 BaseTy = ArrTy->getElementType();
5036 NumRegs = ArrTy->getNumElements();
5037 }
5038 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5039
Tim Northovera2ee4332014-03-29 15:09:45 +00005040 // The AArch64 va_list type and handling is specified in the Procedure Call
5041 // Standard, section B.4:
5042 //
5043 // struct {
5044 // void *__stack;
5045 // void *__gr_top;
5046 // void *__vr_top;
5047 // int __gr_offs;
5048 // int __vr_offs;
5049 // };
5050
5051 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5052 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5053 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5054 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005055
John McCall7f416cc2015-09-08 08:05:57 +00005056 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5057 CharUnits TyAlign = TyInfo.second;
5058
5059 Address reg_offs_p = Address::invalid();
5060 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005061 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005062 CharUnits reg_top_offset;
5063 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005064 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005065 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005066 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005067 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5068 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5070 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005071 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005072 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005073 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005074 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005075 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005076 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5077 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005078 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5079 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005080 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005081 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 }
5083
5084 //=======================================
5085 // Find out where argument was passed
5086 //=======================================
5087
5088 // If reg_offs >= 0 we're already using the stack for this type of
5089 // argument. We don't want to keep updating reg_offs (in case it overflows,
5090 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5091 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005092 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005093 UsingStack = CGF.Builder.CreateICmpSGE(
5094 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5095
5096 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5097
5098 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005099 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005100 CGF.EmitBlock(MaybeRegBlock);
5101
5102 // Integer arguments may need to correct register alignment (for example a
5103 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5104 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005105 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5106 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005107
5108 reg_offs = CGF.Builder.CreateAdd(
5109 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5110 "align_regoffs");
5111 reg_offs = CGF.Builder.CreateAnd(
5112 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5113 "aligned_regoffs");
5114 }
5115
5116 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005117 // The fact that this is done unconditionally reflects the fact that
5118 // allocating an argument to the stack also uses up all the remaining
5119 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005120 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005121 NewOffset = CGF.Builder.CreateAdd(
5122 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5123 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5124
5125 // Now we're in a position to decide whether this argument really was in
5126 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005127 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005128 InRegs = CGF.Builder.CreateICmpSLE(
5129 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5130
5131 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5132
5133 //=======================================
5134 // Argument was in registers
5135 //=======================================
5136
5137 // Now we emit the code for if the argument was originally passed in
5138 // registers. First start the appropriate block:
5139 CGF.EmitBlock(InRegBlock);
5140
John McCall7f416cc2015-09-08 08:05:57 +00005141 llvm::Value *reg_top = nullptr;
5142 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5143 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005144 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005145 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5146 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5147 Address RegAddr = Address::invalid();
5148 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005149
5150 if (IsIndirect) {
5151 // If it's been passed indirectly (actually a struct), whatever we find from
5152 // stored registers or on the stack will actually be a struct **.
5153 MemTy = llvm::PointerType::getUnqual(MemTy);
5154 }
5155
Craig Topper8a13c412014-05-21 05:09:00 +00005156 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005157 uint64_t NumMembers = 0;
5158 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005159 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005160 // Homogeneous aggregates passed in registers will have their elements split
5161 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5162 // qN+1, ...). We reload and store into a temporary local variable
5163 // contiguously.
5164 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005165 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005166 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5167 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005168 Address Tmp = CGF.CreateTempAlloca(HFATy,
5169 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005170
John McCall7f416cc2015-09-08 08:05:57 +00005171 // On big-endian platforms, the value will be right-aligned in its slot.
5172 int Offset = 0;
5173 if (CGF.CGM.getDataLayout().isBigEndian() &&
5174 BaseTyInfo.first.getQuantity() < 16)
5175 Offset = 16 - BaseTyInfo.first.getQuantity();
5176
Tim Northovera2ee4332014-03-29 15:09:45 +00005177 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005178 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5179 Address LoadAddr =
5180 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5181 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5182
5183 Address StoreAddr =
5184 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005185
5186 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5187 CGF.Builder.CreateStore(Elem, StoreAddr);
5188 }
5189
John McCall7f416cc2015-09-08 08:05:57 +00005190 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005191 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005192 // Otherwise the object is contiguous in memory.
5193
5194 // It might be right-aligned in its slot.
5195 CharUnits SlotSize = BaseAddr.getAlignment();
5196 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005197 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005198 TyInfo.first < SlotSize) {
5199 CharUnits Offset = SlotSize - TyInfo.first;
5200 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005201 }
5202
John McCall7f416cc2015-09-08 08:05:57 +00005203 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005204 }
5205
5206 CGF.EmitBranch(ContBlock);
5207
5208 //=======================================
5209 // Argument was on the stack
5210 //=======================================
5211 CGF.EmitBlock(OnStackBlock);
5212
John McCall7f416cc2015-09-08 08:05:57 +00005213 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5214 CharUnits::Zero(), "stack_p");
5215 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005216
John McCall7f416cc2015-09-08 08:05:57 +00005217 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005218 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005219 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5220 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005221
John McCall7f416cc2015-09-08 08:05:57 +00005222 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005223
John McCall7f416cc2015-09-08 08:05:57 +00005224 OnStackPtr = CGF.Builder.CreateAdd(
5225 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005226 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005227 OnStackPtr = CGF.Builder.CreateAnd(
5228 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005229 "align_stack");
5230
John McCall7f416cc2015-09-08 08:05:57 +00005231 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005232 }
John McCall7f416cc2015-09-08 08:05:57 +00005233 Address OnStackAddr(OnStackPtr,
5234 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005235
John McCall7f416cc2015-09-08 08:05:57 +00005236 // All stack slots are multiples of 8 bytes.
5237 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5238 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005239 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005240 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005241 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005242 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005243
John McCall7f416cc2015-09-08 08:05:57 +00005244 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005245 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005246 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005247
5248 // Write the new value of __stack for the next call to va_arg
5249 CGF.Builder.CreateStore(NewStack, stack_p);
5250
5251 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005252 TyInfo.first < StackSlotSize) {
5253 CharUnits Offset = StackSlotSize - TyInfo.first;
5254 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005255 }
5256
John McCall7f416cc2015-09-08 08:05:57 +00005257 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005258
5259 CGF.EmitBranch(ContBlock);
5260
5261 //=======================================
5262 // Tidy up
5263 //=======================================
5264 CGF.EmitBlock(ContBlock);
5265
John McCall7f416cc2015-09-08 08:05:57 +00005266 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5267 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005268
5269 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005270 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5271 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005272
5273 return ResAddr;
5274}
5275
John McCall7f416cc2015-09-08 08:05:57 +00005276Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5277 CodeGenFunction &CGF) const {
5278 // The backend's lowering doesn't support va_arg for aggregates or
5279 // illegal vector types. Lower VAArg here for these cases and use
5280 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005281 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005282 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005283
John McCall7f416cc2015-09-08 08:05:57 +00005284 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005285
John McCall7f416cc2015-09-08 08:05:57 +00005286 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005287 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005288 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5289 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5290 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005291 }
5292
John McCall7f416cc2015-09-08 08:05:57 +00005293 // The size of the actual thing passed, which might end up just
5294 // being a pointer for indirect types.
5295 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5296
5297 // Arguments bigger than 16 bytes which aren't homogeneous
5298 // aggregates should be passed indirectly.
5299 bool IsIndirect = false;
5300 if (TyInfo.first.getQuantity() > 16) {
5301 const Type *Base = nullptr;
5302 uint64_t Members = 0;
5303 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005304 }
5305
John McCall7f416cc2015-09-08 08:05:57 +00005306 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5307 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005308}
5309
5310//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005311// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005312//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005313
5314namespace {
5315
John McCall12f23522016-04-04 18:33:08 +00005316class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005317public:
5318 enum ABIKind {
5319 APCS = 0,
5320 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005321 AAPCS_VFP = 2,
5322 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005323 };
5324
5325private:
5326 ABIKind Kind;
5327
5328public:
John McCall12f23522016-04-04 18:33:08 +00005329 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5330 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005331 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005332 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005333
John McCall3480ef22011-08-30 01:42:09 +00005334 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005335 switch (getTarget().getTriple().getEnvironment()) {
5336 case llvm::Triple::Android:
5337 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005338 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005339 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005340 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005341 case llvm::Triple::MuslEABI:
5342 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005343 return true;
5344 default:
5345 return false;
5346 }
John McCall3480ef22011-08-30 01:42:09 +00005347 }
5348
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005349 bool isEABIHF() const {
5350 switch (getTarget().getTriple().getEnvironment()) {
5351 case llvm::Triple::EABIHF:
5352 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005353 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005354 return true;
5355 default:
5356 return false;
5357 }
5358 }
5359
Daniel Dunbar020daa92009-09-12 01:00:39 +00005360 ABIKind getABIKind() const { return Kind; }
5361
Tim Northovera484bc02013-10-01 14:34:25 +00005362private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005363 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005364 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005365 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005366
Reid Klecknere9f6a712014-10-31 17:10:41 +00005367 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5368 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5369 uint64_t Members) const override;
5370
Craig Topper4f12f102014-03-12 06:41:41 +00005371 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005372
John McCall7f416cc2015-09-08 08:05:57 +00005373 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5374 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005375
5376 llvm::CallingConv::ID getLLVMDefaultCC() const;
5377 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005378 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005379
5380 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5381 ArrayRef<llvm::Type*> scalars,
5382 bool asReturnValue) const override {
5383 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5384 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005385 bool isSwiftErrorInRegister() const override {
5386 return true;
5387 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005388};
5389
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005390class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5391public:
Chris Lattner2b037972010-07-29 02:01:43 +00005392 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5393 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005394
John McCall3480ef22011-08-30 01:42:09 +00005395 const ARMABIInfo &getABIInfo() const {
5396 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5397 }
5398
Craig Topper4f12f102014-03-12 06:41:41 +00005399 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005400 return 13;
5401 }
Roman Divackyc1617352011-05-18 19:36:54 +00005402
Craig Topper4f12f102014-03-12 06:41:41 +00005403 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005404 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5405 }
5406
Roman Divackyc1617352011-05-18 19:36:54 +00005407 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005408 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005409 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005410
5411 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005412 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005413 return false;
5414 }
John McCall3480ef22011-08-30 01:42:09 +00005415
Craig Topper4f12f102014-03-12 06:41:41 +00005416 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005417 if (getABIInfo().isEABI()) return 88;
5418 return TargetCodeGenInfo::getSizeOfUnwindException();
5419 }
Tim Northovera484bc02013-10-01 14:34:25 +00005420
Eric Christopher162c91c2015-06-05 22:03:00 +00005421 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005422 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005423 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005424 if (!FD)
5425 return;
5426
5427 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5428 if (!Attr)
5429 return;
5430
5431 const char *Kind;
5432 switch (Attr->getInterrupt()) {
5433 case ARMInterruptAttr::Generic: Kind = ""; break;
5434 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5435 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5436 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5437 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5438 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5439 }
5440
5441 llvm::Function *Fn = cast<llvm::Function>(GV);
5442
5443 Fn->addFnAttr("interrupt", Kind);
5444
Tim Northover5627d392015-10-30 16:30:45 +00005445 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5446 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005447 return;
5448
5449 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5450 // however this is not necessarily true on taking any interrupt. Instruct
5451 // the backend to perform a realignment as part of the function prologue.
5452 llvm::AttrBuilder B;
5453 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005454 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005455 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005456};
5457
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005458class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005459public:
5460 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5461 : ARMTargetCodeGenInfo(CGT, K) {}
5462
Eric Christopher162c91c2015-06-05 22:03:00 +00005463 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005464 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005465
5466 void getDependentLibraryOption(llvm::StringRef Lib,
5467 llvm::SmallString<24> &Opt) const override {
5468 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5469 }
5470
5471 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5472 llvm::SmallString<32> &Opt) const override {
5473 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5474 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005475};
5476
Eric Christopher162c91c2015-06-05 22:03:00 +00005477void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005478 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005479 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005480 addStackProbeSizeTargetAttribute(D, GV, CGM);
5481}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005482}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005483
Chris Lattner22326a12010-07-29 02:31:05 +00005484void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005485 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005486 FI.getReturnInfo() =
5487 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005488
Tim Northoverbc784d12015-02-24 17:22:40 +00005489 for (auto &I : FI.arguments())
5490 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005491
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005492 // Always honor user-specified calling convention.
5493 if (FI.getCallingConvention() != llvm::CallingConv::C)
5494 return;
5495
John McCall882987f2013-02-28 19:01:20 +00005496 llvm::CallingConv::ID cc = getRuntimeCC();
5497 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005498 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005499}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005500
John McCall882987f2013-02-28 19:01:20 +00005501/// Return the default calling convention that LLVM will use.
5502llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5503 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005504 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005505 return llvm::CallingConv::ARM_AAPCS_VFP;
5506 else if (isEABI())
5507 return llvm::CallingConv::ARM_AAPCS;
5508 else
5509 return llvm::CallingConv::ARM_APCS;
5510}
5511
5512/// Return the calling convention that our ABI would like us to use
5513/// as the C calling convention.
5514llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005515 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005516 case APCS: return llvm::CallingConv::ARM_APCS;
5517 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5518 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005519 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005520 }
John McCall882987f2013-02-28 19:01:20 +00005521 llvm_unreachable("bad ABI kind");
5522}
5523
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005524void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005525 assert(getRuntimeCC() == llvm::CallingConv::C);
5526
5527 // Don't muddy up the IR with a ton of explicit annotations if
5528 // they'd just match what LLVM will infer from the triple.
5529 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5530 if (abiCC != getLLVMDefaultCC())
5531 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005532
Tim Northover5627d392015-10-30 16:30:45 +00005533 // AAPCS apparently requires runtime support functions to be soft-float, but
5534 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5535 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5536 switch (getABIKind()) {
5537 case APCS:
5538 case AAPCS16_VFP:
5539 if (abiCC != getLLVMDefaultCC())
5540 BuiltinCC = abiCC;
5541 break;
5542 case AAPCS:
5543 case AAPCS_VFP:
5544 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5545 break;
5546 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005547}
5548
Tim Northoverbc784d12015-02-24 17:22:40 +00005549ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5550 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005551 // 6.1.2.1 The following argument types are VFP CPRCs:
5552 // A single-precision floating-point type (including promoted
5553 // half-precision types); A double-precision floating-point type;
5554 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5555 // with a Base Type of a single- or double-precision floating-point type,
5556 // 64-bit containerized vectors or 128-bit containerized vectors with one
5557 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005558 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005559
Reid Klecknerb1be6832014-11-15 01:41:41 +00005560 Ty = useFirstFieldIfTransparentUnion(Ty);
5561
Manman Renfef9e312012-10-16 19:18:39 +00005562 // Handle illegal vector types here.
5563 if (isIllegalVectorType(Ty)) {
5564 uint64_t Size = getContext().getTypeSize(Ty);
5565 if (Size <= 32) {
5566 llvm::Type *ResType =
5567 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005568 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005569 }
5570 if (Size == 64) {
5571 llvm::Type *ResType = llvm::VectorType::get(
5572 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005573 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005574 }
5575 if (Size == 128) {
5576 llvm::Type *ResType = llvm::VectorType::get(
5577 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005578 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005579 }
John McCall7f416cc2015-09-08 08:05:57 +00005580 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005581 }
5582
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005583 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5584 // unspecified. This is not done for OpenCL as it handles the half type
5585 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005586 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005587 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5588 llvm::Type::getFloatTy(getVMContext()) :
5589 llvm::Type::getInt32Ty(getVMContext());
5590 return ABIArgInfo::getDirect(ResType);
5591 }
5592
John McCalla1dee5302010-08-22 10:59:02 +00005593 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005594 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005595 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005596 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005597 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005598
Tim Northover5a1558e2014-11-07 22:30:50 +00005599 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5600 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005601 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005602
Oliver Stannard405bded2014-02-11 09:25:50 +00005603 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005604 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005605 }
Tim Northover1060eae2013-06-21 22:49:34 +00005606
Daniel Dunbar09d33622009-09-14 21:54:03 +00005607 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005608 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005609 return ABIArgInfo::getIgnore();
5610
Tim Northover5a1558e2014-11-07 22:30:50 +00005611 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005612 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5613 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005614 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005615 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005616 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005617 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005618 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005619 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005620 }
Tim Northover5627d392015-10-30 16:30:45 +00005621 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5622 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5623 // this convention even for a variadic function: the backend will use GPRs
5624 // if needed.
5625 const Type *Base = nullptr;
5626 uint64_t Members = 0;
5627 if (isHomogeneousAggregate(Ty, Base, Members)) {
5628 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5629 llvm::Type *Ty =
5630 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5631 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5632 }
5633 }
5634
5635 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5636 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5637 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5638 // bigger than 128-bits, they get placed in space allocated by the caller,
5639 // and a pointer is passed.
5640 return ABIArgInfo::getIndirect(
5641 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005642 }
5643
Manman Ren6c30e132012-08-13 21:23:55 +00005644 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005645 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5646 // most 8-byte. We realign the indirect argument if type alignment is bigger
5647 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005648 uint64_t ABIAlign = 4;
5649 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5650 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005651 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005652 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005653
Manman Ren8cd99812012-11-06 04:58:01 +00005654 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005655 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005656 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5657 /*ByVal=*/true,
5658 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005659 }
5660
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005661 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5662 // same size and alignment.
5663 if (getTarget().isRenderScriptTarget()) {
5664 return coerceToIntArray(Ty, getContext(), getVMContext());
5665 }
5666
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005667 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005668 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005669 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005670 // FIXME: Try to match the types of the arguments more accurately where
5671 // we can.
5672 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005673 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5674 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005675 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005676 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5677 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005678 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005679
Tim Northover5a1558e2014-11-07 22:30:50 +00005680 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005681}
5682
Chris Lattner458b2aa2010-07-29 02:16:43 +00005683static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005684 llvm::LLVMContext &VMContext) {
5685 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5686 // is called integer-like if its size is less than or equal to one word, and
5687 // the offset of each of its addressable sub-fields is zero.
5688
5689 uint64_t Size = Context.getTypeSize(Ty);
5690
5691 // Check that the type fits in a word.
5692 if (Size > 32)
5693 return false;
5694
5695 // FIXME: Handle vector types!
5696 if (Ty->isVectorType())
5697 return false;
5698
Daniel Dunbard53bac72009-09-14 02:20:34 +00005699 // Float types are never treated as "integer like".
5700 if (Ty->isRealFloatingType())
5701 return false;
5702
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005703 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005704 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005705 return true;
5706
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005707 // Small complex integer types are "integer like".
5708 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5709 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005710
5711 // Single element and zero sized arrays should be allowed, by the definition
5712 // above, but they are not.
5713
5714 // Otherwise, it must be a record type.
5715 const RecordType *RT = Ty->getAs<RecordType>();
5716 if (!RT) return false;
5717
5718 // Ignore records with flexible arrays.
5719 const RecordDecl *RD = RT->getDecl();
5720 if (RD->hasFlexibleArrayMember())
5721 return false;
5722
5723 // Check that all sub-fields are at offset 0, and are themselves "integer
5724 // like".
5725 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5726
5727 bool HadField = false;
5728 unsigned idx = 0;
5729 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5730 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005731 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005732
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005733 // Bit-fields are not addressable, we only need to verify they are "integer
5734 // like". We still have to disallow a subsequent non-bitfield, for example:
5735 // struct { int : 0; int x }
5736 // is non-integer like according to gcc.
5737 if (FD->isBitField()) {
5738 if (!RD->isUnion())
5739 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005740
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005741 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5742 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005743
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005744 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005745 }
5746
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005747 // Check if this field is at offset 0.
5748 if (Layout.getFieldOffset(idx) != 0)
5749 return false;
5750
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005751 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5752 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005753
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005754 // Only allow at most one field in a structure. This doesn't match the
5755 // wording above, but follows gcc in situations with a field following an
5756 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005757 if (!RD->isUnion()) {
5758 if (HadField)
5759 return false;
5760
5761 HadField = true;
5762 }
5763 }
5764
5765 return true;
5766}
5767
Oliver Stannard405bded2014-02-11 09:25:50 +00005768ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5769 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005770 bool IsEffectivelyAAPCS_VFP =
5771 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005772
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005773 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005774 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005775
Daniel Dunbar19964db2010-09-23 01:54:32 +00005776 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005777 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005778 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005779 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005780
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005781 // __fp16 gets returned as if it were an int or float, but with the top 16
5782 // bits unspecified. This is not done for OpenCL as it handles the half type
5783 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005784 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005785 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5786 llvm::Type::getFloatTy(getVMContext()) :
5787 llvm::Type::getInt32Ty(getVMContext());
5788 return ABIArgInfo::getDirect(ResType);
5789 }
5790
John McCalla1dee5302010-08-22 10:59:02 +00005791 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005792 // Treat an enum type as its underlying type.
5793 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5794 RetTy = EnumTy->getDecl()->getIntegerType();
5795
Tim Northover5a1558e2014-11-07 22:30:50 +00005796 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5797 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005798 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005799
5800 // Are we following APCS?
5801 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005802 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005803 return ABIArgInfo::getIgnore();
5804
Daniel Dunbareedf1512010-02-01 23:31:19 +00005805 // Complex types are all returned as packed integers.
5806 //
5807 // FIXME: Consider using 2 x vector types if the back end handles them
5808 // correctly.
5809 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005810 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5811 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005812
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005813 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005814 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005815 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005816 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005817 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005818 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005819 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005820 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5821 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005822 }
5823
5824 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005825 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005826 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005827
5828 // Otherwise this is an AAPCS variant.
5829
Chris Lattner458b2aa2010-07-29 02:16:43 +00005830 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005831 return ABIArgInfo::getIgnore();
5832
Bob Wilson1d9269a2011-11-02 04:51:36 +00005833 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005834 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005835 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005836 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005837 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005838 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005839 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005840 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005841 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005842 }
5843
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005844 // Aggregates <= 4 bytes are returned in r0; other aggregates
5845 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005846 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005847 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005848 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5849 // same size and alignment.
5850 if (getTarget().isRenderScriptTarget()) {
5851 return coerceToIntArray(RetTy, getContext(), getVMContext());
5852 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005853 if (getDataLayout().isBigEndian())
5854 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005855 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005856
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005857 // Return in the smallest viable integer type.
5858 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005859 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005860 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005861 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5862 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005863 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5864 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5865 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005866 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005867 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005868 }
5869
John McCall7f416cc2015-09-08 08:05:57 +00005870 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005871}
5872
Manman Renfef9e312012-10-16 19:18:39 +00005873/// isIllegalVector - check whether Ty is an illegal vector type.
5874bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005875 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5876 if (isAndroid()) {
5877 // Android shipped using Clang 3.1, which supported a slightly different
5878 // vector ABI. The primary differences were that 3-element vector types
5879 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5880 // accepts that legacy behavior for Android only.
5881 // Check whether VT is legal.
5882 unsigned NumElements = VT->getNumElements();
5883 // NumElements should be power of 2 or equal to 3.
5884 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5885 return true;
5886 } else {
5887 // Check whether VT is legal.
5888 unsigned NumElements = VT->getNumElements();
5889 uint64_t Size = getContext().getTypeSize(VT);
5890 // NumElements should be power of 2.
5891 if (!llvm::isPowerOf2_32(NumElements))
5892 return true;
5893 // Size should be greater than 32 bits.
5894 return Size <= 32;
5895 }
Manman Renfef9e312012-10-16 19:18:39 +00005896 }
5897 return false;
5898}
5899
Reid Klecknere9f6a712014-10-31 17:10:41 +00005900bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5901 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5902 // double, or 64-bit or 128-bit vectors.
5903 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5904 if (BT->getKind() == BuiltinType::Float ||
5905 BT->getKind() == BuiltinType::Double ||
5906 BT->getKind() == BuiltinType::LongDouble)
5907 return true;
5908 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5909 unsigned VecSize = getContext().getTypeSize(VT);
5910 if (VecSize == 64 || VecSize == 128)
5911 return true;
5912 }
5913 return false;
5914}
5915
5916bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5917 uint64_t Members) const {
5918 return Members <= 4;
5919}
5920
John McCall7f416cc2015-09-08 08:05:57 +00005921Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5922 QualType Ty) const {
5923 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005924
John McCall7f416cc2015-09-08 08:05:57 +00005925 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005926 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005927 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5928 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5929 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005930 }
5931
John McCall7f416cc2015-09-08 08:05:57 +00005932 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5933 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005934
John McCall7f416cc2015-09-08 08:05:57 +00005935 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5936 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005937 const Type *Base = nullptr;
5938 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005939 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5940 IsIndirect = true;
5941
Tim Northover5627d392015-10-30 16:30:45 +00005942 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5943 // allocated by the caller.
5944 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5945 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5946 !isHomogeneousAggregate(Ty, Base, Members)) {
5947 IsIndirect = true;
5948
John McCall7f416cc2015-09-08 08:05:57 +00005949 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005950 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5951 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005952 // Our callers should be prepared to handle an under-aligned address.
5953 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5954 getABIKind() == ARMABIInfo::AAPCS) {
5955 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5956 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005957 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5958 // ARMv7k allows type alignment up to 16 bytes.
5959 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5960 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005961 } else {
5962 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005963 }
John McCall7f416cc2015-09-08 08:05:57 +00005964 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005965
John McCall7f416cc2015-09-08 08:05:57 +00005966 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5967 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005968}
5969
Chris Lattner0cf24192010-06-28 20:05:43 +00005970//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005971// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005972//===----------------------------------------------------------------------===//
5973
5974namespace {
5975
Justin Holewinski83e96682012-05-24 17:43:12 +00005976class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005977public:
Justin Holewinski36837432013-03-30 14:38:24 +00005978 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005979
5980 ABIArgInfo classifyReturnType(QualType RetTy) const;
5981 ABIArgInfo classifyArgumentType(QualType Ty) const;
5982
Craig Topper4f12f102014-03-12 06:41:41 +00005983 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005984 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5985 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005986};
5987
Justin Holewinski83e96682012-05-24 17:43:12 +00005988class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005989public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005990 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5991 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005992
Eric Christopher162c91c2015-06-05 22:03:00 +00005993 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005994 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005995private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005996 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5997 // resulting MDNode to the nvvm.annotations MDNode.
5998 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005999};
6000
Justin Holewinski83e96682012-05-24 17:43:12 +00006001ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006002 if (RetTy->isVoidType())
6003 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006004
6005 // note: this is different from default ABI
6006 if (!RetTy->isScalarType())
6007 return ABIArgInfo::getDirect();
6008
6009 // Treat an enum type as its underlying type.
6010 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6011 RetTy = EnumTy->getDecl()->getIntegerType();
6012
6013 return (RetTy->isPromotableIntegerType() ?
6014 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006015}
6016
Justin Holewinski83e96682012-05-24 17:43:12 +00006017ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006018 // Treat an enum type as its underlying type.
6019 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6020 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006021
Eli Bendersky95338a02014-10-29 13:43:21 +00006022 // Return aggregates type as indirect by value
6023 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006024 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006025
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006026 return (Ty->isPromotableIntegerType() ?
6027 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006028}
6029
Justin Holewinski83e96682012-05-24 17:43:12 +00006030void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006031 if (!getCXXABI().classifyReturnType(FI))
6032 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006033 for (auto &I : FI.arguments())
6034 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006035
6036 // Always honor user-specified calling convention.
6037 if (FI.getCallingConvention() != llvm::CallingConv::C)
6038 return;
6039
John McCall882987f2013-02-28 19:01:20 +00006040 FI.setEffectiveCallingConvention(getRuntimeCC());
6041}
6042
John McCall7f416cc2015-09-08 08:05:57 +00006043Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6044 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006045 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006046}
6047
Justin Holewinski83e96682012-05-24 17:43:12 +00006048void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00006049setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00006050 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006051 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006052 if (!FD) return;
6053
6054 llvm::Function *F = cast<llvm::Function>(GV);
6055
6056 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006057 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006058 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006059 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006060 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006061 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006062 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6063 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006064 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006065 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006066 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006067 }
Justin Holewinski38031972011-10-05 17:58:44 +00006068
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006069 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006070 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006071 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006072 // __global__ functions cannot be called from the device, we do not
6073 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006074 if (FD->hasAttr<CUDAGlobalAttr>()) {
6075 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6076 addNVVMMetadata(F, "kernel", 1);
6077 }
Artem Belevich7093e402015-04-21 22:55:54 +00006078 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006079 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006080 llvm::APSInt MaxThreads(32);
6081 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6082 if (MaxThreads > 0)
6083 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6084
6085 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6086 // not specified in __launch_bounds__ or if the user specified a 0 value,
6087 // we don't have to add a PTX directive.
6088 if (Attr->getMinBlocks()) {
6089 llvm::APSInt MinBlocks(32);
6090 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6091 if (MinBlocks > 0)
6092 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6093 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006094 }
6095 }
Justin Holewinski38031972011-10-05 17:58:44 +00006096 }
6097}
6098
Eli Benderskye06a2c42014-04-15 16:57:05 +00006099void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6100 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006101 llvm::Module *M = F->getParent();
6102 llvm::LLVMContext &Ctx = M->getContext();
6103
6104 // Get "nvvm.annotations" metadata node
6105 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6106
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006107 llvm::Metadata *MDVals[] = {
6108 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6109 llvm::ConstantAsMetadata::get(
6110 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006111 // Append metadata to nvvm.annotations
6112 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6113}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006114}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006115
6116//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006117// SystemZ ABI Implementation
6118//===----------------------------------------------------------------------===//
6119
6120namespace {
6121
Bryan Chane3f1ed52016-04-28 13:56:43 +00006122class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006123 bool HasVector;
6124
Ulrich Weigand47445072013-05-06 16:26:41 +00006125public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006126 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006127 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006128
6129 bool isPromotableIntegerType(QualType Ty) const;
6130 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006131 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006132 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006133 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006134
6135 ABIArgInfo classifyReturnType(QualType RetTy) const;
6136 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6137
Craig Topper4f12f102014-03-12 06:41:41 +00006138 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006139 if (!getCXXABI().classifyReturnType(FI))
6140 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006141 for (auto &I : FI.arguments())
6142 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006143 }
6144
John McCall7f416cc2015-09-08 08:05:57 +00006145 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6146 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006147
6148 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6149 ArrayRef<llvm::Type*> scalars,
6150 bool asReturnValue) const override {
6151 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6152 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006153 bool isSwiftErrorInRegister() const override {
6154 return true;
6155 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006156};
6157
6158class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6159public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006160 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6161 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006162};
6163
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006164}
Ulrich Weigand47445072013-05-06 16:26:41 +00006165
6166bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6167 // Treat an enum type as its underlying type.
6168 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6169 Ty = EnumTy->getDecl()->getIntegerType();
6170
6171 // Promotable integer types are required to be promoted by the ABI.
6172 if (Ty->isPromotableIntegerType())
6173 return true;
6174
6175 // 32-bit values must also be promoted.
6176 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6177 switch (BT->getKind()) {
6178 case BuiltinType::Int:
6179 case BuiltinType::UInt:
6180 return true;
6181 default:
6182 return false;
6183 }
6184 return false;
6185}
6186
6187bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006188 return (Ty->isAnyComplexType() ||
6189 Ty->isVectorType() ||
6190 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006191}
6192
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006193bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6194 return (HasVector &&
6195 Ty->isVectorType() &&
6196 getContext().getTypeSize(Ty) <= 128);
6197}
6198
Ulrich Weigand47445072013-05-06 16:26:41 +00006199bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6200 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6201 switch (BT->getKind()) {
6202 case BuiltinType::Float:
6203 case BuiltinType::Double:
6204 return true;
6205 default:
6206 return false;
6207 }
6208
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006209 return false;
6210}
6211
6212QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006213 if (const RecordType *RT = Ty->getAsStructureType()) {
6214 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006215 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006216
6217 // If this is a C++ record, check the bases first.
6218 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006219 for (const auto &I : CXXRD->bases()) {
6220 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006221
6222 // Empty bases don't affect things either way.
6223 if (isEmptyRecord(getContext(), Base, true))
6224 continue;
6225
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006226 if (!Found.isNull())
6227 return Ty;
6228 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006229 }
6230
6231 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006232 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006233 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006234 // Unlike isSingleElementStruct(), empty structure and array fields
6235 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006236 if (getContext().getLangOpts().CPlusPlus &&
6237 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6238 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006239
6240 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006241 // Nested structures still do though.
6242 if (!Found.isNull())
6243 return Ty;
6244 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006245 }
6246
6247 // Unlike isSingleElementStruct(), trailing padding is allowed.
6248 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006249 if (!Found.isNull())
6250 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006251 }
6252
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006253 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006254}
6255
John McCall7f416cc2015-09-08 08:05:57 +00006256Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6257 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006258 // Assume that va_list type is correct; should be pointer to LLVM type:
6259 // struct {
6260 // i64 __gpr;
6261 // i64 __fpr;
6262 // i8 *__overflow_arg_area;
6263 // i8 *__reg_save_area;
6264 // };
6265
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006266 // Every non-vector argument occupies 8 bytes and is passed by preference
6267 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6268 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006269 Ty = getContext().getCanonicalType(Ty);
6270 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006271 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006272 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006273 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006274 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006275 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006276 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006277 CharUnits UnpaddedSize;
6278 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006279 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006280 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6281 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006282 } else {
6283 if (AI.getCoerceToType())
6284 ArgTy = AI.getCoerceToType();
6285 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006286 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006287 UnpaddedSize = TyInfo.first;
6288 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006289 }
John McCall7f416cc2015-09-08 08:05:57 +00006290 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6291 if (IsVector && UnpaddedSize > PaddedSize)
6292 PaddedSize = CharUnits::fromQuantity(16);
6293 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006294
John McCall7f416cc2015-09-08 08:05:57 +00006295 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006296
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006297 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006298 llvm::Value *PaddedSizeV =
6299 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006300
6301 if (IsVector) {
6302 // Work out the address of a vector argument on the stack.
6303 // Vector arguments are always passed in the high bits of a
6304 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006305 Address OverflowArgAreaPtr =
6306 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006307 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006308 Address OverflowArgArea =
6309 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6310 TyInfo.second);
6311 Address MemAddr =
6312 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006313
6314 // Update overflow_arg_area_ptr pointer
6315 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006316 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6317 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006318 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6319
6320 return MemAddr;
6321 }
6322
John McCall7f416cc2015-09-08 08:05:57 +00006323 assert(PaddedSize.getQuantity() == 8);
6324
6325 unsigned MaxRegs, RegCountField, RegSaveIndex;
6326 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006327 if (InFPRs) {
6328 MaxRegs = 4; // Maximum of 4 FPR arguments
6329 RegCountField = 1; // __fpr
6330 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006331 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006332 } else {
6333 MaxRegs = 5; // Maximum of 5 GPR arguments
6334 RegCountField = 0; // __gpr
6335 RegSaveIndex = 2; // save offset for r2
6336 RegPadding = Padding; // values are passed in the low bits of a GPR
6337 }
6338
John McCall7f416cc2015-09-08 08:05:57 +00006339 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6340 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6341 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006342 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006343 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6344 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006345 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006346
6347 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6348 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6349 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6350 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6351
6352 // Emit code to load the value if it was passed in registers.
6353 CGF.EmitBlock(InRegBlock);
6354
6355 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006356 llvm::Value *ScaledRegCount =
6357 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6358 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006359 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6360 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006361 llvm::Value *RegOffset =
6362 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006363 Address RegSaveAreaPtr =
6364 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6365 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006366 llvm::Value *RegSaveArea =
6367 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006368 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6369 "raw_reg_addr"),
6370 PaddedSize);
6371 Address RegAddr =
6372 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006373
6374 // Update the register count
6375 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6376 llvm::Value *NewRegCount =
6377 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6378 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6379 CGF.EmitBranch(ContBlock);
6380
6381 // Emit code to load the value if it was passed in memory.
6382 CGF.EmitBlock(InMemBlock);
6383
6384 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006385 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6386 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6387 Address OverflowArgArea =
6388 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6389 PaddedSize);
6390 Address RawMemAddr =
6391 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6392 Address MemAddr =
6393 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006394
6395 // Update overflow_arg_area_ptr pointer
6396 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006397 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6398 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006399 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6400 CGF.EmitBranch(ContBlock);
6401
6402 // Return the appropriate result.
6403 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006404 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6405 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006406
6407 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006408 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6409 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006410
6411 return ResAddr;
6412}
6413
Ulrich Weigand47445072013-05-06 16:26:41 +00006414ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6415 if (RetTy->isVoidType())
6416 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006417 if (isVectorArgumentType(RetTy))
6418 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006419 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006420 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006421 return (isPromotableIntegerType(RetTy) ?
6422 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6423}
6424
6425ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6426 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006427 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006428 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006429
6430 // Integers and enums are extended to full register width.
6431 if (isPromotableIntegerType(Ty))
6432 return ABIArgInfo::getExtend();
6433
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006434 // Handle vector types and vector-like structure types. Note that
6435 // as opposed to float-like structure types, we do not allow any
6436 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006437 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006438 QualType SingleElementTy = GetSingleElementType(Ty);
6439 if (isVectorArgumentType(SingleElementTy) &&
6440 getContext().getTypeSize(SingleElementTy) == Size)
6441 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6442
6443 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006444 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006445 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006446
6447 // Handle small structures.
6448 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6449 // Structures with flexible arrays have variable length, so really
6450 // fail the size test above.
6451 const RecordDecl *RD = RT->getDecl();
6452 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006453 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006454
6455 // The structure is passed as an unextended integer, a float, or a double.
6456 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006457 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006458 assert(Size == 32 || Size == 64);
6459 if (Size == 32)
6460 PassTy = llvm::Type::getFloatTy(getVMContext());
6461 else
6462 PassTy = llvm::Type::getDoubleTy(getVMContext());
6463 } else
6464 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6465 return ABIArgInfo::getDirect(PassTy);
6466 }
6467
6468 // Non-structure compounds are passed indirectly.
6469 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006470 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006471
Craig Topper8a13c412014-05-21 05:09:00 +00006472 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006473}
6474
6475//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006476// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006477//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006478
6479namespace {
6480
6481class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6482public:
Chris Lattner2b037972010-07-29 02:01:43 +00006483 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6484 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006485 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006486 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006487};
6488
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006489}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006490
Eric Christopher162c91c2015-06-05 22:03:00 +00006491void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006492 llvm::GlobalValue *GV,
6493 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006494 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006495 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6496 // Handle 'interrupt' attribute:
6497 llvm::Function *F = cast<llvm::Function>(GV);
6498
6499 // Step 1: Set ISR calling convention.
6500 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6501
6502 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006503 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006504
6505 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006506 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006507 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6508 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006509 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006510 }
6511}
6512
Chris Lattner0cf24192010-06-28 20:05:43 +00006513//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006514// MIPS ABI Implementation. This works for both little-endian and
6515// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006516//===----------------------------------------------------------------------===//
6517
John McCall943fae92010-05-27 06:19:26 +00006518namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006519class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006520 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006521 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6522 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006523 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006524 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006525 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006526 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006527public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006528 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006529 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006530 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006531
6532 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006533 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006534 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006535 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6536 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006537 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006538};
6539
John McCall943fae92010-05-27 06:19:26 +00006540class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006541 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006542public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006543 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6544 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006545 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006546
Craig Topper4f12f102014-03-12 06:41:41 +00006547 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006548 return 29;
6549 }
6550
Eric Christopher162c91c2015-06-05 22:03:00 +00006551 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006552 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006553 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006554 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006555 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006556 if (FD->hasAttr<Mips16Attr>()) {
6557 Fn->addFnAttr("mips16");
6558 }
6559 else if (FD->hasAttr<NoMips16Attr>()) {
6560 Fn->addFnAttr("nomips16");
6561 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006562
6563 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6564 if (!Attr)
6565 return;
6566
6567 const char *Kind;
6568 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006569 case MipsInterruptAttr::eic: Kind = "eic"; break;
6570 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6571 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6572 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6573 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6574 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6575 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6576 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6577 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6578 }
6579
6580 Fn->addFnAttr("interrupt", Kind);
6581
Reed Kotler373feca2013-01-16 17:10:28 +00006582 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006583
John McCall943fae92010-05-27 06:19:26 +00006584 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006585 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006586
Craig Topper4f12f102014-03-12 06:41:41 +00006587 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006588 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006589 }
John McCall943fae92010-05-27 06:19:26 +00006590};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006591}
John McCall943fae92010-05-27 06:19:26 +00006592
Eric Christopher7565e0d2015-05-29 23:09:49 +00006593void MipsABIInfo::CoerceToIntArgs(
6594 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006595 llvm::IntegerType *IntTy =
6596 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006597
6598 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6599 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6600 ArgList.push_back(IntTy);
6601
6602 // If necessary, add one more integer type to ArgList.
6603 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6604
6605 if (R)
6606 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006607}
6608
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006609// In N32/64, an aligned double precision floating point field is passed in
6610// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006611llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006612 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6613
6614 if (IsO32) {
6615 CoerceToIntArgs(TySize, ArgList);
6616 return llvm::StructType::get(getVMContext(), ArgList);
6617 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006618
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006619 if (Ty->isComplexType())
6620 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006621
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006622 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006623
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006624 // Unions/vectors are passed in integer registers.
6625 if (!RT || !RT->isStructureOrClassType()) {
6626 CoerceToIntArgs(TySize, ArgList);
6627 return llvm::StructType::get(getVMContext(), ArgList);
6628 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006629
6630 const RecordDecl *RD = RT->getDecl();
6631 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006632 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006633
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006634 uint64_t LastOffset = 0;
6635 unsigned idx = 0;
6636 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6637
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006638 // Iterate over fields in the struct/class and check if there are any aligned
6639 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006640 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6641 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006642 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006643 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6644
6645 if (!BT || BT->getKind() != BuiltinType::Double)
6646 continue;
6647
6648 uint64_t Offset = Layout.getFieldOffset(idx);
6649 if (Offset % 64) // Ignore doubles that are not aligned.
6650 continue;
6651
6652 // Add ((Offset - LastOffset) / 64) args of type i64.
6653 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6654 ArgList.push_back(I64);
6655
6656 // Add double type.
6657 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6658 LastOffset = Offset + 64;
6659 }
6660
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006661 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6662 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006663
6664 return llvm::StructType::get(getVMContext(), ArgList);
6665}
6666
Akira Hatanakaddd66342013-10-29 18:41:15 +00006667llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6668 uint64_t Offset) const {
6669 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006670 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006671
Akira Hatanakaddd66342013-10-29 18:41:15 +00006672 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006673}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006674
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006675ABIArgInfo
6676MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006677 Ty = useFirstFieldIfTransparentUnion(Ty);
6678
Akira Hatanaka1632af62012-01-09 19:31:25 +00006679 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006680 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006681 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006682
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006683 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6684 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006685 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6686 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006687
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006688 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006689 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006690 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006691 return ABIArgInfo::getIgnore();
6692
Mark Lacey3825e832013-10-06 01:33:34 +00006693 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006694 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006695 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006696 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006697
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006698 // If we have reached here, aggregates are passed directly by coercing to
6699 // another structure type. Padding is inserted if the offset of the
6700 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006701 ABIArgInfo ArgInfo =
6702 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6703 getPaddingType(OrigOffset, CurrOffset));
6704 ArgInfo.setInReg(true);
6705 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006706 }
6707
6708 // Treat an enum type as its underlying type.
6709 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6710 Ty = EnumTy->getDecl()->getIntegerType();
6711
Daniel Sanders5b445b32014-10-24 14:42:42 +00006712 // All integral types are promoted to the GPR width.
6713 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006714 return ABIArgInfo::getExtend();
6715
Akira Hatanakaddd66342013-10-29 18:41:15 +00006716 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006717 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006718}
6719
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006720llvm::Type*
6721MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006722 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006723 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006724
Akira Hatanakab6f74432012-02-09 18:49:26 +00006725 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006726 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006727 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6728 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006729
Akira Hatanakab6f74432012-02-09 18:49:26 +00006730 // N32/64 returns struct/classes in floating point registers if the
6731 // following conditions are met:
6732 // 1. The size of the struct/class is no larger than 128-bit.
6733 // 2. The struct/class has one or two fields all of which are floating
6734 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006735 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006736 //
6737 // Any other composite results are returned in integer registers.
6738 //
6739 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6740 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6741 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006742 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006743
Akira Hatanakab6f74432012-02-09 18:49:26 +00006744 if (!BT || !BT->isFloatingPoint())
6745 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006746
David Blaikie2d7c57e2012-04-30 02:36:29 +00006747 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006748 }
6749
6750 if (b == e)
6751 return llvm::StructType::get(getVMContext(), RTList,
6752 RD->hasAttr<PackedAttr>());
6753
6754 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006755 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006756 }
6757
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006758 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006759 return llvm::StructType::get(getVMContext(), RTList);
6760}
6761
Akira Hatanakab579fe52011-06-02 00:09:17 +00006762ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006763 uint64_t Size = getContext().getTypeSize(RetTy);
6764
Daniel Sandersed39f582014-09-04 13:28:14 +00006765 if (RetTy->isVoidType())
6766 return ABIArgInfo::getIgnore();
6767
6768 // O32 doesn't treat zero-sized structs differently from other structs.
6769 // However, N32/N64 ignores zero sized return values.
6770 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006771 return ABIArgInfo::getIgnore();
6772
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006773 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006774 if (Size <= 128) {
6775 if (RetTy->isAnyComplexType())
6776 return ABIArgInfo::getDirect();
6777
Daniel Sanderse5018b62014-09-04 15:05:39 +00006778 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006779 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006780 if (!IsO32 ||
6781 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6782 ABIArgInfo ArgInfo =
6783 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6784 ArgInfo.setInReg(true);
6785 return ArgInfo;
6786 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006787 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006788
John McCall7f416cc2015-09-08 08:05:57 +00006789 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006790 }
6791
6792 // Treat an enum type as its underlying type.
6793 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6794 RetTy = EnumTy->getDecl()->getIntegerType();
6795
6796 return (RetTy->isPromotableIntegerType() ?
6797 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6798}
6799
6800void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006801 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006802 if (!getCXXABI().classifyReturnType(FI))
6803 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006804
Eric Christopher7565e0d2015-05-29 23:09:49 +00006805 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006806 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006807
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006808 for (auto &I : FI.arguments())
6809 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006810}
6811
John McCall7f416cc2015-09-08 08:05:57 +00006812Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6813 QualType OrigTy) const {
6814 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006815
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006816 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6817 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006818 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006819 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006820 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006821 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006822 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006823 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006824 DidPromote = true;
6825 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6826 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006827 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006828
John McCall7f416cc2015-09-08 08:05:57 +00006829 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006830
John McCall7f416cc2015-09-08 08:05:57 +00006831 // The alignment of things in the argument area is never larger than
6832 // StackAlignInBytes.
6833 TyInfo.second =
6834 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6835
6836 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6837 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6838
6839 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6840 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6841
6842
6843 // If there was a promotion, "unpromote" into a temporary.
6844 // TODO: can we just use a pointer into a subset of the original slot?
6845 if (DidPromote) {
6846 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6847 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6848
6849 // Truncate down to the right width.
6850 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6851 : CGF.IntPtrTy);
6852 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6853 if (OrigTy->isPointerType())
6854 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6855
6856 CGF.Builder.CreateStore(V, Temp);
6857 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006858 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006859
John McCall7f416cc2015-09-08 08:05:57 +00006860 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006861}
6862
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006863bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6864 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006865
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006866 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6867 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6868 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006869
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006870 return false;
6871}
6872
John McCall943fae92010-05-27 06:19:26 +00006873bool
6874MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6875 llvm::Value *Address) const {
6876 // This information comes from gcc's implementation, which seems to
6877 // as canonical as it gets.
6878
John McCall943fae92010-05-27 06:19:26 +00006879 // Everything on MIPS is 4 bytes. Double-precision FP registers
6880 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006881 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006882
6883 // 0-31 are the general purpose registers, $0 - $31.
6884 // 32-63 are the floating-point registers, $f0 - $f31.
6885 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6886 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006887 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006888
6889 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6890 // They are one bit wide and ignored here.
6891
6892 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6893 // (coprocessor 1 is the FP unit)
6894 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6895 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6896 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006897 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006898 return false;
6899}
6900
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006901//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00006902// AVR ABI Implementation.
6903//===----------------------------------------------------------------------===//
6904
6905namespace {
6906class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6907public:
6908 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6909 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6910
6911 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6912 CodeGen::CodeGenModule &CGM) const override {
6913 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6914 if (!FD) return;
6915 auto *Fn = cast<llvm::Function>(GV);
6916
6917 if (FD->getAttr<AVRInterruptAttr>())
6918 Fn->addFnAttr("interrupt");
6919
6920 if (FD->getAttr<AVRSignalAttr>())
6921 Fn->addFnAttr("signal");
6922 }
6923};
6924}
6925
6926//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006927// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006928// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006929// handling.
6930//===----------------------------------------------------------------------===//
6931
6932namespace {
6933
6934class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6935public:
6936 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6937 : DefaultTargetCodeGenInfo(CGT) {}
6938
Eric Christopher162c91c2015-06-05 22:03:00 +00006939 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006940 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006941};
6942
Eric Christopher162c91c2015-06-05 22:03:00 +00006943void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006944 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006945 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006946 if (!FD) return;
6947
6948 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006949
David Blaikiebbafb8a2012-03-11 07:00:24 +00006950 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006951 if (FD->hasAttr<OpenCLKernelAttr>()) {
6952 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006953 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006954 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6955 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006956 // Convert the reqd_work_group_size() attributes to metadata.
6957 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006958 llvm::NamedMDNode *OpenCLMetadata =
6959 M.getModule().getOrInsertNamedMetadata(
6960 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006961
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006962 SmallVector<llvm::Metadata *, 5> Operands;
6963 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006964
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006965 Operands.push_back(
6966 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6967 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6968 Operands.push_back(
6969 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6970 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6971 Operands.push_back(
6972 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6973 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006974
Eric Christopher7565e0d2015-05-29 23:09:49 +00006975 // Add a boolean constant operand for "required" (true) or "hint"
6976 // (false) for implementing the work_group_size_hint attr later.
6977 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006978 Operands.push_back(
6979 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006980 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6981 }
6982 }
6983 }
6984}
6985
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006986}
John McCall943fae92010-05-27 06:19:26 +00006987
Tony Linthicum76329bf2011-12-12 21:14:55 +00006988//===----------------------------------------------------------------------===//
6989// Hexagon ABI Implementation
6990//===----------------------------------------------------------------------===//
6991
6992namespace {
6993
6994class HexagonABIInfo : public ABIInfo {
6995
6996
6997public:
6998 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6999
7000private:
7001
7002 ABIArgInfo classifyReturnType(QualType RetTy) const;
7003 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7004
Craig Topper4f12f102014-03-12 06:41:41 +00007005 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007006
John McCall7f416cc2015-09-08 08:05:57 +00007007 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7008 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007009};
7010
7011class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7012public:
7013 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7014 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7015
Craig Topper4f12f102014-03-12 06:41:41 +00007016 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007017 return 29;
7018 }
7019};
7020
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007021}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007022
7023void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007024 if (!getCXXABI().classifyReturnType(FI))
7025 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007026 for (auto &I : FI.arguments())
7027 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007028}
7029
7030ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7031 if (!isAggregateTypeForABI(Ty)) {
7032 // Treat an enum type as its underlying type.
7033 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7034 Ty = EnumTy->getDecl()->getIntegerType();
7035
7036 return (Ty->isPromotableIntegerType() ?
7037 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7038 }
7039
7040 // Ignore empty records.
7041 if (isEmptyRecord(getContext(), Ty, true))
7042 return ABIArgInfo::getIgnore();
7043
Mark Lacey3825e832013-10-06 01:33:34 +00007044 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007045 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007046
7047 uint64_t Size = getContext().getTypeSize(Ty);
7048 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007049 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007050 // Pass in the smallest viable integer type.
7051 else if (Size > 32)
7052 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7053 else if (Size > 16)
7054 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7055 else if (Size > 8)
7056 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7057 else
7058 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7059}
7060
7061ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7062 if (RetTy->isVoidType())
7063 return ABIArgInfo::getIgnore();
7064
7065 // Large vector types should be returned via memory.
7066 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007067 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007068
7069 if (!isAggregateTypeForABI(RetTy)) {
7070 // Treat an enum type as its underlying type.
7071 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7072 RetTy = EnumTy->getDecl()->getIntegerType();
7073
7074 return (RetTy->isPromotableIntegerType() ?
7075 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7076 }
7077
Tony Linthicum76329bf2011-12-12 21:14:55 +00007078 if (isEmptyRecord(getContext(), RetTy, true))
7079 return ABIArgInfo::getIgnore();
7080
7081 // Aggregates <= 8 bytes are returned in r0; other aggregates
7082 // are returned indirectly.
7083 uint64_t Size = getContext().getTypeSize(RetTy);
7084 if (Size <= 64) {
7085 // Return in the smallest viable integer type.
7086 if (Size <= 8)
7087 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7088 if (Size <= 16)
7089 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7090 if (Size <= 32)
7091 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7092 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7093 }
7094
John McCall7f416cc2015-09-08 08:05:57 +00007095 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007096}
7097
John McCall7f416cc2015-09-08 08:05:57 +00007098Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7099 QualType Ty) const {
7100 // FIXME: Someone needs to audit that this handle alignment correctly.
7101 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7102 getContext().getTypeInfoInChars(Ty),
7103 CharUnits::fromQuantity(4),
7104 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007105}
7106
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007107//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007108// Lanai ABI Implementation
7109//===----------------------------------------------------------------------===//
7110
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007111namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007112class LanaiABIInfo : public DefaultABIInfo {
7113public:
7114 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7115
7116 bool shouldUseInReg(QualType Ty, CCState &State) const;
7117
7118 void computeInfo(CGFunctionInfo &FI) const override {
7119 CCState State(FI.getCallingConvention());
7120 // Lanai uses 4 registers to pass arguments unless the function has the
7121 // regparm attribute set.
7122 if (FI.getHasRegParm()) {
7123 State.FreeRegs = FI.getRegParm();
7124 } else {
7125 State.FreeRegs = 4;
7126 }
7127
7128 if (!getCXXABI().classifyReturnType(FI))
7129 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7130 for (auto &I : FI.arguments())
7131 I.info = classifyArgumentType(I.type, State);
7132 }
7133
Jacques Pienaare74d9132016-04-26 00:09:29 +00007134 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007135 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7136};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007137} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007138
7139bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7140 unsigned Size = getContext().getTypeSize(Ty);
7141 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7142
7143 if (SizeInRegs == 0)
7144 return false;
7145
7146 if (SizeInRegs > State.FreeRegs) {
7147 State.FreeRegs = 0;
7148 return false;
7149 }
7150
7151 State.FreeRegs -= SizeInRegs;
7152
7153 return true;
7154}
7155
Jacques Pienaare74d9132016-04-26 00:09:29 +00007156ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7157 CCState &State) const {
7158 if (!ByVal) {
7159 if (State.FreeRegs) {
7160 --State.FreeRegs; // Non-byval indirects just use one pointer.
7161 return getNaturalAlignIndirectInReg(Ty);
7162 }
7163 return getNaturalAlignIndirect(Ty, false);
7164 }
7165
7166 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007167 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007168 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7169 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7170 /*Realign=*/TypeAlign >
7171 MinABIStackAlignInBytes);
7172}
7173
Jacques Pienaard964cc22016-03-28 21:02:54 +00007174ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7175 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007176 // Check with the C++ ABI first.
7177 const RecordType *RT = Ty->getAs<RecordType>();
7178 if (RT) {
7179 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7180 if (RAA == CGCXXABI::RAA_Indirect) {
7181 return getIndirectResult(Ty, /*ByVal=*/false, State);
7182 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7183 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7184 }
7185 }
7186
7187 if (isAggregateTypeForABI(Ty)) {
7188 // Structures with flexible arrays are always indirect.
7189 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7190 return getIndirectResult(Ty, /*ByVal=*/true, State);
7191
7192 // Ignore empty structs/unions.
7193 if (isEmptyRecord(getContext(), Ty, true))
7194 return ABIArgInfo::getIgnore();
7195
7196 llvm::LLVMContext &LLVMContext = getVMContext();
7197 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7198 if (SizeInRegs <= State.FreeRegs) {
7199 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7200 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7201 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7202 State.FreeRegs -= SizeInRegs;
7203 return ABIArgInfo::getDirectInReg(Result);
7204 } else {
7205 State.FreeRegs = 0;
7206 }
7207 return getIndirectResult(Ty, true, State);
7208 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007209
7210 // Treat an enum type as its underlying type.
7211 if (const auto *EnumTy = Ty->getAs<EnumType>())
7212 Ty = EnumTy->getDecl()->getIntegerType();
7213
Jacques Pienaare74d9132016-04-26 00:09:29 +00007214 bool InReg = shouldUseInReg(Ty, State);
7215 if (Ty->isPromotableIntegerType()) {
7216 if (InReg)
7217 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007218 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007219 }
7220 if (InReg)
7221 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007222 return ABIArgInfo::getDirect();
7223}
7224
7225namespace {
7226class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7227public:
7228 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7229 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7230};
7231}
7232
7233//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007234// AMDGPU ABI Implementation
7235//===----------------------------------------------------------------------===//
7236
7237namespace {
7238
Matt Arsenault88d7da02016-08-22 19:25:59 +00007239class AMDGPUABIInfo final : public DefaultABIInfo {
7240public:
7241 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7242
7243private:
7244 ABIArgInfo classifyArgumentType(QualType Ty) const;
7245
7246 void computeInfo(CGFunctionInfo &FI) const override;
7247};
7248
7249void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7250 if (!getCXXABI().classifyReturnType(FI))
7251 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7252
7253 unsigned CC = FI.getCallingConvention();
7254 for (auto &Arg : FI.arguments())
7255 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7256 Arg.info = classifyArgumentType(Arg.type);
7257 else
7258 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7259}
7260
7261/// \brief Classify argument of given type \p Ty.
7262ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7263 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7264 if (!StrTy) {
7265 return DefaultABIInfo::classifyArgumentType(Ty);
7266 }
7267
7268 // Coerce single element structs to its element.
7269 if (StrTy->getNumElements() == 1) {
7270 return ABIArgInfo::getDirect();
7271 }
7272
7273 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7274 // individual elements, which confuses the Clover OpenCL backend; therefore we
7275 // have to set it to false here. Other args of getDirect() are just defaults.
7276 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7277}
7278
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007279class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7280public:
7281 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007282 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007283 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007284 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007285 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007286
Yaxun Liu402804b2016-12-15 08:09:08 +00007287 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7288 llvm::PointerType *T, QualType QT) const override;
7289};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007290}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007291
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007292static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7293
Eric Christopher162c91c2015-06-05 22:03:00 +00007294void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007295 const Decl *D,
7296 llvm::GlobalValue *GV,
7297 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007298 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007299 if (!FD)
7300 return;
7301
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007302 llvm::Function *F = cast<llvm::Function>(GV);
7303
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007304 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7305 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7306 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7307 if (ReqdWGS || FlatWGS) {
7308 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7309 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7310 if (ReqdWGS && Min == 0 && Max == 0)
7311 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007312
7313 if (Min != 0) {
7314 assert(Min <= Max && "Min must be less than or equal Max");
7315
7316 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7317 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7318 } else
7319 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007320 }
7321
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007322 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7323 unsigned Min = Attr->getMin();
7324 unsigned Max = Attr->getMax();
7325
7326 if (Min != 0) {
7327 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7328
7329 std::string AttrVal = llvm::utostr(Min);
7330 if (Max != 0)
7331 AttrVal = AttrVal + "," + llvm::utostr(Max);
7332 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7333 } else
7334 assert(Max == 0 && "Max must be zero");
7335 }
7336
7337 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007338 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007339
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007340 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007341 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7342 }
7343
7344 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7345 uint32_t NumVGPR = Attr->getNumVGPR();
7346
7347 if (NumVGPR != 0)
7348 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007349 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007350
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007351 appendOpenCLVersionMD(M);
7352}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007353
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007354unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7355 return llvm::CallingConv::AMDGPU_KERNEL;
7356}
7357
Yaxun Liu402804b2016-12-15 08:09:08 +00007358// Currently LLVM assumes null pointers always have value 0,
7359// which results in incorrectly transformed IR. Therefore, instead of
7360// emitting null pointers in private and local address spaces, a null
7361// pointer in generic address space is emitted which is casted to a
7362// pointer in local or private address space.
7363llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7364 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7365 QualType QT) const {
7366 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7367 return llvm::ConstantPointerNull::get(PT);
7368
7369 auto &Ctx = CGM.getContext();
7370 auto NPT = llvm::PointerType::get(PT->getElementType(),
7371 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7372 return llvm::ConstantExpr::getAddrSpaceCast(
7373 llvm::ConstantPointerNull::get(NPT), PT);
7374}
7375
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007376//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007377// SPARC v8 ABI Implementation.
7378// Based on the SPARC Compliance Definition version 2.4.1.
7379//
7380// Ensures that complex values are passed in registers.
7381//
7382namespace {
7383class SparcV8ABIInfo : public DefaultABIInfo {
7384public:
7385 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7386
7387private:
7388 ABIArgInfo classifyReturnType(QualType RetTy) const;
7389 void computeInfo(CGFunctionInfo &FI) const override;
7390};
7391} // end anonymous namespace
7392
7393
7394ABIArgInfo
7395SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7396 if (Ty->isAnyComplexType()) {
7397 return ABIArgInfo::getDirect();
7398 }
7399 else {
7400 return DefaultABIInfo::classifyReturnType(Ty);
7401 }
7402}
7403
7404void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7405
7406 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7407 for (auto &Arg : FI.arguments())
7408 Arg.info = classifyArgumentType(Arg.type);
7409}
7410
7411namespace {
7412class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7413public:
7414 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7415 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7416};
7417} // end anonymous namespace
7418
7419//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007420// SPARC v9 ABI Implementation.
7421// Based on the SPARC Compliance Definition version 2.4.1.
7422//
7423// Function arguments a mapped to a nominal "parameter array" and promoted to
7424// registers depending on their type. Each argument occupies 8 or 16 bytes in
7425// the array, structs larger than 16 bytes are passed indirectly.
7426//
7427// One case requires special care:
7428//
7429// struct mixed {
7430// int i;
7431// float f;
7432// };
7433//
7434// When a struct mixed is passed by value, it only occupies 8 bytes in the
7435// parameter array, but the int is passed in an integer register, and the float
7436// is passed in a floating point register. This is represented as two arguments
7437// with the LLVM IR inreg attribute:
7438//
7439// declare void f(i32 inreg %i, float inreg %f)
7440//
7441// The code generator will only allocate 4 bytes from the parameter array for
7442// the inreg arguments. All other arguments are allocated a multiple of 8
7443// bytes.
7444//
7445namespace {
7446class SparcV9ABIInfo : public ABIInfo {
7447public:
7448 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7449
7450private:
7451 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007452 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007453 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7454 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007455
7456 // Coercion type builder for structs passed in registers. The coercion type
7457 // serves two purposes:
7458 //
7459 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7460 // in registers.
7461 // 2. Expose aligned floating point elements as first-level elements, so the
7462 // code generator knows to pass them in floating point registers.
7463 //
7464 // We also compute the InReg flag which indicates that the struct contains
7465 // aligned 32-bit floats.
7466 //
7467 struct CoerceBuilder {
7468 llvm::LLVMContext &Context;
7469 const llvm::DataLayout &DL;
7470 SmallVector<llvm::Type*, 8> Elems;
7471 uint64_t Size;
7472 bool InReg;
7473
7474 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7475 : Context(c), DL(dl), Size(0), InReg(false) {}
7476
7477 // Pad Elems with integers until Size is ToSize.
7478 void pad(uint64_t ToSize) {
7479 assert(ToSize >= Size && "Cannot remove elements");
7480 if (ToSize == Size)
7481 return;
7482
7483 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007484 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007485 if (Aligned > Size && Aligned <= ToSize) {
7486 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7487 Size = Aligned;
7488 }
7489
7490 // Add whole 64-bit words.
7491 while (Size + 64 <= ToSize) {
7492 Elems.push_back(llvm::Type::getInt64Ty(Context));
7493 Size += 64;
7494 }
7495
7496 // Final in-word padding.
7497 if (Size < ToSize) {
7498 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7499 Size = ToSize;
7500 }
7501 }
7502
7503 // Add a floating point element at Offset.
7504 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7505 // Unaligned floats are treated as integers.
7506 if (Offset % Bits)
7507 return;
7508 // The InReg flag is only required if there are any floats < 64 bits.
7509 if (Bits < 64)
7510 InReg = true;
7511 pad(Offset);
7512 Elems.push_back(Ty);
7513 Size = Offset + Bits;
7514 }
7515
7516 // Add a struct type to the coercion type, starting at Offset (in bits).
7517 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7518 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7519 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7520 llvm::Type *ElemTy = StrTy->getElementType(i);
7521 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7522 switch (ElemTy->getTypeID()) {
7523 case llvm::Type::StructTyID:
7524 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7525 break;
7526 case llvm::Type::FloatTyID:
7527 addFloat(ElemOffset, ElemTy, 32);
7528 break;
7529 case llvm::Type::DoubleTyID:
7530 addFloat(ElemOffset, ElemTy, 64);
7531 break;
7532 case llvm::Type::FP128TyID:
7533 addFloat(ElemOffset, ElemTy, 128);
7534 break;
7535 case llvm::Type::PointerTyID:
7536 if (ElemOffset % 64 == 0) {
7537 pad(ElemOffset);
7538 Elems.push_back(ElemTy);
7539 Size += 64;
7540 }
7541 break;
7542 default:
7543 break;
7544 }
7545 }
7546 }
7547
7548 // Check if Ty is a usable substitute for the coercion type.
7549 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007550 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007551 }
7552
7553 // Get the coercion type as a literal struct type.
7554 llvm::Type *getType() const {
7555 if (Elems.size() == 1)
7556 return Elems.front();
7557 else
7558 return llvm::StructType::get(Context, Elems);
7559 }
7560 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007561};
7562} // end anonymous namespace
7563
7564ABIArgInfo
7565SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7566 if (Ty->isVoidType())
7567 return ABIArgInfo::getIgnore();
7568
7569 uint64_t Size = getContext().getTypeSize(Ty);
7570
7571 // Anything too big to fit in registers is passed with an explicit indirect
7572 // pointer / sret pointer.
7573 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007574 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007575
7576 // Treat an enum type as its underlying type.
7577 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7578 Ty = EnumTy->getDecl()->getIntegerType();
7579
7580 // Integer types smaller than a register are extended.
7581 if (Size < 64 && Ty->isIntegerType())
7582 return ABIArgInfo::getExtend();
7583
7584 // Other non-aggregates go in registers.
7585 if (!isAggregateTypeForABI(Ty))
7586 return ABIArgInfo::getDirect();
7587
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007588 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7589 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7590 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007591 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007592
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007593 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007594 // Build a coercion type from the LLVM struct type.
7595 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7596 if (!StrTy)
7597 return ABIArgInfo::getDirect();
7598
7599 CoerceBuilder CB(getVMContext(), getDataLayout());
7600 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007601 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007602
7603 // Try to use the original type for coercion.
7604 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7605
7606 if (CB.InReg)
7607 return ABIArgInfo::getDirectInReg(CoerceTy);
7608 else
7609 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007610}
7611
John McCall7f416cc2015-09-08 08:05:57 +00007612Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7613 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007614 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7615 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7616 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7617 AI.setCoerceToType(ArgTy);
7618
John McCall7f416cc2015-09-08 08:05:57 +00007619 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007620
John McCall7f416cc2015-09-08 08:05:57 +00007621 CGBuilderTy &Builder = CGF.Builder;
7622 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7623 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7624
7625 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7626
7627 Address ArgAddr = Address::invalid();
7628 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007629 switch (AI.getKind()) {
7630 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007631 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007632 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007633 llvm_unreachable("Unsupported ABI kind for va_arg");
7634
John McCall7f416cc2015-09-08 08:05:57 +00007635 case ABIArgInfo::Extend: {
7636 Stride = SlotSize;
7637 CharUnits Offset = SlotSize - TypeInfo.first;
7638 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007639 break;
John McCall7f416cc2015-09-08 08:05:57 +00007640 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007641
John McCall7f416cc2015-09-08 08:05:57 +00007642 case ABIArgInfo::Direct: {
7643 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007644 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007645 ArgAddr = Addr;
7646 break;
John McCall7f416cc2015-09-08 08:05:57 +00007647 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007648
7649 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007650 Stride = SlotSize;
7651 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7652 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7653 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007654 break;
7655
7656 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007657 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007658 }
7659
7660 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007661 llvm::Value *NextPtr =
7662 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7663 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007664
John McCall7f416cc2015-09-08 08:05:57 +00007665 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007666}
7667
7668void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7669 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007670 for (auto &I : FI.arguments())
7671 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007672}
7673
7674namespace {
7675class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7676public:
7677 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7678 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007679
Craig Topper4f12f102014-03-12 06:41:41 +00007680 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007681 return 14;
7682 }
7683
7684 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007685 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007686};
7687} // end anonymous namespace
7688
Roman Divackyf02c9942014-02-24 18:46:27 +00007689bool
7690SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7691 llvm::Value *Address) const {
7692 // This is calculated from the LLVM and GCC tables and verified
7693 // against gcc output. AFAIK all ABIs use the same encoding.
7694
7695 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7696
7697 llvm::IntegerType *i8 = CGF.Int8Ty;
7698 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7699 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7700
7701 // 0-31: the 8-byte general-purpose registers
7702 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7703
7704 // 32-63: f0-31, the 4-byte floating-point registers
7705 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7706
7707 // Y = 64
7708 // PSR = 65
7709 // WIM = 66
7710 // TBR = 67
7711 // PC = 68
7712 // NPC = 69
7713 // FSR = 70
7714 // CSR = 71
7715 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007716
Roman Divackyf02c9942014-02-24 18:46:27 +00007717 // 72-87: d0-15, the 8-byte floating-point registers
7718 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7719
7720 return false;
7721}
7722
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007723
Robert Lytton0e076492013-08-13 09:43:10 +00007724//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007725// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007726//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007727
Robert Lytton0e076492013-08-13 09:43:10 +00007728namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007729
7730/// A SmallStringEnc instance is used to build up the TypeString by passing
7731/// it by reference between functions that append to it.
7732typedef llvm::SmallString<128> SmallStringEnc;
7733
7734/// TypeStringCache caches the meta encodings of Types.
7735///
7736/// The reason for caching TypeStrings is two fold:
7737/// 1. To cache a type's encoding for later uses;
7738/// 2. As a means to break recursive member type inclusion.
7739///
7740/// A cache Entry can have a Status of:
7741/// NonRecursive: The type encoding is not recursive;
7742/// Recursive: The type encoding is recursive;
7743/// Incomplete: An incomplete TypeString;
7744/// IncompleteUsed: An incomplete TypeString that has been used in a
7745/// Recursive type encoding.
7746///
7747/// A NonRecursive entry will have all of its sub-members expanded as fully
7748/// as possible. Whilst it may contain types which are recursive, the type
7749/// itself is not recursive and thus its encoding may be safely used whenever
7750/// the type is encountered.
7751///
7752/// A Recursive entry will have all of its sub-members expanded as fully as
7753/// possible. The type itself is recursive and it may contain other types which
7754/// are recursive. The Recursive encoding must not be used during the expansion
7755/// of a recursive type's recursive branch. For simplicity the code uses
7756/// IncompleteCount to reject all usage of Recursive encodings for member types.
7757///
7758/// An Incomplete entry is always a RecordType and only encodes its
7759/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7760/// are placed into the cache during type expansion as a means to identify and
7761/// handle recursive inclusion of types as sub-members. If there is recursion
7762/// the entry becomes IncompleteUsed.
7763///
7764/// During the expansion of a RecordType's members:
7765///
7766/// If the cache contains a NonRecursive encoding for the member type, the
7767/// cached encoding is used;
7768///
7769/// If the cache contains a Recursive encoding for the member type, the
7770/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7771///
7772/// If the member is a RecordType, an Incomplete encoding is placed into the
7773/// cache to break potential recursive inclusion of itself as a sub-member;
7774///
7775/// Once a member RecordType has been expanded, its temporary incomplete
7776/// entry is removed from the cache. If a Recursive encoding was swapped out
7777/// it is swapped back in;
7778///
7779/// If an incomplete entry is used to expand a sub-member, the incomplete
7780/// entry is marked as IncompleteUsed. The cache keeps count of how many
7781/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7782///
7783/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7784/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7785/// Else the member is part of a recursive type and thus the recursion has
7786/// been exited too soon for the encoding to be correct for the member.
7787///
7788class TypeStringCache {
7789 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7790 struct Entry {
7791 std::string Str; // The encoded TypeString for the type.
7792 enum Status State; // Information about the encoding in 'Str'.
7793 std::string Swapped; // A temporary place holder for a Recursive encoding
7794 // during the expansion of RecordType's members.
7795 };
7796 std::map<const IdentifierInfo *, struct Entry> Map;
7797 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7798 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7799public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007800 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007801 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7802 bool removeIncomplete(const IdentifierInfo *ID);
7803 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7804 bool IsRecursive);
7805 StringRef lookupStr(const IdentifierInfo *ID);
7806};
7807
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007808/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007809/// FieldEncoding is a helper for this ordering process.
7810class FieldEncoding {
7811 bool HasName;
7812 std::string Enc;
7813public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007814 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007815 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007816 bool operator<(const FieldEncoding &rhs) const {
7817 if (HasName != rhs.HasName) return HasName;
7818 return Enc < rhs.Enc;
7819 }
7820};
7821
Robert Lytton7d1db152013-08-19 09:46:39 +00007822class XCoreABIInfo : public DefaultABIInfo {
7823public:
7824 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007825 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7826 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007827};
7828
Robert Lyttond21e2d72014-03-03 13:45:29 +00007829class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007830 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007831public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007832 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007833 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007834 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7835 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007836};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007837
Robert Lytton2d196952013-10-11 10:29:34 +00007838} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007839
James Y Knight29b5f082016-02-24 02:59:33 +00007840// TODO: this implementation is likely now redundant with the default
7841// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007842Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7843 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007844 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007845
Robert Lytton2d196952013-10-11 10:29:34 +00007846 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007847 CharUnits SlotSize = CharUnits::fromQuantity(4);
7848 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007849
Robert Lytton2d196952013-10-11 10:29:34 +00007850 // Handle the argument.
7851 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007852 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007853 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7854 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7855 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007856 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007857
7858 Address Val = Address::invalid();
7859 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007860 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007861 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007862 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007863 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007864 llvm_unreachable("Unsupported ABI kind for va_arg");
7865 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007866 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7867 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007868 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007869 case ABIArgInfo::Extend:
7870 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007871 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7872 ArgSize = CharUnits::fromQuantity(
7873 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007874 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007875 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007876 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007877 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7878 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7879 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007880 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007881 }
Robert Lytton2d196952013-10-11 10:29:34 +00007882
7883 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007884 if (!ArgSize.isZero()) {
7885 llvm::Value *APN =
7886 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7887 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007888 }
John McCall7f416cc2015-09-08 08:05:57 +00007889
Robert Lytton2d196952013-10-11 10:29:34 +00007890 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007891}
Robert Lytton0e076492013-08-13 09:43:10 +00007892
Robert Lytton844aeeb2014-05-02 09:33:20 +00007893/// During the expansion of a RecordType, an incomplete TypeString is placed
7894/// into the cache as a means to identify and break recursion.
7895/// If there is a Recursive encoding in the cache, it is swapped out and will
7896/// be reinserted by removeIncomplete().
7897/// All other types of encoding should have been used rather than arriving here.
7898void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7899 std::string StubEnc) {
7900 if (!ID)
7901 return;
7902 Entry &E = Map[ID];
7903 assert( (E.Str.empty() || E.State == Recursive) &&
7904 "Incorrectly use of addIncomplete");
7905 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7906 E.Swapped.swap(E.Str); // swap out the Recursive
7907 E.Str.swap(StubEnc);
7908 E.State = Incomplete;
7909 ++IncompleteCount;
7910}
7911
7912/// Once the RecordType has been expanded, the temporary incomplete TypeString
7913/// must be removed from the cache.
7914/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7915/// Returns true if the RecordType was defined recursively.
7916bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7917 if (!ID)
7918 return false;
7919 auto I = Map.find(ID);
7920 assert(I != Map.end() && "Entry not present");
7921 Entry &E = I->second;
7922 assert( (E.State == Incomplete ||
7923 E.State == IncompleteUsed) &&
7924 "Entry must be an incomplete type");
7925 bool IsRecursive = false;
7926 if (E.State == IncompleteUsed) {
7927 // We made use of our Incomplete encoding, thus we are recursive.
7928 IsRecursive = true;
7929 --IncompleteUsedCount;
7930 }
7931 if (E.Swapped.empty())
7932 Map.erase(I);
7933 else {
7934 // Swap the Recursive back.
7935 E.Swapped.swap(E.Str);
7936 E.Swapped.clear();
7937 E.State = Recursive;
7938 }
7939 --IncompleteCount;
7940 return IsRecursive;
7941}
7942
7943/// Add the encoded TypeString to the cache only if it is NonRecursive or
7944/// Recursive (viz: all sub-members were expanded as fully as possible).
7945void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7946 bool IsRecursive) {
7947 if (!ID || IncompleteUsedCount)
7948 return; // No key or it is is an incomplete sub-type so don't add.
7949 Entry &E = Map[ID];
7950 if (IsRecursive && !E.Str.empty()) {
7951 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7952 "This is not the same Recursive entry");
7953 // The parent container was not recursive after all, so we could have used
7954 // this Recursive sub-member entry after all, but we assumed the worse when
7955 // we started viz: IncompleteCount!=0.
7956 return;
7957 }
7958 assert(E.Str.empty() && "Entry already present");
7959 E.Str = Str.str();
7960 E.State = IsRecursive? Recursive : NonRecursive;
7961}
7962
7963/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7964/// are recursively expanding a type (IncompleteCount != 0) and the cached
7965/// encoding is Recursive, return an empty StringRef.
7966StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7967 if (!ID)
7968 return StringRef(); // We have no key.
7969 auto I = Map.find(ID);
7970 if (I == Map.end())
7971 return StringRef(); // We have no encoding.
7972 Entry &E = I->second;
7973 if (E.State == Recursive && IncompleteCount)
7974 return StringRef(); // We don't use Recursive encodings for member types.
7975
7976 if (E.State == Incomplete) {
7977 // The incomplete type is being used to break out of recursion.
7978 E.State = IncompleteUsed;
7979 ++IncompleteUsedCount;
7980 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007981 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007982}
7983
7984/// The XCore ABI includes a type information section that communicates symbol
7985/// type information to the linker. The linker uses this information to verify
7986/// safety/correctness of things such as array bound and pointers et al.
7987/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7988/// This type information (TypeString) is emitted into meta data for all global
7989/// symbols: definitions, declarations, functions & variables.
7990///
7991/// The TypeString carries type, qualifier, name, size & value details.
7992/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007993/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007994/// The output is tested by test/CodeGen/xcore-stringtype.c.
7995///
7996static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7997 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7998
7999/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8000void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8001 CodeGen::CodeGenModule &CGM) const {
8002 SmallStringEnc Enc;
8003 if (getTypeString(Enc, D, CGM, TSC)) {
8004 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008005 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8006 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008007 llvm::NamedMDNode *MD =
8008 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8009 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8010 }
8011}
8012
Xiuli Pan972bea82016-03-24 03:57:17 +00008013//===----------------------------------------------------------------------===//
8014// SPIR ABI Implementation
8015//===----------------------------------------------------------------------===//
8016
8017namespace {
8018class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8019public:
8020 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8021 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8022 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8023 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008024 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008025};
8026} // End anonymous namespace.
8027
8028/// Emit SPIR specific metadata: OpenCL and SPIR version.
8029void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8030 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00008031 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8032 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8033 llvm::Module &M = CGM.getModule();
8034 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8035 // opencl.spir.version named metadata.
8036 llvm::Metadata *SPIRVerElts[] = {
Alexey Baderb3190822016-12-07 08:38:24 +00008037 llvm::ConstantAsMetadata::get(
8038 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8039 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8040 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
Xiuli Pan972bea82016-03-24 03:57:17 +00008041 llvm::NamedMDNode *SPIRVerMD =
8042 M.getOrInsertNamedMetadata("opencl.spir.version");
8043 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00008044 appendOpenCLVersionMD(CGM);
8045}
8046
Matt Arsenault8afb5cd2016-09-07 07:07:59 +00008047static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00008048 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8049 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8050 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00008051 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8052 // opencl.ocl.version named metadata node.
8053 llvm::Metadata *OCLVerElts[] = {
8054 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8055 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8056 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8057 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8058 llvm::NamedMDNode *OCLVerMD =
8059 M.getOrInsertNamedMetadata("opencl.ocl.version");
8060 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8061}
8062
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008063unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8064 return llvm::CallingConv::SPIR_KERNEL;
8065}
8066
Robert Lytton844aeeb2014-05-02 09:33:20 +00008067static bool appendType(SmallStringEnc &Enc, QualType QType,
8068 const CodeGen::CodeGenModule &CGM,
8069 TypeStringCache &TSC);
8070
8071/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008072/// Builds a SmallVector containing the encoded field types in declaration
8073/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008074static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8075 const RecordDecl *RD,
8076 const CodeGen::CodeGenModule &CGM,
8077 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008078 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008079 SmallStringEnc Enc;
8080 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008081 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008082 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008083 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008084 Enc += "b(";
8085 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008086 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008087 Enc += ':';
8088 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008089 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008090 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008091 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008092 Enc += ')';
8093 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008094 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008095 }
8096 return true;
8097}
8098
8099/// Appends structure and union types to Enc and adds encoding to cache.
8100/// Recursively calls appendType (via extractFieldType) for each field.
8101/// Union types have their fields ordered according to the ABI.
8102static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8103 const CodeGen::CodeGenModule &CGM,
8104 TypeStringCache &TSC, const IdentifierInfo *ID) {
8105 // Append the cached TypeString if we have one.
8106 StringRef TypeString = TSC.lookupStr(ID);
8107 if (!TypeString.empty()) {
8108 Enc += TypeString;
8109 return true;
8110 }
8111
8112 // Start to emit an incomplete TypeString.
8113 size_t Start = Enc.size();
8114 Enc += (RT->isUnionType()? 'u' : 's');
8115 Enc += '(';
8116 if (ID)
8117 Enc += ID->getName();
8118 Enc += "){";
8119
8120 // We collect all encoded fields and order as necessary.
8121 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008122 const RecordDecl *RD = RT->getDecl()->getDefinition();
8123 if (RD && !RD->field_empty()) {
8124 // An incomplete TypeString stub is placed in the cache for this RecordType
8125 // so that recursive calls to this RecordType will use it whilst building a
8126 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008127 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008128 std::string StubEnc(Enc.substr(Start).str());
8129 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8130 TSC.addIncomplete(ID, std::move(StubEnc));
8131 if (!extractFieldType(FE, RD, CGM, TSC)) {
8132 (void) TSC.removeIncomplete(ID);
8133 return false;
8134 }
8135 IsRecursive = TSC.removeIncomplete(ID);
8136 // The ABI requires unions to be sorted but not structures.
8137 // See FieldEncoding::operator< for sort algorithm.
8138 if (RT->isUnionType())
8139 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008140 // We can now complete the TypeString.
8141 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008142 for (unsigned I = 0; I != E; ++I) {
8143 if (I)
8144 Enc += ',';
8145 Enc += FE[I].str();
8146 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008147 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008148 Enc += '}';
8149 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8150 return true;
8151}
8152
8153/// Appends enum types to Enc and adds the encoding to the cache.
8154static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8155 TypeStringCache &TSC,
8156 const IdentifierInfo *ID) {
8157 // Append the cached TypeString if we have one.
8158 StringRef TypeString = TSC.lookupStr(ID);
8159 if (!TypeString.empty()) {
8160 Enc += TypeString;
8161 return true;
8162 }
8163
8164 size_t Start = Enc.size();
8165 Enc += "e(";
8166 if (ID)
8167 Enc += ID->getName();
8168 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008169
8170 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008171 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008172 SmallVector<FieldEncoding, 16> FE;
8173 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8174 ++I) {
8175 SmallStringEnc EnumEnc;
8176 EnumEnc += "m(";
8177 EnumEnc += I->getName();
8178 EnumEnc += "){";
8179 I->getInitVal().toString(EnumEnc);
8180 EnumEnc += '}';
8181 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8182 }
8183 std::sort(FE.begin(), FE.end());
8184 unsigned E = FE.size();
8185 for (unsigned I = 0; I != E; ++I) {
8186 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008187 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008188 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008189 }
8190 }
8191 Enc += '}';
8192 TSC.addIfComplete(ID, Enc.substr(Start), false);
8193 return true;
8194}
8195
8196/// Appends type's qualifier to Enc.
8197/// This is done prior to appending the type's encoding.
8198static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8199 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008200 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008201 int Lookup = 0;
8202 if (QT.isConstQualified())
8203 Lookup += 1<<0;
8204 if (QT.isRestrictQualified())
8205 Lookup += 1<<1;
8206 if (QT.isVolatileQualified())
8207 Lookup += 1<<2;
8208 Enc += Table[Lookup];
8209}
8210
8211/// Appends built-in types to Enc.
8212static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8213 const char *EncType;
8214 switch (BT->getKind()) {
8215 case BuiltinType::Void:
8216 EncType = "0";
8217 break;
8218 case BuiltinType::Bool:
8219 EncType = "b";
8220 break;
8221 case BuiltinType::Char_U:
8222 EncType = "uc";
8223 break;
8224 case BuiltinType::UChar:
8225 EncType = "uc";
8226 break;
8227 case BuiltinType::SChar:
8228 EncType = "sc";
8229 break;
8230 case BuiltinType::UShort:
8231 EncType = "us";
8232 break;
8233 case BuiltinType::Short:
8234 EncType = "ss";
8235 break;
8236 case BuiltinType::UInt:
8237 EncType = "ui";
8238 break;
8239 case BuiltinType::Int:
8240 EncType = "si";
8241 break;
8242 case BuiltinType::ULong:
8243 EncType = "ul";
8244 break;
8245 case BuiltinType::Long:
8246 EncType = "sl";
8247 break;
8248 case BuiltinType::ULongLong:
8249 EncType = "ull";
8250 break;
8251 case BuiltinType::LongLong:
8252 EncType = "sll";
8253 break;
8254 case BuiltinType::Float:
8255 EncType = "ft";
8256 break;
8257 case BuiltinType::Double:
8258 EncType = "d";
8259 break;
8260 case BuiltinType::LongDouble:
8261 EncType = "ld";
8262 break;
8263 default:
8264 return false;
8265 }
8266 Enc += EncType;
8267 return true;
8268}
8269
8270/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8271static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8272 const CodeGen::CodeGenModule &CGM,
8273 TypeStringCache &TSC) {
8274 Enc += "p(";
8275 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8276 return false;
8277 Enc += ')';
8278 return true;
8279}
8280
8281/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008282static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8283 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008284 const CodeGen::CodeGenModule &CGM,
8285 TypeStringCache &TSC, StringRef NoSizeEnc) {
8286 if (AT->getSizeModifier() != ArrayType::Normal)
8287 return false;
8288 Enc += "a(";
8289 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8290 CAT->getSize().toStringUnsigned(Enc);
8291 else
8292 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8293 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008294 // The Qualifiers should be attached to the type rather than the array.
8295 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008296 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8297 return false;
8298 Enc += ')';
8299 return true;
8300}
8301
8302/// Appends a function encoding to Enc, calling appendType for the return type
8303/// and the arguments.
8304static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8305 const CodeGen::CodeGenModule &CGM,
8306 TypeStringCache &TSC) {
8307 Enc += "f{";
8308 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8309 return false;
8310 Enc += "}(";
8311 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8312 // N.B. we are only interested in the adjusted param types.
8313 auto I = FPT->param_type_begin();
8314 auto E = FPT->param_type_end();
8315 if (I != E) {
8316 do {
8317 if (!appendType(Enc, *I, CGM, TSC))
8318 return false;
8319 ++I;
8320 if (I != E)
8321 Enc += ',';
8322 } while (I != E);
8323 if (FPT->isVariadic())
8324 Enc += ",va";
8325 } else {
8326 if (FPT->isVariadic())
8327 Enc += "va";
8328 else
8329 Enc += '0';
8330 }
8331 }
8332 Enc += ')';
8333 return true;
8334}
8335
8336/// Handles the type's qualifier before dispatching a call to handle specific
8337/// type encodings.
8338static bool appendType(SmallStringEnc &Enc, QualType QType,
8339 const CodeGen::CodeGenModule &CGM,
8340 TypeStringCache &TSC) {
8341
8342 QualType QT = QType.getCanonicalType();
8343
Robert Lytton6adb20f2014-06-05 09:06:21 +00008344 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8345 // The Qualifiers should be attached to the type rather than the array.
8346 // Thus we don't call appendQualifier() here.
8347 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8348
Robert Lytton844aeeb2014-05-02 09:33:20 +00008349 appendQualifier(Enc, QT);
8350
8351 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8352 return appendBuiltinType(Enc, BT);
8353
Robert Lytton844aeeb2014-05-02 09:33:20 +00008354 if (const PointerType *PT = QT->getAs<PointerType>())
8355 return appendPointerType(Enc, PT, CGM, TSC);
8356
8357 if (const EnumType *ET = QT->getAs<EnumType>())
8358 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8359
8360 if (const RecordType *RT = QT->getAsStructureType())
8361 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8362
8363 if (const RecordType *RT = QT->getAsUnionType())
8364 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8365
8366 if (const FunctionType *FT = QT->getAs<FunctionType>())
8367 return appendFunctionType(Enc, FT, CGM, TSC);
8368
8369 return false;
8370}
8371
8372static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8373 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8374 if (!D)
8375 return false;
8376
8377 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8378 if (FD->getLanguageLinkage() != CLanguageLinkage)
8379 return false;
8380 return appendType(Enc, FD->getType(), CGM, TSC);
8381 }
8382
8383 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8384 if (VD->getLanguageLinkage() != CLanguageLinkage)
8385 return false;
8386 QualType QT = VD->getType().getCanonicalType();
8387 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8388 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008389 // The Qualifiers should be attached to the type rather than the array.
8390 // Thus we don't call appendQualifier() here.
8391 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008392 }
8393 return appendType(Enc, QT, CGM, TSC);
8394 }
8395 return false;
8396}
8397
8398
Robert Lytton0e076492013-08-13 09:43:10 +00008399//===----------------------------------------------------------------------===//
8400// Driver code
8401//===----------------------------------------------------------------------===//
8402
Rafael Espindola9f834732014-09-19 01:54:22 +00008403bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008404 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008405}
8406
Chris Lattner2b037972010-07-29 02:01:43 +00008407const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008408 if (TheTargetCodeGenInfo)
8409 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008410
Reid Kleckner9305fd12016-04-13 23:37:17 +00008411 // Helper to set the unique_ptr while still keeping the return value.
8412 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8413 this->TheTargetCodeGenInfo.reset(P);
8414 return *P;
8415 };
8416
John McCallc8e01702013-04-16 22:48:15 +00008417 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008418 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008419 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008420 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008421
Derek Schuff09338a22012-09-06 17:37:28 +00008422 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008423 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008424 case llvm::Triple::mips:
8425 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008426 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008427 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8428 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008429
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008430 case llvm::Triple::mips64:
8431 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008432 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008433
Dylan McKaye8232d72017-02-08 05:09:26 +00008434 case llvm::Triple::avr:
8435 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8436
Tim Northover25e8a672014-05-24 12:51:25 +00008437 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008438 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008439 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008440 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008441 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008442
Reid Kleckner9305fd12016-04-13 23:37:17 +00008443 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008444 }
8445
Dan Gohmanc2853072015-09-03 22:51:53 +00008446 case llvm::Triple::wasm32:
8447 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008448 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008449
Daniel Dunbard59655c2009-09-12 00:59:49 +00008450 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008451 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008452 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008453 case llvm::Triple::thumbeb: {
8454 if (Triple.getOS() == llvm::Triple::Win32) {
8455 return SetCGInfo(
8456 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008457 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008458
Reid Kleckner9305fd12016-04-13 23:37:17 +00008459 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8460 StringRef ABIStr = getTarget().getABI();
8461 if (ABIStr == "apcs-gnu")
8462 Kind = ARMABIInfo::APCS;
8463 else if (ABIStr == "aapcs16")
8464 Kind = ARMABIInfo::AAPCS16_VFP;
8465 else if (CodeGenOpts.FloatABI == "hard" ||
8466 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008467 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008468 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008469 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008470 Kind = ARMABIInfo::AAPCS_VFP;
8471
8472 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8473 }
8474
John McCallea8d8bb2010-03-11 00:10:12 +00008475 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008476 return SetCGInfo(
8477 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008478 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008479 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008480 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008481 if (getTarget().getABI() == "elfv2")
8482 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008483 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008484 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008485
Hal Finkel415c2a32016-10-02 02:10:45 +00008486 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8487 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008488 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008489 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008490 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008491 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008492 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008493 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008494 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008495 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008496 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008497
Hal Finkel415c2a32016-10-02 02:10:45 +00008498 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8499 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008500 }
John McCallea8d8bb2010-03-11 00:10:12 +00008501
Peter Collingbournec947aae2012-05-20 23:28:41 +00008502 case llvm::Triple::nvptx:
8503 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008504 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008505
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008506 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008507 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008508
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008509 case llvm::Triple::systemz: {
8510 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008511 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008512 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008513
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008514 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008515 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008516 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008517
Eli Friedman33465822011-07-08 23:31:17 +00008518 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008519 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008520 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008521 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008522 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008523
John McCall1fe2a8c2013-06-18 02:46:29 +00008524 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008525 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8526 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8527 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008528 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008529 return SetCGInfo(new X86_32TargetCodeGenInfo(
8530 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8531 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8532 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008533 }
Eli Friedman33465822011-07-08 23:31:17 +00008534 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008535
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008536 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008537 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008538 X86AVXABILevel AVXLevel =
8539 (ABI == "avx512"
8540 ? X86AVXABILevel::AVX512
8541 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008542
Chris Lattner04dc9572010-08-31 16:44:54 +00008543 switch (Triple.getOS()) {
8544 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008545 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008546 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008547 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008548 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008549 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008550 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008551 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008552 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008553 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008554 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008555 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008556 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008557 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008558 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008559 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008560 case llvm::Triple::sparc:
8561 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008562 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008563 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008564 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008565 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008566 case llvm::Triple::spir:
8567 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008568 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008569 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008570}