clang 20.0.0git
X86.cpp
Go to the documentation of this file.
1//===- X86.cpp ------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ABIInfoImpl.h"
10#include "TargetInfo.h"
12#include "llvm/ADT/SmallBitVector.h"
13
14using namespace clang;
15using namespace clang::CodeGen;
16
17namespace {
18
19/// IsX86_MMXType - Return true if this is an MMX type.
20bool IsX86_MMXType(llvm::Type *IRType) {
21 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
22 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
23 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
24 IRType->getScalarSizeInBits() != 64;
25}
26
27static llvm::Type *X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
28 StringRef Constraint,
29 llvm::Type *Ty) {
30 if (Constraint == "k") {
31 llvm::Type *Int1Ty = llvm::Type::getInt1Ty(CGF.getLLVMContext());
32 return llvm::FixedVectorType::get(Int1Ty, Ty->getScalarSizeInBits());
33 }
34
35 // No operation needed
36 return Ty;
37}
38
39/// Returns true if this type can be passed in SSE registers with the
40/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
41static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
42 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
43 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
44 if (BT->getKind() == BuiltinType::LongDouble) {
45 if (&Context.getTargetInfo().getLongDoubleFormat() ==
46 &llvm::APFloat::x87DoubleExtended())
47 return false;
48 }
49 return true;
50 }
51 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
52 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
53 // registers specially.
54 unsigned VecSize = Context.getTypeSize(VT);
55 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
56 return true;
57 }
58 return false;
59}
60
61/// Returns true if this aggregate is small enough to be passed in SSE registers
62/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
63static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
64 return NumMembers <= 4;
65}
66
67/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
68static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
69 auto AI = ABIArgInfo::getDirect(T);
70 AI.setInReg(true);
71 AI.setCanBeFlattened(false);
72 return AI;
73}
74
75//===----------------------------------------------------------------------===//
76// X86-32 ABI Implementation
77//===----------------------------------------------------------------------===//
78
79/// Similar to llvm::CCState, but for Clang.
80struct CCState {
81 CCState(CGFunctionInfo &FI)
82 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()),
83 Required(FI.getRequiredArgs()), IsDelegateCall(FI.isDelegateCall()) {}
84
85 llvm::SmallBitVector IsPreassigned;
86 unsigned CC = CallingConv::CC_C;
87 unsigned FreeRegs = 0;
88 unsigned FreeSSERegs = 0;
90 bool IsDelegateCall = false;
91};
92
93/// X86_32ABIInfo - The X86-32 ABI information.
94class X86_32ABIInfo : public ABIInfo {
95 enum Class {
96 Integer,
97 Float
98 };
99
100 static const unsigned MinABIStackAlignInBytes = 4;
101
102 bool IsDarwinVectorABI;
103 bool IsRetSmallStructInRegABI;
104 bool IsWin32StructABI;
105 bool IsSoftFloatABI;
106 bool IsMCUABI;
107 bool IsLinuxABI;
108 unsigned DefaultNumRegisterParameters;
109
110 static bool isRegisterSize(unsigned Size) {
111 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
112 }
113
114 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
115 // FIXME: Assumes vectorcall is in use.
116 return isX86VectorTypeForVectorCall(getContext(), Ty);
117 }
118
120 uint64_t NumMembers) const override {
121 // FIXME: Assumes vectorcall is in use.
122 return isX86VectorCallAggregateSmallEnough(NumMembers);
123 }
124
125 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
126
127 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
128 /// such that the argument will be passed in memory.
129 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
130
131 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
132
133 /// Return the alignment to use for the given type on the stack.
134 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
135
136 Class classify(QualType Ty) const;
137 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
138 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
139 unsigned ArgIndex) const;
140
141 /// Updates the number of available free registers, returns
142 /// true if any registers were allocated.
143 bool updateFreeRegs(QualType Ty, CCState &State) const;
144
145 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
146 bool &NeedsPadding) const;
147 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
148
149 bool canExpandIndirectArgument(QualType Ty) const;
150
151 /// Rewrite the function info so that all memory arguments use
152 /// inalloca.
153 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
154
155 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
156 CharUnits &StackOffset, ABIArgInfo &Info,
157 QualType Type) const;
158 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
159
160public:
161
162 void computeInfo(CGFunctionInfo &FI) const override;
163 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
164 AggValueSlot Slot) const override;
165
166 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
167 bool RetSmallStructInRegABI, bool Win32StructABI,
168 unsigned NumRegisterParameters, bool SoftFloatABI)
169 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
170 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
171 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
172 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
173 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
174 CGT.getTarget().getTriple().isOSCygMing()),
175 DefaultNumRegisterParameters(NumRegisterParameters) {}
176};
177
178class X86_32SwiftABIInfo : public SwiftABIInfo {
179public:
180 explicit X86_32SwiftABIInfo(CodeGenTypes &CGT)
181 : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/false) {}
182
184 bool AsReturnValue) const override {
185 // LLVM's x86-32 lowering currently only assigns up to three
186 // integer registers and three fp registers. Oddly, it'll use up to
187 // four vector registers for vectors, but those can overlap with the
188 // scalar registers.
189 return occupiesMoreThan(ComponentTys, /*total=*/3);
190 }
191};
192
193class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
194public:
195 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
196 bool RetSmallStructInRegABI, bool Win32StructABI,
197 unsigned NumRegisterParameters, bool SoftFloatABI)
198 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
199 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
200 NumRegisterParameters, SoftFloatABI)) {
201 SwiftInfo = std::make_unique<X86_32SwiftABIInfo>(CGT);
202 }
203
204 static bool isStructReturnInRegABI(
205 const llvm::Triple &Triple, const CodeGenOptions &Opts);
206
207 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
208 CodeGen::CodeGenModule &CGM) const override;
209
210 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
211 // Darwin uses different dwarf register numbers for EH.
212 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
213 return 4;
214 }
215
217 llvm::Value *Address) const override;
218
220 StringRef Constraint,
221 llvm::Type* Ty) const override {
222 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
223 }
224
225 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
226 std::string &Constraints,
227 std::vector<llvm::Type *> &ResultRegTypes,
228 std::vector<llvm::Type *> &ResultTruncRegTypes,
229 std::vector<LValue> &ResultRegDests,
230 std::string &AsmString,
231 unsigned NumOutputs) const override;
232
233 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
234 return "movl\t%ebp, %ebp"
235 "\t\t// marker for objc_retainAutoreleaseReturnValue";
236 }
237};
238
239}
240
241/// Rewrite input constraint references after adding some output constraints.
242/// In the case where there is one output and one input and we add one output,
243/// we need to replace all operand references greater than or equal to 1:
244/// mov $0, $1
245/// mov eax, $1
246/// The result will be:
247/// mov $0, $2
248/// mov eax, $2
249static void rewriteInputConstraintReferences(unsigned FirstIn,
250 unsigned NumNewOuts,
251 std::string &AsmString) {
252 std::string Buf;
253 llvm::raw_string_ostream OS(Buf);
254 size_t Pos = 0;
255 while (Pos < AsmString.size()) {
256 size_t DollarStart = AsmString.find('$', Pos);
257 if (DollarStart == std::string::npos)
258 DollarStart = AsmString.size();
259 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
260 if (DollarEnd == std::string::npos)
261 DollarEnd = AsmString.size();
262 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
263 Pos = DollarEnd;
264 size_t NumDollars = DollarEnd - DollarStart;
265 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
266 // We have an operand reference.
267 size_t DigitStart = Pos;
268 if (AsmString[DigitStart] == '{') {
269 OS << '{';
270 ++DigitStart;
271 }
272 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
273 if (DigitEnd == std::string::npos)
274 DigitEnd = AsmString.size();
275 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
276 unsigned OperandIndex;
277 if (!OperandStr.getAsInteger(10, OperandIndex)) {
278 if (OperandIndex >= FirstIn)
279 OperandIndex += NumNewOuts;
280 OS << OperandIndex;
281 } else {
282 OS << OperandStr;
283 }
284 Pos = DigitEnd;
285 }
286 }
287 AsmString = std::move(OS.str());
288}
289
290/// Add output constraints for EAX:EDX because they are return registers.
291void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
292 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
293 std::vector<llvm::Type *> &ResultRegTypes,
294 std::vector<llvm::Type *> &ResultTruncRegTypes,
295 std::vector<LValue> &ResultRegDests, std::string &AsmString,
296 unsigned NumOutputs) const {
297 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
298
299 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
300 // larger.
301 if (!Constraints.empty())
302 Constraints += ',';
303 if (RetWidth <= 32) {
304 Constraints += "={eax}";
305 ResultRegTypes.push_back(CGF.Int32Ty);
306 } else {
307 // Use the 'A' constraint for EAX:EDX.
308 Constraints += "=A";
309 ResultRegTypes.push_back(CGF.Int64Ty);
310 }
311
312 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
313 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
314 ResultTruncRegTypes.push_back(CoerceTy);
315
316 // Coerce the integer by bitcasting the return slot pointer.
317 ReturnSlot.setAddress(ReturnSlot.getAddress().withElementType(CoerceTy));
318 ResultRegDests.push_back(ReturnSlot);
319
320 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
321}
322
323/// shouldReturnTypeInRegister - Determine if the given type should be
324/// returned in a register (for the Darwin and MCU ABI).
325bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
326 ASTContext &Context) const {
327 uint64_t Size = Context.getTypeSize(Ty);
328
329 // For i386, type must be register sized.
330 // For the MCU ABI, it only needs to be <= 8-byte
331 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
332 return false;
333
334 if (Ty->isVectorType()) {
335 // 64- and 128- bit vectors inside structures are not returned in
336 // registers.
337 if (Size == 64 || Size == 128)
338 return false;
339
340 return true;
341 }
342
343 // If this is a builtin, pointer, enum, complex type, member pointer, or
344 // member function pointer it is ok.
345 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
346 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
348 return true;
349
350 // Arrays are treated like records.
351 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
352 return shouldReturnTypeInRegister(AT->getElementType(), Context);
353
354 // Otherwise, it must be a record type.
355 const RecordType *RT = Ty->getAs<RecordType>();
356 if (!RT) return false;
357
358 // FIXME: Traverse bases here too.
359
360 // Structure types are passed in register if all fields would be
361 // passed in a register.
362 for (const auto *FD : RT->getDecl()->fields()) {
363 // Empty fields are ignored.
364 if (isEmptyField(Context, FD, true))
365 continue;
366
367 // Check fields recursively.
368 if (!shouldReturnTypeInRegister(FD->getType(), Context))
369 return false;
370 }
371 return true;
372}
373
374static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
375 // Treat complex types as the element type.
376 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
377 Ty = CTy->getElementType();
378
379 // Check for a type which we know has a simple scalar argument-passing
380 // convention without any padding. (We're specifically looking for 32
381 // and 64-bit integer and integer-equivalents, float, and double.)
382 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
383 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
384 return false;
385
386 uint64_t Size = Context.getTypeSize(Ty);
387 return Size == 32 || Size == 64;
388}
389
390static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
391 uint64_t &Size) {
392 for (const auto *FD : RD->fields()) {
393 // Scalar arguments on the stack get 4 byte alignment on x86. If the
394 // argument is smaller than 32-bits, expanding the struct will create
395 // alignment padding.
396 if (!is32Or64BitBasicType(FD->getType(), Context))
397 return false;
398
399 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
400 // how to expand them yet, and the predicate for telling if a bitfield still
401 // counts as "basic" is more complicated than what we were doing previously.
402 if (FD->isBitField())
403 return false;
404
405 Size += Context.getTypeSize(FD->getType());
406 }
407 return true;
408}
409
410static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
411 uint64_t &Size) {
412 // Don't do this if there are any non-empty bases.
413 for (const CXXBaseSpecifier &Base : RD->bases()) {
414 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
415 Size))
416 return false;
417 }
418 if (!addFieldSizes(Context, RD, Size))
419 return false;
420 return true;
421}
422
423/// Test whether an argument type which is to be passed indirectly (on the
424/// stack) would have the equivalent layout if it was expanded into separate
425/// arguments. If so, we prefer to do the latter to avoid inhibiting
426/// optimizations.
427bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
428 // We can only expand structure types.
429 const RecordType *RT = Ty->getAs<RecordType>();
430 if (!RT)
431 return false;
432 const RecordDecl *RD = RT->getDecl();
433 uint64_t Size = 0;
434 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
435 if (!IsWin32StructABI) {
436 // On non-Windows, we have to conservatively match our old bitcode
437 // prototypes in order to be ABI-compatible at the bitcode level.
438 if (!CXXRD->isCLike())
439 return false;
440 } else {
441 // Don't do this for dynamic classes.
442 if (CXXRD->isDynamicClass())
443 return false;
444 }
445 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
446 return false;
447 } else {
448 if (!addFieldSizes(getContext(), RD, Size))
449 return false;
450 }
451
452 // We can do this if there was no alignment padding.
453 return Size == getContext().getTypeSize(Ty);
454}
455
456ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
457 // If the return value is indirect, then the hidden argument is consuming one
458 // integer register.
459 if (State.CC != llvm::CallingConv::X86_FastCall &&
460 State.CC != llvm::CallingConv::X86_VectorCall && State.FreeRegs) {
461 --State.FreeRegs;
462 if (!IsMCUABI)
463 return getNaturalAlignIndirectInReg(RetTy);
464 }
465 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
466}
467
468ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
469 CCState &State) const {
470 if (RetTy->isVoidType())
471 return ABIArgInfo::getIgnore();
472
473 const Type *Base = nullptr;
474 uint64_t NumElts = 0;
475 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
476 State.CC == llvm::CallingConv::X86_RegCall) &&
477 isHomogeneousAggregate(RetTy, Base, NumElts)) {
478 // The LLVM struct type for such an aggregate should lower properly.
479 return ABIArgInfo::getDirect();
480 }
481
482 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
483 // On Darwin, some vectors are returned in registers.
484 if (IsDarwinVectorABI) {
485 uint64_t Size = getContext().getTypeSize(RetTy);
486
487 // 128-bit vectors are a special case; they are returned in
488 // registers and we need to make sure to pick a type the LLVM
489 // backend will like.
490 if (Size == 128)
491 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
492 llvm::Type::getInt64Ty(getVMContext()), 2));
493
494 // Always return in register if it fits in a general purpose
495 // register, or if it is 64 bits and has a single element.
496 if ((Size == 8 || Size == 16 || Size == 32) ||
497 (Size == 64 && VT->getNumElements() == 1))
498 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
499 Size));
500
501 return getIndirectReturnResult(RetTy, State);
502 }
503
504 return ABIArgInfo::getDirect();
505 }
506
507 if (isAggregateTypeForABI(RetTy)) {
508 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
509 // Structures with flexible arrays are always indirect.
510 if (RT->getDecl()->hasFlexibleArrayMember())
511 return getIndirectReturnResult(RetTy, State);
512 }
513
514 // If specified, structs and unions are always indirect.
515 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
516 return getIndirectReturnResult(RetTy, State);
517
518 // Ignore empty structs/unions.
519 if (isEmptyRecord(getContext(), RetTy, true))
520 return ABIArgInfo::getIgnore();
521
522 // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
523 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
524 QualType ET = getContext().getCanonicalType(CT->getElementType());
525 if (ET->isFloat16Type())
526 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
527 llvm::Type::getHalfTy(getVMContext()), 2));
528 }
529
530 // Small structures which are register sized are generally returned
531 // in a register.
532 if (shouldReturnTypeInRegister(RetTy, getContext())) {
533 uint64_t Size = getContext().getTypeSize(RetTy);
534
535 // As a special-case, if the struct is a "single-element" struct, and
536 // the field is of type "float" or "double", return it in a
537 // floating-point register. (MSVC does not apply this special case.)
538 // We apply a similar transformation for pointer types to improve the
539 // quality of the generated IR.
540 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
541 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
542 || SeltTy->hasPointerRepresentation())
543 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
544
545 // FIXME: We should be able to narrow this integer in cases with dead
546 // padding.
547 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
548 }
549
550 return getIndirectReturnResult(RetTy, State);
551 }
552
553 // Treat an enum type as its underlying type.
554 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
555 RetTy = EnumTy->getDecl()->getIntegerType();
556
557 if (const auto *EIT = RetTy->getAs<BitIntType>())
558 if (EIT->getNumBits() > 64)
559 return getIndirectReturnResult(RetTy, State);
560
561 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
563}
564
565unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
566 unsigned Align) const {
567 // Otherwise, if the alignment is less than or equal to the minimum ABI
568 // alignment, just use the default; the backend will handle this.
569 if (Align <= MinABIStackAlignInBytes)
570 return 0; // Use default alignment.
571
572 if (IsLinuxABI) {
573 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
574 // want to spend any effort dealing with the ramifications of ABI breaks.
575 //
576 // If the vector type is __m128/__m256/__m512, return the default alignment.
577 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
578 return Align;
579 }
580 // On non-Darwin, the stack type alignment is always 4.
581 if (!IsDarwinVectorABI) {
582 // Set explicit alignment, since we may need to realign the top.
583 return MinABIStackAlignInBytes;
584 }
585
586 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
587 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
588 isRecordWithSIMDVectorType(getContext(), Ty)))
589 return 16;
590
591 return MinABIStackAlignInBytes;
592}
593
594ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
595 CCState &State) const {
596 if (!ByVal) {
597 if (State.FreeRegs) {
598 --State.FreeRegs; // Non-byval indirects just use one pointer.
599 if (!IsMCUABI)
600 return getNaturalAlignIndirectInReg(Ty);
601 }
602 return getNaturalAlignIndirect(Ty, false);
603 }
604
605 // Compute the byval alignment.
606 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
607 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
608 if (StackAlign == 0)
609 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
610
611 // If the stack alignment is less than the type alignment, realign the
612 // argument.
613 bool Realign = TypeAlign > StackAlign;
615 /*ByVal=*/true, Realign);
616}
617
618X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
619 const Type *T = isSingleElementStruct(Ty, getContext());
620 if (!T)
621 T = Ty.getTypePtr();
622
623 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
624 BuiltinType::Kind K = BT->getKind();
625 if (K == BuiltinType::Float || K == BuiltinType::Double)
626 return Float;
627 }
628 return Integer;
629}
630
631bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
632 if (!IsSoftFloatABI) {
633 Class C = classify(Ty);
634 if (C == Float)
635 return false;
636 }
637
638 unsigned Size = getContext().getTypeSize(Ty);
639 unsigned SizeInRegs = (Size + 31) / 32;
640
641 if (SizeInRegs == 0)
642 return false;
643
644 if (!IsMCUABI) {
645 if (SizeInRegs > State.FreeRegs) {
646 State.FreeRegs = 0;
647 return false;
648 }
649 } else {
650 // The MCU psABI allows passing parameters in-reg even if there are
651 // earlier parameters that are passed on the stack. Also,
652 // it does not allow passing >8-byte structs in-register,
653 // even if there are 3 free registers available.
654 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
655 return false;
656 }
657
658 State.FreeRegs -= SizeInRegs;
659 return true;
660}
661
662bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
663 bool &InReg,
664 bool &NeedsPadding) const {
665 // On Windows, aggregates other than HFAs are never passed in registers, and
666 // they do not consume register slots. Homogenous floating-point aggregates
667 // (HFAs) have already been dealt with at this point.
668 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
669 return false;
670
671 NeedsPadding = false;
672 InReg = !IsMCUABI;
673
674 if (!updateFreeRegs(Ty, State))
675 return false;
676
677 if (IsMCUABI)
678 return true;
679
680 if (State.CC == llvm::CallingConv::X86_FastCall ||
681 State.CC == llvm::CallingConv::X86_VectorCall ||
682 State.CC == llvm::CallingConv::X86_RegCall) {
683 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
684 NeedsPadding = true;
685
686 return false;
687 }
688
689 return true;
690}
691
692bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
693 bool IsPtrOrInt = (getContext().getTypeSize(Ty) <= 32) &&
695 Ty->isReferenceType());
696
697 if (!IsPtrOrInt && (State.CC == llvm::CallingConv::X86_FastCall ||
698 State.CC == llvm::CallingConv::X86_VectorCall))
699 return false;
700
701 if (!updateFreeRegs(Ty, State))
702 return false;
703
704 if (!IsPtrOrInt && State.CC == llvm::CallingConv::X86_RegCall)
705 return false;
706
707 // Return true to apply inreg to all legal parameters except for MCU targets.
708 return !IsMCUABI;
709}
710
711void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
712 // Vectorcall x86 works subtly different than in x64, so the format is
713 // a bit different than the x64 version. First, all vector types (not HVAs)
714 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
715 // This differs from the x64 implementation, where the first 6 by INDEX get
716 // registers.
717 // In the second pass over the arguments, HVAs are passed in the remaining
718 // vector registers if possible, or indirectly by address. The address will be
719 // passed in ECX/EDX if available. Any other arguments are passed according to
720 // the usual fastcall rules.
722 for (int I = 0, E = Args.size(); I < E; ++I) {
723 const Type *Base = nullptr;
724 uint64_t NumElts = 0;
725 const QualType &Ty = Args[I].type;
726 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
727 isHomogeneousAggregate(Ty, Base, NumElts)) {
728 if (State.FreeSSERegs >= NumElts) {
729 State.FreeSSERegs -= NumElts;
730 Args[I].info = ABIArgInfo::getDirectInReg();
731 State.IsPreassigned.set(I);
732 }
733 }
734 }
735}
736
737ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State,
738 unsigned ArgIndex) const {
739 // FIXME: Set alignment on indirect arguments.
740 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
741 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
742 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
743
745 TypeInfo TI = getContext().getTypeInfo(Ty);
746
747 // Check with the C++ ABI first.
748 const RecordType *RT = Ty->getAs<RecordType>();
749 if (RT) {
750 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
751 if (RAA == CGCXXABI::RAA_Indirect) {
752 return getIndirectResult(Ty, false, State);
753 } else if (State.IsDelegateCall) {
754 // Avoid having different alignments on delegate call args by always
755 // setting the alignment to 4, which is what we do for inallocas.
756 ABIArgInfo Res = getIndirectResult(Ty, false, State);
758 return Res;
759 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
760 // The field index doesn't matter, we'll fix it up later.
761 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
762 }
763 }
764
765 // Regcall uses the concept of a homogenous vector aggregate, similar
766 // to other targets.
767 const Type *Base = nullptr;
768 uint64_t NumElts = 0;
769 if ((IsRegCall || IsVectorCall) &&
770 isHomogeneousAggregate(Ty, Base, NumElts)) {
771 if (State.FreeSSERegs >= NumElts) {
772 State.FreeSSERegs -= NumElts;
773
774 // Vectorcall passes HVAs directly and does not flatten them, but regcall
775 // does.
776 if (IsVectorCall)
777 return getDirectX86Hva();
778
779 if (Ty->isBuiltinType() || Ty->isVectorType())
780 return ABIArgInfo::getDirect();
781 return ABIArgInfo::getExpand();
782 }
783 if (IsVectorCall && Ty->isBuiltinType())
784 return ABIArgInfo::getDirect();
785 return getIndirectResult(Ty, /*ByVal=*/false, State);
786 }
787
788 if (isAggregateTypeForABI(Ty)) {
789 // Structures with flexible arrays are always indirect.
790 // FIXME: This should not be byval!
791 if (RT && RT->getDecl()->hasFlexibleArrayMember())
792 return getIndirectResult(Ty, true, State);
793
794 // Ignore empty structs/unions on non-Windows.
795 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
796 return ABIArgInfo::getIgnore();
797
798 llvm::LLVMContext &LLVMContext = getVMContext();
799 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
800 bool NeedsPadding = false;
801 bool InReg;
802 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
803 unsigned SizeInRegs = (TI.Width + 31) / 32;
804 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
805 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
806 if (InReg)
807 return ABIArgInfo::getDirectInReg(Result);
808 else
809 return ABIArgInfo::getDirect(Result);
810 }
811 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
812
813 // Pass over-aligned aggregates to non-variadic functions on Windows
814 // indirectly. This behavior was added in MSVC 2015. Use the required
815 // alignment from the record layout, since that may be less than the
816 // regular type alignment, and types with required alignment of less than 4
817 // bytes are not passed indirectly.
818 if (IsWin32StructABI && State.Required.isRequiredArg(ArgIndex)) {
819 unsigned AlignInBits = 0;
820 if (RT) {
821 const ASTRecordLayout &Layout =
822 getContext().getASTRecordLayout(RT->getDecl());
823 AlignInBits = getContext().toBits(Layout.getRequiredAlignment());
824 } else if (TI.isAlignRequired()) {
825 AlignInBits = TI.Align;
826 }
827 if (AlignInBits > 32)
828 return getIndirectResult(Ty, /*ByVal=*/false, State);
829 }
830
831 // Expand small (<= 128-bit) record types when we know that the stack layout
832 // of those arguments will match the struct. This is important because the
833 // LLVM backend isn't smart enough to remove byval, which inhibits many
834 // optimizations.
835 // Don't do this for the MCU if there are still free integer registers
836 // (see X86_64 ABI for full explanation).
837 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
838 canExpandIndirectArgument(Ty))
840 IsFastCall || IsVectorCall || IsRegCall, PaddingType);
841
842 return getIndirectResult(Ty, true, State);
843 }
844
845 if (const VectorType *VT = Ty->getAs<VectorType>()) {
846 // On Windows, vectors are passed directly if registers are available, or
847 // indirectly if not. This avoids the need to align argument memory. Pass
848 // user-defined vector types larger than 512 bits indirectly for simplicity.
849 if (IsWin32StructABI) {
850 if (TI.Width <= 512 && State.FreeSSERegs > 0) {
851 --State.FreeSSERegs;
853 }
854 return getIndirectResult(Ty, /*ByVal=*/false, State);
855 }
856
857 // On Darwin, some vectors are passed in memory, we handle this by passing
858 // it as an i8/i16/i32/i64.
859 if (IsDarwinVectorABI) {
860 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
861 (TI.Width == 64 && VT->getNumElements() == 1))
863 llvm::IntegerType::get(getVMContext(), TI.Width));
864 }
865
866 if (IsX86_MMXType(CGT.ConvertType(Ty)))
867 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
868
869 return ABIArgInfo::getDirect();
870 }
871
872
873 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
874 Ty = EnumTy->getDecl()->getIntegerType();
875
876 bool InReg = shouldPrimitiveUseInReg(Ty, State);
877
878 if (isPromotableIntegerTypeForABI(Ty)) {
879 if (InReg)
881 return ABIArgInfo::getExtend(Ty);
882 }
883
884 if (const auto *EIT = Ty->getAs<BitIntType>()) {
885 if (EIT->getNumBits() <= 64) {
886 if (InReg)
888 return ABIArgInfo::getDirect();
889 }
890 return getIndirectResult(Ty, /*ByVal=*/false, State);
891 }
892
893 if (InReg)
895 return ABIArgInfo::getDirect();
896}
897
898void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
899 CCState State(FI);
900 if (IsMCUABI)
901 State.FreeRegs = 3;
902 else if (State.CC == llvm::CallingConv::X86_FastCall) {
903 State.FreeRegs = 2;
904 State.FreeSSERegs = 3;
905 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
906 State.FreeRegs = 2;
907 State.FreeSSERegs = 6;
908 } else if (FI.getHasRegParm())
909 State.FreeRegs = FI.getRegParm();
910 else if (State.CC == llvm::CallingConv::X86_RegCall) {
911 State.FreeRegs = 5;
912 State.FreeSSERegs = 8;
913 } else if (IsWin32StructABI) {
914 // Since MSVC 2015, the first three SSE vectors have been passed in
915 // registers. The rest are passed indirectly.
916 State.FreeRegs = DefaultNumRegisterParameters;
917 State.FreeSSERegs = 3;
918 } else
919 State.FreeRegs = DefaultNumRegisterParameters;
920
921 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
923 } else if (FI.getReturnInfo().isIndirect()) {
924 // The C++ ABI is not aware of register usage, so we have to check if the
925 // return value was sret and put it in a register ourselves if appropriate.
926 if (State.FreeRegs) {
927 --State.FreeRegs; // The sret parameter consumes a register.
928 if (!IsMCUABI)
929 FI.getReturnInfo().setInReg(true);
930 }
931 }
932
933 // The chain argument effectively gives us another free register.
934 if (FI.isChainCall())
935 ++State.FreeRegs;
936
937 // For vectorcall, do a first pass over the arguments, assigning FP and vector
938 // arguments to XMM registers as available.
939 if (State.CC == llvm::CallingConv::X86_VectorCall)
940 runVectorCallFirstPass(FI, State);
941
942 bool UsedInAlloca = false;
944 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
945 // Skip arguments that have already been assigned.
946 if (State.IsPreassigned.test(I))
947 continue;
948
949 Args[I].info =
950 classifyArgumentType(Args[I].type, State, I);
951 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
952 }
953
954 // If we needed to use inalloca for any argument, do a second pass and rewrite
955 // all the memory arguments to use inalloca.
956 if (UsedInAlloca)
957 rewriteWithInAlloca(FI);
958}
959
960void
961X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
962 CharUnits &StackOffset, ABIArgInfo &Info,
963 QualType Type) const {
964 // Arguments are always 4-byte-aligned.
966 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
967
968 // sret pointers and indirect things will require an extra pointer
969 // indirection, unless they are byval. Most things are byval, and will not
970 // require this indirection.
971 bool IsIndirect = false;
972 if (Info.isIndirect() && !Info.getIndirectByVal())
973 IsIndirect = true;
974 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
975 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
976 if (IsIndirect)
977 LLTy = llvm::PointerType::getUnqual(getVMContext());
978 FrameFields.push_back(LLTy);
979 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
980
981 // Insert padding bytes to respect alignment.
982 CharUnits FieldEnd = StackOffset;
983 StackOffset = FieldEnd.alignTo(WordSize);
984 if (StackOffset != FieldEnd) {
985 CharUnits NumBytes = StackOffset - FieldEnd;
986 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
987 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
988 FrameFields.push_back(Ty);
989 }
990}
991
992static bool isArgInAlloca(const ABIArgInfo &Info) {
993 // Leave ignored and inreg arguments alone.
994 switch (Info.getKind()) {
996 return true;
999 return false;
1001 case ABIArgInfo::Direct:
1002 case ABIArgInfo::Extend:
1003 return !Info.getInReg();
1004 case ABIArgInfo::Expand:
1006 // These are aggregate types which are never passed in registers when
1007 // inalloca is involved.
1008 return true;
1009 }
1010 llvm_unreachable("invalid enum");
1011}
1012
1013void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1014 assert(IsWin32StructABI && "inalloca only supported on win32");
1015
1016 // Build a packed struct type for all of the arguments in memory.
1017 SmallVector<llvm::Type *, 6> FrameFields;
1018
1019 // The stack alignment is always 4.
1020 CharUnits StackAlign = CharUnits::fromQuantity(4);
1021
1022 CharUnits StackOffset;
1024
1025 // Put 'this' into the struct before 'sret', if necessary.
1026 bool IsThisCall =
1027 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1029 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1030 isArgInAlloca(I->info)) {
1031 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1032 ++I;
1033 }
1034
1035 // Put the sret parameter into the inalloca struct if it's in memory.
1036 if (Ret.isIndirect() && !Ret.getInReg()) {
1037 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
1038 // On Windows, the hidden sret parameter is always returned in eax.
1039 Ret.setInAllocaSRet(IsWin32StructABI);
1040 }
1041
1042 // Skip the 'this' parameter in ecx.
1043 if (IsThisCall)
1044 ++I;
1045
1046 // Put arguments passed in memory into the struct.
1047 for (; I != E; ++I) {
1048 if (isArgInAlloca(I->info))
1049 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1050 }
1051
1052 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1053 /*isPacked=*/true),
1054 StackAlign);
1055}
1056
1057RValue X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1058 QualType Ty, AggValueSlot Slot) const {
1059
1060 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1061
1062 CCState State(*const_cast<CGFunctionInfo *>(CGF.CurFnInfo));
1063 ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
1064 // Empty records are ignored for parameter passing purposes.
1065 if (AI.isIgnore())
1066 return Slot.asRValue();
1067
1068 // x86-32 changes the alignment of certain arguments on the stack.
1069 //
1070 // Just messing with TypeInfo like this works because we never pass
1071 // anything indirectly.
1073 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
1074
1075 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
1077 /*AllowHigherAlign*/ true, Slot);
1078}
1079
1080bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1081 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1082 assert(Triple.getArch() == llvm::Triple::x86);
1083
1084 switch (Opts.getStructReturnConvention()) {
1086 break;
1087 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1088 return false;
1089 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1090 return true;
1091 }
1092
1093 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1094 return true;
1095
1096 switch (Triple.getOS()) {
1097 case llvm::Triple::DragonFly:
1098 case llvm::Triple::FreeBSD:
1099 case llvm::Triple::OpenBSD:
1100 case llvm::Triple::Win32:
1101 return true;
1102 default:
1103 return false;
1104 }
1105}
1106
1107static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
1109 if (!FD->hasAttr<AnyX86InterruptAttr>())
1110 return;
1111
1112 llvm::Function *Fn = cast<llvm::Function>(GV);
1113 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1114 if (FD->getNumParams() == 0)
1115 return;
1116
1117 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
1118 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
1119 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
1120 Fn->getContext(), ByValTy);
1121 Fn->addParamAttr(0, NewAttr);
1122}
1123
1124void X86_32TargetCodeGenInfo::setTargetAttributes(
1125 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1126 if (GV->isDeclaration())
1127 return;
1128 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1129 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1130 llvm::Function *Fn = cast<llvm::Function>(GV);
1131 Fn->addFnAttr("stackrealign");
1132 }
1133
1134 addX86InterruptAttrs(FD, GV, CGM);
1135 }
1136}
1137
1138bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1140 llvm::Value *Address) const {
1141 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1142
1143 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1144
1145 // 0-7 are the eight integer registers; the order is different
1146 // on Darwin (for EH), but the range is the same.
1147 // 8 is %eip.
1148 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1149
1150 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1151 // 12-16 are st(0..4). Not sure why we stop at 4.
1152 // These have size 16, which is sizeof(long double) on
1153 // platforms with 8-byte alignment for that type.
1154 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1155 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1156
1157 } else {
1158 // 9 is %eflags, which doesn't get a size on Darwin for some
1159 // reason.
1160 Builder.CreateAlignedStore(
1161 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1162 CharUnits::One());
1163
1164 // 11-16 are st(0..5). Not sure why we stop at 5.
1165 // These have size 12, which is sizeof(long double) on
1166 // platforms with 4-byte alignment for that type.
1167 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1168 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1169 }
1170
1171 return false;
1172}
1173
1174//===----------------------------------------------------------------------===//
1175// X86-64 ABI Implementation
1176//===----------------------------------------------------------------------===//
1177
1178
1179namespace {
1180
1181/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1182static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1183 switch (AVXLevel) {
1184 case X86AVXABILevel::AVX512:
1185 return 512;
1186 case X86AVXABILevel::AVX:
1187 return 256;
1188 case X86AVXABILevel::None:
1189 return 128;
1190 }
1191 llvm_unreachable("Unknown AVXLevel");
1192}
1193
1194/// X86_64ABIInfo - The X86_64 ABI information.
1195class X86_64ABIInfo : public ABIInfo {
1196 enum Class {
1197 Integer = 0,
1198 SSE,
1199 SSEUp,
1200 X87,
1201 X87Up,
1202 ComplexX87,
1203 NoClass,
1204 Memory
1205 };
1206
1207 /// merge - Implement the X86_64 ABI merging algorithm.
1208 ///
1209 /// Merge an accumulating classification \arg Accum with a field
1210 /// classification \arg Field.
1211 ///
1212 /// \param Accum - The accumulating classification. This should
1213 /// always be either NoClass or the result of a previous merge
1214 /// call. In addition, this should never be Memory (the caller
1215 /// should just return Memory for the aggregate).
1216 static Class merge(Class Accum, Class Field);
1217
1218 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1219 ///
1220 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1221 /// final MEMORY or SSE classes when necessary.
1222 ///
1223 /// \param AggregateSize - The size of the current aggregate in
1224 /// the classification process.
1225 ///
1226 /// \param Lo - The classification for the parts of the type
1227 /// residing in the low word of the containing object.
1228 ///
1229 /// \param Hi - The classification for the parts of the type
1230 /// residing in the higher words of the containing object.
1231 ///
1232 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1233
1234 /// classify - Determine the x86_64 register classes in which the
1235 /// given type T should be passed.
1236 ///
1237 /// \param Lo - The classification for the parts of the type
1238 /// residing in the low word of the containing object.
1239 ///
1240 /// \param Hi - The classification for the parts of the type
1241 /// residing in the high word of the containing object.
1242 ///
1243 /// \param OffsetBase - The bit offset of this type in the
1244 /// containing object. Some parameters are classified different
1245 /// depending on whether they straddle an eightbyte boundary.
1246 ///
1247 /// \param isNamedArg - Whether the argument in question is a "named"
1248 /// argument, as used in AMD64-ABI 3.5.7.
1249 ///
1250 /// \param IsRegCall - Whether the calling conversion is regcall.
1251 ///
1252 /// If a word is unused its result will be NoClass; if a type should
1253 /// be passed in Memory then at least the classification of \arg Lo
1254 /// will be Memory.
1255 ///
1256 /// The \arg Lo class will be NoClass iff the argument is ignored.
1257 ///
1258 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1259 /// also be ComplexX87.
1260 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1261 bool isNamedArg, bool IsRegCall = false) const;
1262
1263 llvm::Type *GetByteVectorType(QualType Ty) const;
1264 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1265 unsigned IROffset, QualType SourceTy,
1266 unsigned SourceOffset) const;
1267 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1268 unsigned IROffset, QualType SourceTy,
1269 unsigned SourceOffset) const;
1270
1271 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1272 /// such that the argument will be returned in memory.
1273 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1274
1275 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1276 /// such that the argument will be passed in memory.
1277 ///
1278 /// \param freeIntRegs - The number of free integer registers remaining
1279 /// available.
1280 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1281
1283
1284 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1285 unsigned &neededInt, unsigned &neededSSE,
1286 bool isNamedArg,
1287 bool IsRegCall = false) const;
1288
1289 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1290 unsigned &NeededSSE,
1291 unsigned &MaxVectorWidth) const;
1292
1293 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
1294 unsigned &NeededSSE,
1295 unsigned &MaxVectorWidth) const;
1296
1297 bool IsIllegalVectorType(QualType Ty) const;
1298
1299 /// The 0.98 ABI revision clarified a lot of ambiguities,
1300 /// unfortunately in ways that were not always consistent with
1301 /// certain previous compilers. In particular, platforms which
1302 /// required strict binary compatibility with older versions of GCC
1303 /// may need to exempt themselves.
1304 bool honorsRevision0_98() const {
1305 return !getTarget().getTriple().isOSDarwin();
1306 }
1307
1308 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
1309 /// classify it as INTEGER (for compatibility with older clang compilers).
1310 bool classifyIntegerMMXAsSSE() const {
1311 // Clang <= 3.8 did not do this.
1312 if (getContext().getLangOpts().getClangABICompat() <=
1313 LangOptions::ClangABI::Ver3_8)
1314 return false;
1315
1316 const llvm::Triple &Triple = getTarget().getTriple();
1317 if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD())
1318 return false;
1319 return true;
1320 }
1321
1322 // GCC classifies vectors of __int128 as memory.
1323 bool passInt128VectorsInMem() const {
1324 // Clang <= 9.0 did not do this.
1325 if (getContext().getLangOpts().getClangABICompat() <=
1326 LangOptions::ClangABI::Ver9)
1327 return false;
1328
1329 const llvm::Triple &T = getTarget().getTriple();
1330 return T.isOSLinux() || T.isOSNetBSD();
1331 }
1332
1333 X86AVXABILevel AVXLevel;
1334 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1335 // 64-bit hardware.
1336 bool Has64BitPointers;
1337
1338public:
1339 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1340 : ABIInfo(CGT), AVXLevel(AVXLevel),
1341 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {}
1342
1343 bool isPassedUsingAVXType(QualType type) const {
1344 unsigned neededInt, neededSSE;
1345 // The freeIntRegs argument doesn't matter here.
1346 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1347 /*isNamedArg*/true);
1348 if (info.isDirect()) {
1349 llvm::Type *ty = info.getCoerceToType();
1350 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1351 return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
1352 }
1353 return false;
1354 }
1355
1356 void computeInfo(CGFunctionInfo &FI) const override;
1357
1358 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1359 AggValueSlot Slot) const override;
1360 RValue EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1361 AggValueSlot Slot) const override;
1362
1363 bool has64BitPointers() const {
1364 return Has64BitPointers;
1365 }
1366};
1367
1368/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1369class WinX86_64ABIInfo : public ABIInfo {
1370public:
1371 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1372 : ABIInfo(CGT), AVXLevel(AVXLevel),
1373 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
1374
1375 void computeInfo(CGFunctionInfo &FI) const override;
1376
1377 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1378 AggValueSlot Slot) const override;
1379
1380 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1381 // FIXME: Assumes vectorcall is in use.
1382 return isX86VectorTypeForVectorCall(getContext(), Ty);
1383 }
1384
1386 uint64_t NumMembers) const override {
1387 // FIXME: Assumes vectorcall is in use.
1388 return isX86VectorCallAggregateSmallEnough(NumMembers);
1389 }
1390
1391private:
1392 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
1393 bool IsVectorCall, bool IsRegCall) const;
1394 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
1395 const ABIArgInfo &current) const;
1396
1397 X86AVXABILevel AVXLevel;
1398
1399 bool IsMingw64;
1400};
1401
1402class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1403public:
1404 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1405 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {
1406 SwiftInfo =
1407 std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1408 }
1409
1410 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
1411 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
1412 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
1413
1414 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1415 return 7;
1416 }
1417
1419 llvm::Value *Address) const override {
1420 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1421
1422 // 0-15 are the 16 integer registers.
1423 // 16 is %rip.
1424 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1425 return false;
1426 }
1427
1429 StringRef Constraint,
1430 llvm::Type* Ty) const override {
1431 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1432 }
1433
1434 bool isNoProtoCallVariadic(const CallArgList &args,
1435 const FunctionNoProtoType *fnType) const override {
1436 // The default CC on x86-64 sets %al to the number of SSA
1437 // registers used, and GCC sets this when calling an unprototyped
1438 // function, so we override the default behavior. However, don't do
1439 // that when AVX types are involved: the ABI explicitly states it is
1440 // undefined, and it doesn't work in practice because of how the ABI
1441 // defines varargs anyway.
1442 if (fnType->getCallConv() == CC_C) {
1443 bool HasAVXType = false;
1444 for (CallArgList::const_iterator
1445 it = args.begin(), ie = args.end(); it != ie; ++it) {
1446 if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(it->Ty)) {
1447 HasAVXType = true;
1448 break;
1449 }
1450 }
1451
1452 if (!HasAVXType)
1453 return true;
1454 }
1455
1456 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1457 }
1458
1459 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1460 CodeGen::CodeGenModule &CGM) const override {
1461 if (GV->isDeclaration())
1462 return;
1463 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1464 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1465 llvm::Function *Fn = cast<llvm::Function>(GV);
1466 Fn->addFnAttr("stackrealign");
1467 }
1468
1469 addX86InterruptAttrs(FD, GV, CGM);
1470 }
1471 }
1472
1474 const FunctionDecl *Caller,
1475 const FunctionDecl *Callee, const CallArgList &Args,
1476 QualType ReturnType) const override;
1477};
1478} // namespace
1479
1480static void initFeatureMaps(const ASTContext &Ctx,
1481 llvm::StringMap<bool> &CallerMap,
1482 const FunctionDecl *Caller,
1483 llvm::StringMap<bool> &CalleeMap,
1484 const FunctionDecl *Callee) {
1485 if (CalleeMap.empty() && CallerMap.empty()) {
1486 // The caller is potentially nullptr in the case where the call isn't in a
1487 // function. In this case, the getFunctionFeatureMap ensures we just get
1488 // the TU level setting (since it cannot be modified by 'target'..
1489 Ctx.getFunctionFeatureMap(CallerMap, Caller);
1490 Ctx.getFunctionFeatureMap(CalleeMap, Callee);
1491 }
1492}
1493
1495 SourceLocation CallLoc,
1496 const llvm::StringMap<bool> &CallerMap,
1497 const llvm::StringMap<bool> &CalleeMap,
1498 QualType Ty, StringRef Feature,
1499 bool IsArgument) {
1500 bool CallerHasFeat = CallerMap.lookup(Feature);
1501 bool CalleeHasFeat = CalleeMap.lookup(Feature);
1502 if (!CallerHasFeat && !CalleeHasFeat)
1503 return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
1504 << IsArgument << Ty << Feature;
1505
1506 // Mixing calling conventions here is very clearly an error.
1507 if (!CallerHasFeat || !CalleeHasFeat)
1508 return Diag.Report(CallLoc, diag::err_avx_calling_convention)
1509 << IsArgument << Ty << Feature;
1510
1511 // Else, both caller and callee have the required feature, so there is no need
1512 // to diagnose.
1513 return false;
1514}
1515
1517 SourceLocation CallLoc,
1518 const llvm::StringMap<bool> &CallerMap,
1519 const llvm::StringMap<bool> &CalleeMap,
1520 QualType Ty, bool IsArgument) {
1521 bool Caller256 = CallerMap.lookup("avx512f") && !CallerMap.lookup("evex512");
1522 bool Callee256 = CalleeMap.lookup("avx512f") && !CalleeMap.lookup("evex512");
1523
1524 // Forbid 512-bit or larger vector pass or return when we disabled ZMM
1525 // instructions.
1526 if (Caller256 || Callee256)
1527 return Diag.Report(CallLoc, diag::err_avx_calling_convention)
1528 << IsArgument << Ty << "evex512";
1529
1530 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
1531 "avx512f", IsArgument);
1532}
1533
1535 SourceLocation CallLoc,
1536 const llvm::StringMap<bool> &CallerMap,
1537 const llvm::StringMap<bool> &CalleeMap, QualType Ty,
1538 bool IsArgument) {
1539 uint64_t Size = Ctx.getTypeSize(Ty);
1540 if (Size > 256)
1541 return checkAVX512ParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
1542 IsArgument);
1543
1544 if (Size > 128)
1545 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
1546 IsArgument);
1547
1548 return false;
1549}
1550
1551void X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
1552 SourceLocation CallLoc,
1553 const FunctionDecl *Caller,
1554 const FunctionDecl *Callee,
1555 const CallArgList &Args,
1556 QualType ReturnType) const {
1557 if (!Callee)
1558 return;
1559
1560 llvm::StringMap<bool> CallerMap;
1561 llvm::StringMap<bool> CalleeMap;
1562 unsigned ArgIndex = 0;
1563
1564 // We need to loop through the actual call arguments rather than the
1565 // function's parameters, in case this variadic.
1566 for (const CallArg &Arg : Args) {
1567 // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
1568 // additionally changes how vectors >256 in size are passed. Like GCC, we
1569 // warn when a function is called with an argument where this will change.
1570 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
1571 // the caller and callee features are mismatched.
1572 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
1573 // change its ABI with attribute-target after this call.
1574 if (Arg.getType()->isVectorType() &&
1575 CGM.getContext().getTypeSize(Arg.getType()) > 128) {
1576 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1577 QualType Ty = Arg.getType();
1578 // The CallArg seems to have desugared the type already, so for clearer
1579 // diagnostics, replace it with the type in the FunctionDecl if possible.
1580 if (ArgIndex < Callee->getNumParams())
1581 Ty = Callee->getParamDecl(ArgIndex)->getType();
1582
1583 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
1584 CalleeMap, Ty, /*IsArgument*/ true))
1585 return;
1586 }
1587 ++ArgIndex;
1588 }
1589
1590 // Check return always, as we don't have a good way of knowing in codegen
1591 // whether this value is used, tail-called, etc.
1592 if (Callee->getReturnType()->isVectorType() &&
1593 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
1594 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1595 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
1596 CalleeMap, Callee->getReturnType(),
1597 /*IsArgument*/ false);
1598 }
1599}
1600
1602 // If the argument does not end in .lib, automatically add the suffix.
1603 // If the argument contains a space, enclose it in quotes.
1604 // This matches the behavior of MSVC.
1605 bool Quote = Lib.contains(' ');
1606 std::string ArgStr = Quote ? "\"" : "";
1607 ArgStr += Lib;
1608 if (!Lib.ends_with_insensitive(".lib") && !Lib.ends_with_insensitive(".a"))
1609 ArgStr += ".lib";
1610 ArgStr += Quote ? "\"" : "";
1611 return ArgStr;
1612}
1613
1614namespace {
1615class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1616public:
1617 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1618 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1619 unsigned NumRegisterParameters)
1620 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
1621 Win32StructABI, NumRegisterParameters, false) {}
1622
1623 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1624 CodeGen::CodeGenModule &CGM) const override;
1625
1626 void getDependentLibraryOption(llvm::StringRef Lib,
1627 llvm::SmallString<24> &Opt) const override {
1628 Opt = "/DEFAULTLIB:";
1629 Opt += qualifyWindowsLibrary(Lib);
1630 }
1631
1632 void getDetectMismatchOption(llvm::StringRef Name,
1633 llvm::StringRef Value,
1634 llvm::SmallString<32> &Opt) const override {
1635 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1636 }
1637};
1638} // namespace
1639
1640void WinX86_32TargetCodeGenInfo::setTargetAttributes(
1641 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1642 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
1643 if (GV->isDeclaration())
1644 return;
1645 addStackProbeTargetAttributes(D, GV, CGM);
1646}
1647
1648namespace {
1649class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1650public:
1651 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1652 X86AVXABILevel AVXLevel)
1653 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {
1654 SwiftInfo =
1655 std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1656 }
1657
1658 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1659 CodeGen::CodeGenModule &CGM) const override;
1660
1661 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1662 return 7;
1663 }
1664
1665 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1666 llvm::Value *Address) const override {
1667 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1668
1669 // 0-15 are the 16 integer registers.
1670 // 16 is %rip.
1671 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1672 return false;
1673 }
1674
1675 void getDependentLibraryOption(llvm::StringRef Lib,
1676 llvm::SmallString<24> &Opt) const override {
1677 Opt = "/DEFAULTLIB:";
1678 Opt += qualifyWindowsLibrary(Lib);
1679 }
1680
1681 void getDetectMismatchOption(llvm::StringRef Name,
1682 llvm::StringRef Value,
1683 llvm::SmallString<32> &Opt) const override {
1684 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1685 }
1686};
1687} // namespace
1688
1689void WinX86_64TargetCodeGenInfo::setTargetAttributes(
1690 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1692 if (GV->isDeclaration())
1693 return;
1694 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1695 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1696 llvm::Function *Fn = cast<llvm::Function>(GV);
1697 Fn->addFnAttr("stackrealign");
1698 }
1699
1700 addX86InterruptAttrs(FD, GV, CGM);
1701 }
1702
1703 addStackProbeTargetAttributes(D, GV, CGM);
1704}
1705
1706void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1707 Class &Hi) const {
1708 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1709 //
1710 // (a) If one of the classes is Memory, the whole argument is passed in
1711 // memory.
1712 //
1713 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1714 // memory.
1715 //
1716 // (c) If the size of the aggregate exceeds two eightbytes and the first
1717 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1718 // argument is passed in memory. NOTE: This is necessary to keep the
1719 // ABI working for processors that don't support the __m256 type.
1720 //
1721 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1722 //
1723 // Some of these are enforced by the merging logic. Others can arise
1724 // only with unions; for example:
1725 // union { _Complex double; unsigned; }
1726 //
1727 // Note that clauses (b) and (c) were added in 0.98.
1728 //
1729 if (Hi == Memory)
1730 Lo = Memory;
1731 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1732 Lo = Memory;
1733 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1734 Lo = Memory;
1735 if (Hi == SSEUp && Lo != SSE)
1736 Hi = SSE;
1737}
1738
1739X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1740 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1741 // classified recursively so that always two fields are
1742 // considered. The resulting class is calculated according to
1743 // the classes of the fields in the eightbyte:
1744 //
1745 // (a) If both classes are equal, this is the resulting class.
1746 //
1747 // (b) If one of the classes is NO_CLASS, the resulting class is
1748 // the other class.
1749 //
1750 // (c) If one of the classes is MEMORY, the result is the MEMORY
1751 // class.
1752 //
1753 // (d) If one of the classes is INTEGER, the result is the
1754 // INTEGER.
1755 //
1756 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1757 // MEMORY is used as class.
1758 //
1759 // (f) Otherwise class SSE is used.
1760
1761 // Accum should never be memory (we should have returned) or
1762 // ComplexX87 (because this cannot be passed in a structure).
1763 assert((Accum != Memory && Accum != ComplexX87) &&
1764 "Invalid accumulated classification during merge.");
1765 if (Accum == Field || Field == NoClass)
1766 return Accum;
1767 if (Field == Memory)
1768 return Memory;
1769 if (Accum == NoClass)
1770 return Field;
1771 if (Accum == Integer || Field == Integer)
1772 return Integer;
1773 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1774 Accum == X87 || Accum == X87Up)
1775 return Memory;
1776 return SSE;
1777}
1778
1779void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
1780 Class &Hi, bool isNamedArg, bool IsRegCall) const {
1781 // FIXME: This code can be simplified by introducing a simple value class for
1782 // Class pairs with appropriate constructor methods for the various
1783 // situations.
1784
1785 // FIXME: Some of the split computations are wrong; unaligned vectors
1786 // shouldn't be passed in registers for example, so there is no chance they
1787 // can straddle an eightbyte. Verify & simplify.
1788
1789 Lo = Hi = NoClass;
1790
1791 Class &Current = OffsetBase < 64 ? Lo : Hi;
1792 Current = Memory;
1793
1794 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1795 BuiltinType::Kind k = BT->getKind();
1796
1797 if (k == BuiltinType::Void) {
1798 Current = NoClass;
1799 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1800 Lo = Integer;
1801 Hi = Integer;
1802 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1803 Current = Integer;
1804 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
1805 k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
1806 Current = SSE;
1807 } else if (k == BuiltinType::Float128) {
1808 Lo = SSE;
1809 Hi = SSEUp;
1810 } else if (k == BuiltinType::LongDouble) {
1811 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1812 if (LDF == &llvm::APFloat::IEEEquad()) {
1813 Lo = SSE;
1814 Hi = SSEUp;
1815 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
1816 Lo = X87;
1817 Hi = X87Up;
1818 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
1819 Current = SSE;
1820 } else
1821 llvm_unreachable("unexpected long double representation!");
1822 }
1823 // FIXME: _Decimal32 and _Decimal64 are SSE.
1824 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1825 return;
1826 }
1827
1828 if (const EnumType *ET = Ty->getAs<EnumType>()) {
1829 // Classify the underlying integer type.
1830 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1831 return;
1832 }
1833
1834 if (Ty->hasPointerRepresentation()) {
1835 Current = Integer;
1836 return;
1837 }
1838
1839 if (Ty->isMemberPointerType()) {
1840 if (Ty->isMemberFunctionPointerType()) {
1841 if (Has64BitPointers) {
1842 // If Has64BitPointers, this is an {i64, i64}, so classify both
1843 // Lo and Hi now.
1844 Lo = Hi = Integer;
1845 } else {
1846 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1847 // straddles an eightbyte boundary, Hi should be classified as well.
1848 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1849 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1850 if (EB_FuncPtr != EB_ThisAdj) {
1851 Lo = Hi = Integer;
1852 } else {
1853 Current = Integer;
1854 }
1855 }
1856 } else {
1857 Current = Integer;
1858 }
1859 return;
1860 }
1861
1862 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1863 uint64_t Size = getContext().getTypeSize(VT);
1864 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1865 // gcc passes the following as integer:
1866 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
1867 // 2 bytes - <2 x char>, <1 x short>
1868 // 1 byte - <1 x char>
1869 Current = Integer;
1870
1871 // If this type crosses an eightbyte boundary, it should be
1872 // split.
1873 uint64_t EB_Lo = (OffsetBase) / 64;
1874 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
1875 if (EB_Lo != EB_Hi)
1876 Hi = Lo;
1877 } else if (Size == 64) {
1878 QualType ElementType = VT->getElementType();
1879
1880 // gcc passes <1 x double> in memory. :(
1881 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
1882 return;
1883
1884 // gcc passes <1 x long long> as SSE but clang used to unconditionally
1885 // pass them as integer. For platforms where clang is the de facto
1886 // platform compiler, we must continue to use integer.
1887 if (!classifyIntegerMMXAsSSE() &&
1888 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
1889 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1890 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
1891 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
1892 Current = Integer;
1893 else
1894 Current = SSE;
1895
1896 // If this type crosses an eightbyte boundary, it should be
1897 // split.
1898 if (OffsetBase && OffsetBase != 64)
1899 Hi = Lo;
1900 } else if (Size == 128 ||
1901 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
1902 QualType ElementType = VT->getElementType();
1903
1904 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
1905 if (passInt128VectorsInMem() && Size != 128 &&
1906 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
1907 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
1908 return;
1909
1910 // Arguments of 256-bits are split into four eightbyte chunks. The
1911 // least significant one belongs to class SSE and all the others to class
1912 // SSEUP. The original Lo and Hi design considers that types can't be
1913 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1914 // This design isn't correct for 256-bits, but since there're no cases
1915 // where the upper parts would need to be inspected, avoid adding
1916 // complexity and just consider Hi to match the 64-256 part.
1917 //
1918 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1919 // registers if they are "named", i.e. not part of the "..." of a
1920 // variadic function.
1921 //
1922 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1923 // split into eight eightbyte chunks, one SSE and seven SSEUP.
1924 Lo = SSE;
1925 Hi = SSEUp;
1926 }
1927 return;
1928 }
1929
1930 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1931 QualType ET = getContext().getCanonicalType(CT->getElementType());
1932
1933 uint64_t Size = getContext().getTypeSize(Ty);
1934 if (ET->isIntegralOrEnumerationType()) {
1935 if (Size <= 64)
1936 Current = Integer;
1937 else if (Size <= 128)
1938 Lo = Hi = Integer;
1939 } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
1940 ET->isBFloat16Type()) {
1941 Current = SSE;
1942 } else if (ET == getContext().DoubleTy) {
1943 Lo = Hi = SSE;
1944 } else if (ET == getContext().LongDoubleTy) {
1945 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1946 if (LDF == &llvm::APFloat::IEEEquad())
1947 Current = Memory;
1948 else if (LDF == &llvm::APFloat::x87DoubleExtended())
1949 Current = ComplexX87;
1950 else if (LDF == &llvm::APFloat::IEEEdouble())
1951 Lo = Hi = SSE;
1952 else
1953 llvm_unreachable("unexpected long double representation!");
1954 }
1955
1956 // If this complex type crosses an eightbyte boundary then it
1957 // should be split.
1958 uint64_t EB_Real = (OffsetBase) / 64;
1959 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1960 if (Hi == NoClass && EB_Real != EB_Imag)
1961 Hi = Lo;
1962
1963 return;
1964 }
1965
1966 if (const auto *EITy = Ty->getAs<BitIntType>()) {
1967 if (EITy->getNumBits() <= 64)
1968 Current = Integer;
1969 else if (EITy->getNumBits() <= 128)
1970 Lo = Hi = Integer;
1971 // Larger values need to get passed in memory.
1972 return;
1973 }
1974
1975 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1976 // Arrays are treated like structures.
1977
1978 uint64_t Size = getContext().getTypeSize(Ty);
1979
1980 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1981 // than eight eightbytes, ..., it has class MEMORY.
1982 // regcall ABI doesn't have limitation to an object. The only limitation
1983 // is the free registers, which will be checked in computeInfo.
1984 if (!IsRegCall && Size > 512)
1985 return;
1986
1987 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1988 // fields, it has class MEMORY.
1989 //
1990 // Only need to check alignment of array base.
1991 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1992 return;
1993
1994 // Otherwise implement simplified merge. We could be smarter about
1995 // this, but it isn't worth it and would be harder to verify.
1996 Current = NoClass;
1997 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1998 uint64_t ArraySize = AT->getZExtSize();
1999
2000 // The only case a 256-bit wide vector could be used is when the array
2001 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2002 // to work for sizes wider than 128, early check and fallback to memory.
2003 //
2004 if (Size > 128 &&
2005 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2006 return;
2007
2008 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2009 Class FieldLo, FieldHi;
2010 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2011 Lo = merge(Lo, FieldLo);
2012 Hi = merge(Hi, FieldHi);
2013 if (Lo == Memory || Hi == Memory)
2014 break;
2015 }
2016
2017 postMerge(Size, Lo, Hi);
2018 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2019 return;
2020 }
2021
2022 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2023 uint64_t Size = getContext().getTypeSize(Ty);
2024
2025 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2026 // than eight eightbytes, ..., it has class MEMORY.
2027 if (Size > 512)
2028 return;
2029
2030 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2031 // copy constructor or a non-trivial destructor, it is passed by invisible
2032 // reference.
2033 if (getRecordArgABI(RT, getCXXABI()))
2034 return;
2035
2036 const RecordDecl *RD = RT->getDecl();
2037
2038 // Assume variable sized types are passed in memory.
2039 if (RD->hasFlexibleArrayMember())
2040 return;
2041
2042 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2043
2044 // Reset Lo class, this will be recomputed.
2045 Current = NoClass;
2046
2047 // If this is a C++ record, classify the bases first.
2048 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2049 for (const auto &I : CXXRD->bases()) {
2050 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2051 "Unexpected base class!");
2052 const auto *Base =
2053 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2054
2055 // Classify this field.
2056 //
2057 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2058 // single eightbyte, each is classified separately. Each eightbyte gets
2059 // initialized to class NO_CLASS.
2060 Class FieldLo, FieldHi;
2061 uint64_t Offset =
2062 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2063 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2064 Lo = merge(Lo, FieldLo);
2065 Hi = merge(Hi, FieldHi);
2066 if (Lo == Memory || Hi == Memory) {
2067 postMerge(Size, Lo, Hi);
2068 return;
2069 }
2070 }
2071 }
2072
2073 // Classify the fields one at a time, merging the results.
2074 unsigned idx = 0;
2075 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
2077 getContext().getTargetInfo().getTriple().isPS();
2078 bool IsUnion = RT->isUnionType() && !UseClang11Compat;
2079
2080 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2081 i != e; ++i, ++idx) {
2082 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2083 bool BitField = i->isBitField();
2084
2085 // Ignore padding bit-fields.
2086 if (BitField && i->isUnnamedBitField())
2087 continue;
2088
2089 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2090 // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
2091 //
2092 // The only case a 256-bit or a 512-bit wide vector could be used is when
2093 // the struct contains a single 256-bit or 512-bit element. Early check
2094 // and fallback to memory.
2095 //
2096 // FIXME: Extended the Lo and Hi logic properly to work for size wider
2097 // than 128.
2098 if (Size > 128 &&
2099 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
2100 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2101 Lo = Memory;
2102 postMerge(Size, Lo, Hi);
2103 return;
2104 }
2105
2106 bool IsInMemory =
2107 Offset % getContext().getTypeAlign(i->getType().getCanonicalType());
2108 // Note, skip this test for bit-fields, see below.
2109 if (!BitField && IsInMemory) {
2110 Lo = Memory;
2111 postMerge(Size, Lo, Hi);
2112 return;
2113 }
2114
2115 // Classify this field.
2116 //
2117 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2118 // exceeds a single eightbyte, each is classified
2119 // separately. Each eightbyte gets initialized to class
2120 // NO_CLASS.
2121 Class FieldLo, FieldHi;
2122
2123 // Bit-fields require special handling, they do not force the
2124 // structure to be passed in memory even if unaligned, and
2125 // therefore they can straddle an eightbyte.
2126 if (BitField) {
2127 assert(!i->isUnnamedBitField());
2128 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2129 uint64_t Size = i->getBitWidthValue(getContext());
2130
2131 uint64_t EB_Lo = Offset / 64;
2132 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2133
2134 if (EB_Lo) {
2135 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2136 FieldLo = NoClass;
2137 FieldHi = Integer;
2138 } else {
2139 FieldLo = Integer;
2140 FieldHi = EB_Hi ? Integer : NoClass;
2141 }
2142 } else
2143 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2144 Lo = merge(Lo, FieldLo);
2145 Hi = merge(Hi, FieldHi);
2146 if (Lo == Memory || Hi == Memory)
2147 break;
2148 }
2149
2150 postMerge(Size, Lo, Hi);
2151 }
2152}
2153
2154ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2155 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2156 // place naturally.
2157 if (!isAggregateTypeForABI(Ty)) {
2158 // Treat an enum type as its underlying type.
2159 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2160 Ty = EnumTy->getDecl()->getIntegerType();
2161
2162 if (Ty->isBitIntType())
2163 return getNaturalAlignIndirect(Ty);
2164
2165 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2167 }
2168
2169 return getNaturalAlignIndirect(Ty);
2170}
2171
2172bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2173 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2174 uint64_t Size = getContext().getTypeSize(VecTy);
2175 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2176 if (Size <= 64 || Size > LargestVector)
2177 return true;
2178 QualType EltTy = VecTy->getElementType();
2179 if (passInt128VectorsInMem() &&
2180 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2181 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2182 return true;
2183 }
2184
2185 return false;
2186}
2187
2188ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2189 unsigned freeIntRegs) const {
2190 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2191 // place naturally.
2192 //
2193 // This assumption is optimistic, as there could be free registers available
2194 // when we need to pass this argument in memory, and LLVM could try to pass
2195 // the argument in the free register. This does not seem to happen currently,
2196 // but this code would be much safer if we could mark the argument with
2197 // 'onstack'. See PR12193.
2198 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
2199 !Ty->isBitIntType()) {
2200 // Treat an enum type as its underlying type.
2201 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2202 Ty = EnumTy->getDecl()->getIntegerType();
2203
2204 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2206 }
2207
2208 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2209 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2210
2211 // Compute the byval alignment. We specify the alignment of the byval in all
2212 // cases so that the mid-level optimizer knows the alignment of the byval.
2213 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2214
2215 // Attempt to avoid passing indirect results using byval when possible. This
2216 // is important for good codegen.
2217 //
2218 // We do this by coercing the value into a scalar type which the backend can
2219 // handle naturally (i.e., without using byval).
2220 //
2221 // For simplicity, we currently only do this when we have exhausted all of the
2222 // free integer registers. Doing this when there are free integer registers
2223 // would require more care, as we would have to ensure that the coerced value
2224 // did not claim the unused register. That would require either reording the
2225 // arguments to the function (so that any subsequent inreg values came first),
2226 // or only doing this optimization when there were no following arguments that
2227 // might be inreg.
2228 //
2229 // We currently expect it to be rare (particularly in well written code) for
2230 // arguments to be passed on the stack when there are still free integer
2231 // registers available (this would typically imply large structs being passed
2232 // by value), so this seems like a fair tradeoff for now.
2233 //
2234 // We can revisit this if the backend grows support for 'onstack' parameter
2235 // attributes. See PR12193.
2236 if (freeIntRegs == 0) {
2237 uint64_t Size = getContext().getTypeSize(Ty);
2238
2239 // If this type fits in an eightbyte, coerce it into the matching integral
2240 // type, which will end up on the stack (with alignment 8).
2241 if (Align == 8 && Size <= 64)
2242 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2243 Size));
2244 }
2245
2247}
2248
2249/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2250/// register. Pick an LLVM IR type that will be passed as a vector register.
2251llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2252 // Wrapper structs/arrays that only contain vectors are passed just like
2253 // vectors; strip them off if present.
2254 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2255 Ty = QualType(InnerTy, 0);
2256
2257 llvm::Type *IRType = CGT.ConvertType(Ty);
2258 if (isa<llvm::VectorType>(IRType)) {
2259 // Don't pass vXi128 vectors in their native type, the backend can't
2260 // legalize them.
2261 if (passInt128VectorsInMem() &&
2262 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
2263 // Use a vXi64 vector.
2264 uint64_t Size = getContext().getTypeSize(Ty);
2265 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
2266 Size / 64);
2267 }
2268
2269 return IRType;
2270 }
2271
2272 if (IRType->getTypeID() == llvm::Type::FP128TyID)
2273 return IRType;
2274
2275 // We couldn't find the preferred IR vector type for 'Ty'.
2276 uint64_t Size = getContext().getTypeSize(Ty);
2277 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2278
2279
2280 // Return a LLVM IR vector type based on the size of 'Ty'.
2281 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2282 Size / 64);
2283}
2284
2285/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2286/// is known to either be off the end of the specified type or being in
2287/// alignment padding. The user type specified is known to be at most 128 bits
2288/// in size, and have passed through X86_64ABIInfo::classify with a successful
2289/// classification that put one of the two halves in the INTEGER class.
2290///
2291/// It is conservatively correct to return false.
2292static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2293 unsigned EndBit, ASTContext &Context) {
2294 // If the bytes being queried are off the end of the type, there is no user
2295 // data hiding here. This handles analysis of builtins, vectors and other
2296 // types that don't contain interesting padding.
2297 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2298 if (TySize <= StartBit)
2299 return true;
2300
2301 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2302 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2303 unsigned NumElts = (unsigned)AT->getZExtSize();
2304
2305 // Check each element to see if the element overlaps with the queried range.
2306 for (unsigned i = 0; i != NumElts; ++i) {
2307 // If the element is after the span we care about, then we're done..
2308 unsigned EltOffset = i*EltSize;
2309 if (EltOffset >= EndBit) break;
2310
2311 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2312 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2313 EndBit-EltOffset, Context))
2314 return false;
2315 }
2316 // If it overlaps no elements, then it is safe to process as padding.
2317 return true;
2318 }
2319
2320 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2321 const RecordDecl *RD = RT->getDecl();
2322 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2323
2324 // If this is a C++ record, check the bases first.
2325 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2326 for (const auto &I : CXXRD->bases()) {
2327 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2328 "Unexpected base class!");
2329 const auto *Base =
2330 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2331
2332 // If the base is after the span we care about, ignore it.
2333 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2334 if (BaseOffset >= EndBit) continue;
2335
2336 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2337 if (!BitsContainNoUserData(I.getType(), BaseStart,
2338 EndBit-BaseOffset, Context))
2339 return false;
2340 }
2341 }
2342
2343 // Verify that no field has data that overlaps the region of interest. Yes
2344 // this could be sped up a lot by being smarter about queried fields,
2345 // however we're only looking at structs up to 16 bytes, so we don't care
2346 // much.
2347 unsigned idx = 0;
2348 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2349 i != e; ++i, ++idx) {
2350 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2351
2352 // If we found a field after the region we care about, then we're done.
2353 if (FieldOffset >= EndBit) break;
2354
2355 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2356 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2357 Context))
2358 return false;
2359 }
2360
2361 // If nothing in this record overlapped the area of interest, then we're
2362 // clean.
2363 return true;
2364 }
2365
2366 return false;
2367}
2368
2369/// getFPTypeAtOffset - Return a floating point type at the specified offset.
2370static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2371 const llvm::DataLayout &TD) {
2372 if (IROffset == 0 && IRType->isFloatingPointTy())
2373 return IRType;
2374
2375 // If this is a struct, recurse into the field at the specified offset.
2376 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2377 if (!STy->getNumContainedTypes())
2378 return nullptr;
2379
2380 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2381 unsigned Elt = SL->getElementContainingOffset(IROffset);
2382 IROffset -= SL->getElementOffset(Elt);
2383 return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
2384 }
2385
2386 // If this is an array, recurse into the field at the specified offset.
2387 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2388 llvm::Type *EltTy = ATy->getElementType();
2389 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2390 IROffset -= IROffset / EltSize * EltSize;
2391 return getFPTypeAtOffset(EltTy, IROffset, TD);
2392 }
2393
2394 return nullptr;
2395}
2396
2397/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2398/// low 8 bytes of an XMM register, corresponding to the SSE class.
2399llvm::Type *X86_64ABIInfo::
2400GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2401 QualType SourceTy, unsigned SourceOffset) const {
2402 const llvm::DataLayout &TD = getDataLayout();
2403 unsigned SourceSize =
2404 (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
2405 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
2406 if (!T0 || T0->isDoubleTy())
2407 return llvm::Type::getDoubleTy(getVMContext());
2408
2409 // Get the adjacent FP type.
2410 llvm::Type *T1 = nullptr;
2411 unsigned T0Size = TD.getTypeAllocSize(T0);
2412 if (SourceSize > T0Size)
2413 T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
2414 if (T1 == nullptr) {
2415 // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
2416 // to its alignment.
2417 if (T0->is16bitFPTy() && SourceSize > 4)
2418 T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2419 // If we can't get a second FP type, return a simple half or float.
2420 // avx512fp16-abi.c:pr51813_2 shows it works to return float for
2421 // {float, i8} too.
2422 if (T1 == nullptr)
2423 return T0;
2424 }
2425
2426 if (T0->isFloatTy() && T1->isFloatTy())
2427 return llvm::FixedVectorType::get(T0, 2);
2428
2429 if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
2430 llvm::Type *T2 = nullptr;
2431 if (SourceSize > 4)
2432 T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2433 if (T2 == nullptr)
2434 return llvm::FixedVectorType::get(T0, 2);
2435 return llvm::FixedVectorType::get(T0, 4);
2436 }
2437
2438 if (T0->is16bitFPTy() || T1->is16bitFPTy())
2439 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
2440
2441 return llvm::Type::getDoubleTy(getVMContext());
2442}
2443
2444
2445/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2446/// an 8-byte GPR. This means that we either have a scalar or we are talking
2447/// about the high or low part of an up-to-16-byte struct. This routine picks
2448/// the best LLVM IR type to represent this, which may be i64 or may be anything
2449/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2450/// etc).
2451///
2452/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2453/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2454/// the 8-byte value references. PrefType may be null.
2455///
2456/// SourceTy is the source-level type for the entire argument. SourceOffset is
2457/// an offset into this that we're processing (which is always either 0 or 8).
2458///
2459llvm::Type *X86_64ABIInfo::
2460GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2461 QualType SourceTy, unsigned SourceOffset) const {
2462 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2463 // returning an 8-byte unit starting with it. See if we can safely use it.
2464 if (IROffset == 0) {
2465 // Pointers and int64's always fill the 8-byte unit.
2466 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2467 IRType->isIntegerTy(64))
2468 return IRType;
2469
2470 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2471 // goodness in the source type is just tail padding. This is allowed to
2472 // kick in for struct {double,int} on the int, but not on
2473 // struct{double,int,int} because we wouldn't return the second int. We
2474 // have to do this analysis on the source type because we can't depend on
2475 // unions being lowered a specific way etc.
2476 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
2477 IRType->isIntegerTy(32) ||
2478 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2479 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2480 cast<llvm::IntegerType>(IRType)->getBitWidth();
2481
2482 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2483 SourceOffset*8+64, getContext()))
2484 return IRType;
2485 }
2486 }
2487
2488 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2489 // If this is a struct, recurse into the field at the specified offset.
2490 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
2491 if (IROffset < SL->getSizeInBytes()) {
2492 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2493 IROffset -= SL->getElementOffset(FieldIdx);
2494
2495 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2496 SourceTy, SourceOffset);
2497 }
2498 }
2499
2500 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2501 llvm::Type *EltTy = ATy->getElementType();
2502 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
2503 unsigned EltOffset = IROffset/EltSize*EltSize;
2504 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2505 SourceOffset);
2506 }
2507
2508 // Okay, we don't have any better idea of what to pass, so we pass this in an
2509 // integer register that isn't too big to fit the rest of the struct.
2510 unsigned TySizeInBytes =
2511 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
2512
2513 assert(TySizeInBytes != SourceOffset && "Empty field?");
2514
2515 // It is always safe to classify this as an integer type up to i64 that
2516 // isn't larger than the structure.
2517 return llvm::IntegerType::get(getVMContext(),
2518 std::min(TySizeInBytes-SourceOffset, 8U)*8);
2519}
2520
2521
2522/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2523/// be used as elements of a two register pair to pass or return, return a
2524/// first class aggregate to represent them. For example, if the low part of
2525/// a by-value argument should be passed as i32* and the high part as float,
2526/// return {i32*, float}.
2527static llvm::Type *
2528GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2529 const llvm::DataLayout &TD) {
2530 // In order to correctly satisfy the ABI, we need to the high part to start
2531 // at offset 8. If the high and low parts we inferred are both 4-byte types
2532 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2533 // the second element at offset 8. Check for this:
2534 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2535 llvm::Align HiAlign = TD.getABITypeAlign(Hi);
2536 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
2537 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2538
2539 // To handle this, we have to increase the size of the low part so that the
2540 // second element will start at an 8 byte offset. We can't increase the size
2541 // of the second element because it might make us access off the end of the
2542 // struct.
2543 if (HiStart != 8) {
2544 // There are usually two sorts of types the ABI generation code can produce
2545 // for the low part of a pair that aren't 8 bytes in size: half, float or
2546 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2547 // NaCl).
2548 // Promote these to a larger type.
2549 if (Lo->isHalfTy() || Lo->isFloatTy())
2550 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2551 else {
2552 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2553 && "Invalid/unknown lo type");
2554 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2555 }
2556 }
2557
2558 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
2559
2560 // Verify that the second element is at an 8-byte offset.
2561 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2562 "Invalid x86-64 argument pair!");
2563 return Result;
2564}
2565
2566ABIArgInfo X86_64ABIInfo::
2567classifyReturnType(QualType RetTy) const {
2568 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2569 // classification algorithm.
2570 X86_64ABIInfo::Class Lo, Hi;
2571 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
2572
2573 // Check some invariants.
2574 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2575 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2576
2577 llvm::Type *ResType = nullptr;
2578 switch (Lo) {
2579 case NoClass:
2580 if (Hi == NoClass)
2581 return ABIArgInfo::getIgnore();
2582 // If the low part is just padding, it takes no register, leave ResType
2583 // null.
2584 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2585 "Unknown missing lo part");
2586 break;
2587
2588 case SSEUp:
2589 case X87Up:
2590 llvm_unreachable("Invalid classification for lo word.");
2591
2592 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2593 // hidden argument.
2594 case Memory:
2595 return getIndirectReturnResult(RetTy);
2596
2597 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2598 // available register of the sequence %rax, %rdx is used.
2599 case Integer:
2600 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2601
2602 // If we have a sign or zero extended integer, make sure to return Extend
2603 // so that the parameter gets the right LLVM IR attributes.
2604 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2605 // Treat an enum type as its underlying type.
2606 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2607 RetTy = EnumTy->getDecl()->getIntegerType();
2608
2609 if (RetTy->isIntegralOrEnumerationType() &&
2610 isPromotableIntegerTypeForABI(RetTy))
2611 return ABIArgInfo::getExtend(RetTy);
2612 }
2613 break;
2614
2615 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2616 // available SSE register of the sequence %xmm0, %xmm1 is used.
2617 case SSE:
2618 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2619 break;
2620
2621 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2622 // returned on the X87 stack in %st0 as 80-bit x87 number.
2623 case X87:
2624 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2625 break;
2626
2627 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2628 // part of the value is returned in %st0 and the imaginary part in
2629 // %st1.
2630 case ComplexX87:
2631 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2632 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2633 llvm::Type::getX86_FP80Ty(getVMContext()));
2634 break;
2635 }
2636
2637 llvm::Type *HighPart = nullptr;
2638 switch (Hi) {
2639 // Memory was handled previously and X87 should
2640 // never occur as a hi class.
2641 case Memory:
2642 case X87:
2643 llvm_unreachable("Invalid classification for hi word.");
2644
2645 case ComplexX87: // Previously handled.
2646 case NoClass:
2647 break;
2648
2649 case Integer:
2650 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2651 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2652 return ABIArgInfo::getDirect(HighPart, 8);
2653 break;
2654 case SSE:
2655 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2656 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2657 return ABIArgInfo::getDirect(HighPart, 8);
2658 break;
2659
2660 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2661 // is passed in the next available eightbyte chunk if the last used
2662 // vector register.
2663 //
2664 // SSEUP should always be preceded by SSE, just widen.
2665 case SSEUp:
2666 assert(Lo == SSE && "Unexpected SSEUp classification.");
2667 ResType = GetByteVectorType(RetTy);
2668 break;
2669
2670 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2671 // returned together with the previous X87 value in %st0.
2672 case X87Up:
2673 // If X87Up is preceded by X87, we don't need to do
2674 // anything. However, in some cases with unions it may not be
2675 // preceded by X87. In such situations we follow gcc and pass the
2676 // extra bits in an SSE reg.
2677 if (Lo != X87) {
2678 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2679 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2680 return ABIArgInfo::getDirect(HighPart, 8);
2681 }
2682 break;
2683 }
2684
2685 // If a high part was specified, merge it together with the low part. It is
2686 // known to pass in the high eightbyte of the result. We do this by forming a
2687 // first class struct aggregate with the high and low part: {low, high}
2688 if (HighPart)
2689 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2690
2691 return ABIArgInfo::getDirect(ResType);
2692}
2693
2695X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2696 unsigned &neededInt, unsigned &neededSSE,
2697 bool isNamedArg, bool IsRegCall) const {
2699
2700 X86_64ABIInfo::Class Lo, Hi;
2701 classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
2702
2703 // Check some invariants.
2704 // FIXME: Enforce these by construction.
2705 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2706 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2707
2708 neededInt = 0;
2709 neededSSE = 0;
2710 llvm::Type *ResType = nullptr;
2711 switch (Lo) {
2712 case NoClass:
2713 if (Hi == NoClass)
2714 return ABIArgInfo::getIgnore();
2715 // If the low part is just padding, it takes no register, leave ResType
2716 // null.
2717 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2718 "Unknown missing lo part");
2719 break;
2720
2721 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2722 // on the stack.
2723 case Memory:
2724
2725 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2726 // COMPLEX_X87, it is passed in memory.
2727 case X87:
2728 case ComplexX87:
2729 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
2730 ++neededInt;
2731 return getIndirectResult(Ty, freeIntRegs);
2732
2733 case SSEUp:
2734 case X87Up:
2735 llvm_unreachable("Invalid classification for lo word.");
2736
2737 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2738 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2739 // and %r9 is used.
2740 case Integer:
2741 ++neededInt;
2742
2743 // Pick an 8-byte type based on the preferred type.
2744 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2745
2746 // If we have a sign or zero extended integer, make sure to return Extend
2747 // so that the parameter gets the right LLVM IR attributes.
2748 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2749 // Treat an enum type as its underlying type.
2750 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2751 Ty = EnumTy->getDecl()->getIntegerType();
2752
2753 if (Ty->isIntegralOrEnumerationType() &&
2754 isPromotableIntegerTypeForABI(Ty))
2755 return ABIArgInfo::getExtend(Ty);
2756 }
2757
2758 break;
2759
2760 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2761 // available SSE register is used, the registers are taken in the
2762 // order from %xmm0 to %xmm7.
2763 case SSE: {
2764 llvm::Type *IRType = CGT.ConvertType(Ty);
2765 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2766 ++neededSSE;
2767 break;
2768 }
2769 }
2770
2771 llvm::Type *HighPart = nullptr;
2772 switch (Hi) {
2773 // Memory was handled previously, ComplexX87 and X87 should
2774 // never occur as hi classes, and X87Up must be preceded by X87,
2775 // which is passed in memory.
2776 case Memory:
2777 case X87:
2778 case ComplexX87:
2779 llvm_unreachable("Invalid classification for hi word.");
2780
2781 case NoClass: break;
2782
2783 case Integer:
2784 ++neededInt;
2785 // Pick an 8-byte type based on the preferred type.
2786 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2787
2788 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2789 return ABIArgInfo::getDirect(HighPart, 8);
2790 break;
2791
2792 // X87Up generally doesn't occur here (long double is passed in
2793 // memory), except in situations involving unions.
2794 case X87Up:
2795 case SSE:
2796 ++neededSSE;
2797 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2798
2799 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2800 return ABIArgInfo::getDirect(HighPart, 8);
2801 break;
2802
2803 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2804 // eightbyte is passed in the upper half of the last used SSE
2805 // register. This only happens when 128-bit vectors are passed.
2806 case SSEUp:
2807 assert(Lo == SSE && "Unexpected SSEUp classification");
2808 ResType = GetByteVectorType(Ty);
2809 break;
2810 }
2811
2812 // If a high part was specified, merge it together with the low part. It is
2813 // known to pass in the high eightbyte of the result. We do this by forming a
2814 // first class struct aggregate with the high and low part: {low, high}
2815 if (HighPart)
2816 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2817
2818 return ABIArgInfo::getDirect(ResType);
2819}
2820
2822X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2823 unsigned &NeededSSE,
2824 unsigned &MaxVectorWidth) const {
2825 auto RT = Ty->getAs<RecordType>();
2826 assert(RT && "classifyRegCallStructType only valid with struct types");
2827
2828 if (RT->getDecl()->hasFlexibleArrayMember())
2829 return getIndirectReturnResult(Ty);
2830
2831 // Sum up bases
2832 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2833 if (CXXRD->isDynamicClass()) {
2834 NeededInt = NeededSSE = 0;
2835 return getIndirectReturnResult(Ty);
2836 }
2837
2838 for (const auto &I : CXXRD->bases())
2839 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
2840 MaxVectorWidth)
2841 .isIndirect()) {
2842 NeededInt = NeededSSE = 0;
2843 return getIndirectReturnResult(Ty);
2844 }
2845 }
2846
2847 // Sum up members
2848 for (const auto *FD : RT->getDecl()->fields()) {
2849 QualType MTy = FD->getType();
2850 if (MTy->isRecordType() && !MTy->isUnionType()) {
2851 if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
2852 MaxVectorWidth)
2853 .isIndirect()) {
2854 NeededInt = NeededSSE = 0;
2855 return getIndirectReturnResult(Ty);
2856 }
2857 } else {
2858 unsigned LocalNeededInt, LocalNeededSSE;
2859 if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
2860 true, true)
2861 .isIndirect()) {
2862 NeededInt = NeededSSE = 0;
2863 return getIndirectReturnResult(Ty);
2864 }
2865 if (const auto *AT = getContext().getAsConstantArrayType(MTy))
2866 MTy = AT->getElementType();
2867 if (const auto *VT = MTy->getAs<VectorType>())
2868 if (getContext().getTypeSize(VT) > MaxVectorWidth)
2869 MaxVectorWidth = getContext().getTypeSize(VT);
2870 NeededInt += LocalNeededInt;
2871 NeededSSE += LocalNeededSSE;
2872 }
2873 }
2874
2875 return ABIArgInfo::getDirect();
2876}
2877
2879X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2880 unsigned &NeededSSE,
2881 unsigned &MaxVectorWidth) const {
2882
2883 NeededInt = 0;
2884 NeededSSE = 0;
2885 MaxVectorWidth = 0;
2886
2887 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
2888 MaxVectorWidth);
2889}
2890
2891void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2892
2893 const unsigned CallingConv = FI.getCallingConvention();
2894 // It is possible to force Win64 calling convention on any x86_64 target by
2895 // using __attribute__((ms_abi)). In such case to correctly emit Win64
2896 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
2897 if (CallingConv == llvm::CallingConv::Win64) {
2898 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
2899 Win64ABIInfo.computeInfo(FI);
2900 return;
2901 }
2902
2903 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
2904
2905 // Keep track of the number of assigned registers.
2906 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
2907 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
2908 unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
2909
2910 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
2911 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
2912 !FI.getReturnType()->getTypePtr()->isUnionType()) {
2913 FI.getReturnInfo() = classifyRegCallStructType(
2914 FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
2915 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
2916 FreeIntRegs -= NeededInt;
2917 FreeSSERegs -= NeededSSE;
2918 } else {
2919 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2920 }
2921 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
2922 getContext().getCanonicalType(FI.getReturnType()
2923 ->getAs<ComplexType>()
2924 ->getElementType()) ==
2925 getContext().LongDoubleTy)
2926 // Complex Long Double Type is passed in Memory when Regcall
2927 // calling convention is used.
2928 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2929 else
2931 }
2932
2933 // If the return value is indirect, then the hidden argument is consuming one
2934 // integer register.
2935 if (FI.getReturnInfo().isIndirect())
2936 --FreeIntRegs;
2937 else if (NeededSSE && MaxVectorWidth > 0)
2938 FI.setMaxVectorWidth(MaxVectorWidth);
2939
2940 // The chain argument effectively gives us another free register.
2941 if (FI.isChainCall())
2942 ++FreeIntRegs;
2943
2944 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
2945 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2946 // get assigned (in left-to-right order) for passing as follows...
2947 unsigned ArgNo = 0;
2948 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2949 it != ie; ++it, ++ArgNo) {
2950 bool IsNamedArg = ArgNo < NumRequiredArgs;
2951
2952 if (IsRegCall && it->type->isStructureOrClassType())
2953 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
2954 MaxVectorWidth);
2955 else
2956 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
2957 NeededSSE, IsNamedArg);
2958
2959 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2960 // eightbyte of an argument, the whole argument is passed on the
2961 // stack. If registers have already been assigned for some
2962 // eightbytes of such an argument, the assignments get reverted.
2963 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
2964 FreeIntRegs -= NeededInt;
2965 FreeSSERegs -= NeededSSE;
2966 if (MaxVectorWidth > FI.getMaxVectorWidth())
2967 FI.setMaxVectorWidth(MaxVectorWidth);
2968 } else {
2969 it->info = getIndirectResult(it->type, FreeIntRegs);
2970 }
2971 }
2972}
2973
2975 Address VAListAddr, QualType Ty) {
2976 Address overflow_arg_area_p =
2977 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2978 llvm::Value *overflow_arg_area =
2979 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2980
2981 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2982 // byte boundary if alignment needed by type exceeds 8 byte boundary.
2983 // It isn't stated explicitly in the standard, but in practice we use
2984 // alignment greater than 16 where necessary.
2985 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
2986 if (Align > CharUnits::fromQuantity(8)) {
2987 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
2988 Align);
2989 }
2990
2991 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2992 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2993 llvm::Value *Res = overflow_arg_area;
2994
2995 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2996 // l->overflow_arg_area + sizeof(type).
2997 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2998 // an 8 byte boundary.
2999
3000 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3001 llvm::Value *Offset =
3002 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3003 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
3004 Offset, "overflow_arg_area.next");
3005 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3006
3007 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3008 return Address(Res, LTy, Align);
3009}
3010
3011RValue X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3012 QualType Ty, AggValueSlot Slot) const {
3013 // Assume that va_list type is correct; should be pointer to LLVM type:
3014 // struct {
3015 // i32 gp_offset;
3016 // i32 fp_offset;
3017 // i8* overflow_arg_area;
3018 // i8* reg_save_area;
3019 // };
3020 unsigned neededInt, neededSSE;
3021
3022 Ty = getContext().getCanonicalType(Ty);
3023 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3024 /*isNamedArg*/false);
3025
3026 // Empty records are ignored for parameter passing purposes.
3027 if (AI.isIgnore())
3028 return Slot.asRValue();
3029
3030 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3031 // in the registers. If not go to step 7.
3032 if (!neededInt && !neededSSE)
3033 return CGF.EmitLoadOfAnyValue(
3034 CGF.MakeAddrLValue(EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty), Ty),
3035 Slot);
3036
3037 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3038 // general purpose registers needed to pass type and num_fp to hold
3039 // the number of floating point registers needed.
3040
3041 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3042 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3043 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3044 //
3045 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3046 // register save space).
3047
3048 llvm::Value *InRegs = nullptr;
3049 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3050 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3051 if (neededInt) {
3052 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3053 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3054 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3055 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3056 }
3057
3058 if (neededSSE) {
3059 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3060 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3061 llvm::Value *FitsInFP =
3062 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3063 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3064 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3065 }
3066
3067 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3068 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3069 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3070 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3071
3072 // Emit code to load the value if it was passed in registers.
3073
3074 CGF.EmitBlock(InRegBlock);
3075
3076 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3077 // an offset of l->gp_offset and/or l->fp_offset. This may require
3078 // copying to a temporary location in case the parameter is passed
3079 // in different register classes or requires an alignment greater
3080 // than 8 for general purpose registers and 16 for XMM registers.
3081 //
3082 // FIXME: This really results in shameful code when we end up needing to
3083 // collect arguments from different places; often what should result in a
3084 // simple assembling of a structure from scattered addresses has many more
3085 // loads than necessary. Can we clean this up?
3086 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3087 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3088 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3089
3090 Address RegAddr = Address::invalid();
3091 if (neededInt && neededSSE) {
3092 // FIXME: Cleanup.
3093 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3094 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3095 Address Tmp = CGF.CreateMemTemp(Ty);
3096 Tmp = Tmp.withElementType(ST);
3097 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3098 llvm::Type *TyLo = ST->getElementType(0);
3099 llvm::Type *TyHi = ST->getElementType(1);
3100 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3101 "Unexpected ABI info for mixed regs");
3102 llvm::Value *GPAddr =
3103 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
3104 llvm::Value *FPAddr =
3105 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
3106 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3107 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3108
3109 // Copy the first element.
3110 // FIXME: Our choice of alignment here and below is probably pessimistic.
3111 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3112 TyLo, RegLoAddr,
3113 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyLo)));
3114 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3115
3116 // Copy the second element.
3118 TyHi, RegHiAddr,
3119 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
3120 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3121
3122 RegAddr = Tmp.withElementType(LTy);
3123 } else if (neededInt) {
3124 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
3125 LTy, CharUnits::fromQuantity(8));
3126
3127 // Copy to a temporary if necessary to ensure the appropriate alignment.
3128 auto TInfo = getContext().getTypeInfoInChars(Ty);
3129 uint64_t TySize = TInfo.Width.getQuantity();
3130 CharUnits TyAlign = TInfo.Align;
3131
3132 // Copy into a temporary if the type is more aligned than the
3133 // register save area.
3134 if (TyAlign.getQuantity() > 8) {
3135 Address Tmp = CGF.CreateMemTemp(Ty);
3136 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3137 RegAddr = Tmp;
3138 }
3139
3140 } else if (neededSSE == 1) {
3141 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
3142 LTy, CharUnits::fromQuantity(16));
3143 } else {
3144 assert(neededSSE == 2 && "Invalid number of needed registers!");
3145 // SSE registers are spaced 16 bytes apart in the register save
3146 // area, we need to collect the two eightbytes together.
3147 // The ABI isn't explicit about this, but it seems reasonable
3148 // to assume that the slots are 16-byte aligned, since the stack is
3149 // naturally 16-byte aligned and the prologue is expected to store
3150 // all the SSE registers to the RSA.
3151 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
3152 fp_offset),
3154 Address RegAddrHi =
3155 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3157 llvm::Type *ST = AI.canHaveCoerceToType()
3158 ? AI.getCoerceToType()
3159 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3160 llvm::Value *V;
3161 Address Tmp = CGF.CreateMemTemp(Ty);
3162 Tmp = Tmp.withElementType(ST);
3163 V = CGF.Builder.CreateLoad(
3164 RegAddrLo.withElementType(ST->getStructElementType(0)));
3165 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3166 V = CGF.Builder.CreateLoad(
3167 RegAddrHi.withElementType(ST->getStructElementType(1)));
3168 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3169
3170 RegAddr = Tmp.withElementType(LTy);
3171 }
3172
3173 // AMD64-ABI 3.5.7p5: Step 5. Set:
3174 // l->gp_offset = l->gp_offset + num_gp * 8
3175 // l->fp_offset = l->fp_offset + num_fp * 16.
3176 if (neededInt) {
3177 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3178 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3179 gp_offset_p);
3180 }
3181 if (neededSSE) {
3182 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3183 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3184 fp_offset_p);
3185 }
3186 CGF.EmitBranch(ContBlock);
3187
3188 // Emit code to load the value if it was passed in memory.
3189
3190 CGF.EmitBlock(InMemBlock);
3191 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3192
3193 // Return the appropriate result.
3194
3195 CGF.EmitBlock(ContBlock);
3196 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3197 "vaarg.addr");
3198 return CGF.EmitLoadOfAnyValue(CGF.MakeAddrLValue(ResAddr, Ty), Slot);
3199}
3200
3201RValue X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3202 QualType Ty, AggValueSlot Slot) const {
3203 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3204 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3205 uint64_t Width = getContext().getTypeSize(Ty);
3206 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3207
3208 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3211 /*allowHigherAlign*/ false, Slot);
3212}
3213
3214ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
3215 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
3216 const Type *Base = nullptr;
3217 uint64_t NumElts = 0;
3218
3219 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3220 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3221 FreeSSERegs -= NumElts;
3222 return getDirectX86Hva();
3223 }
3224 return current;
3225}
3226
3227ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3228 bool IsReturnType, bool IsVectorCall,
3229 bool IsRegCall) const {
3230
3231 if (Ty->isVoidType())
3232 return ABIArgInfo::getIgnore();
3233
3234 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3235 Ty = EnumTy->getDecl()->getIntegerType();
3236
3237 TypeInfo Info = getContext().getTypeInfo(Ty);
3238 uint64_t Width = Info.Width;
3239 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3240
3241 const RecordType *RT = Ty->getAs<RecordType>();
3242 if (RT) {
3243 if (!IsReturnType) {
3244 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3245 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3246 }
3247
3248 if (RT->getDecl()->hasFlexibleArrayMember())
3249 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3250
3251 }
3252
3253 const Type *Base = nullptr;
3254 uint64_t NumElts = 0;
3255 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3256 // other targets.
3257 if ((IsVectorCall || IsRegCall) &&
3258 isHomogeneousAggregate(Ty, Base, NumElts)) {
3259 if (IsRegCall) {
3260 if (FreeSSERegs >= NumElts) {
3261 FreeSSERegs -= NumElts;
3262 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3263 return ABIArgInfo::getDirect();
3264 return ABIArgInfo::getExpand();
3265 }
3266 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3267 } else if (IsVectorCall) {
3268 if (FreeSSERegs >= NumElts &&
3269 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3270 FreeSSERegs -= NumElts;
3271 return ABIArgInfo::getDirect();
3272 } else if (IsReturnType) {
3273 return ABIArgInfo::getExpand();
3274 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3275 // HVAs are delayed and reclassified in the 2nd step.
3276 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3277 }
3278 }
3279 }
3280
3281 if (Ty->isMemberPointerType()) {
3282 // If the member pointer is represented by an LLVM int or ptr, pass it
3283 // directly.
3284 llvm::Type *LLTy = CGT.ConvertType(Ty);
3285 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3286 return ABIArgInfo::getDirect();
3287 }
3288
3289 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3290 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3291 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3292 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3293 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3294
3295 // Otherwise, coerce it to a small integer.
3296 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3297 }
3298
3299 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3300 switch (BT->getKind()) {
3301 case BuiltinType::Bool:
3302 // Bool type is always extended to the ABI, other builtin types are not
3303 // extended.
3304 return ABIArgInfo::getExtend(Ty);
3305
3306 case BuiltinType::LongDouble:
3307 // Mingw64 GCC uses the old 80 bit extended precision floating point
3308 // unit. It passes them indirectly through memory.
3309 if (IsMingw64) {
3310 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3311 if (LDF == &llvm::APFloat::x87DoubleExtended())
3312 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3313 }
3314 break;
3315
3316 case BuiltinType::Int128:
3317 case BuiltinType::UInt128:
3318 // If it's a parameter type, the normal ABI rule is that arguments larger
3319 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3320 // even though it isn't particularly efficient.
3321 if (!IsReturnType)
3322 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3323
3324 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3325 // Clang matches them for compatibility.
3326 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
3327 llvm::Type::getInt64Ty(getVMContext()), 2));
3328
3329 default:
3330 break;
3331 }
3332 }
3333
3334 if (Ty->isBitIntType()) {
3335 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3336 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3337 // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
3338 // or 8 bytes anyway as long is it fits in them, so we don't have to check
3339 // the power of 2.
3340 if (Width <= 64)
3341 return ABIArgInfo::getDirect();
3342 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3343 }
3344
3345 return ABIArgInfo::getDirect();
3346}
3347
3348void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3349 const unsigned CC = FI.getCallingConvention();
3350 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
3351 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
3352
3353 // If __attribute__((sysv_abi)) is in use, use the SysV argument
3354 // classification rules.
3355 if (CC == llvm::CallingConv::X86_64_SysV) {
3356 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
3357 SysVABIInfo.computeInfo(FI);
3358 return;
3359 }
3360
3361 unsigned FreeSSERegs = 0;
3362 if (IsVectorCall) {
3363 // We can use up to 4 SSE return registers with vectorcall.
3364 FreeSSERegs = 4;
3365 } else if (IsRegCall) {
3366 // RegCall gives us 16 SSE registers.
3367 FreeSSERegs = 16;
3368 }
3369
3370 if (!getCXXABI().classifyReturnType(FI))
3371 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3372 IsVectorCall, IsRegCall);
3373
3374 if (IsVectorCall) {
3375 // We can use up to 6 SSE register parameters with vectorcall.
3376 FreeSSERegs = 6;
3377 } else if (IsRegCall) {
3378 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3379 FreeSSERegs = 16;
3380 }
3381
3382 unsigned ArgNum = 0;
3383 unsigned ZeroSSERegs = 0;
3384 for (auto &I : FI.arguments()) {
3385 // Vectorcall in x64 only permits the first 6 arguments to be passed as
3386 // XMM/YMM registers. After the sixth argument, pretend no vector
3387 // registers are left.
3388 unsigned *MaybeFreeSSERegs =
3389 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
3390 I.info =
3391 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
3392 ++ArgNum;
3393 }
3394
3395 if (IsVectorCall) {
3396 // For vectorcall, assign aggregate HVAs to any free vector registers in a
3397 // second pass.
3398 for (auto &I : FI.arguments())
3399 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
3400 }
3401}
3402
3403RValue WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3404 QualType Ty, AggValueSlot Slot) const {
3405 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3406 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3407 uint64_t Width = getContext().getTypeSize(Ty);
3408 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3409
3410 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3413 /*allowHigherAlign*/ false, Slot);
3414}
3415
3416std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
3417 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3418 unsigned NumRegisterParameters, bool SoftFloatABI) {
3419 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3420 CGM.getTriple(), CGM.getCodeGenOpts());
3421 return std::make_unique<X86_32TargetCodeGenInfo>(
3422 CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3423 NumRegisterParameters, SoftFloatABI);
3424}
3425
3426std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
3427 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3428 unsigned NumRegisterParameters) {
3429 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3430 CGM.getTriple(), CGM.getCodeGenOpts());
3431 return std::make_unique<WinX86_32TargetCodeGenInfo>(
3432 CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3433 NumRegisterParameters);
3434}
3435
3436std::unique_ptr<TargetCodeGenInfo>
3438 X86AVXABILevel AVXLevel) {
3439 return std::make_unique<X86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3440}
3441
3442std::unique_ptr<TargetCodeGenInfo>
3444 X86AVXABILevel AVXLevel) {
3445 return std::make_unique<WinX86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3446}
#define V(N, I)
Definition: ASTContext.h:3338
const Decl * D
Expr * E
static bool checkAVX512ParamFeature(DiagnosticsEngine &Diag, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, bool IsArgument)
Definition: X86.cpp:1516
static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context)
Definition: X86.cpp:374
static void rewriteInputConstraintReferences(unsigned FirstIn, unsigned NumNewOuts, std::string &AsmString)
Rewrite input constraint references after adding some output constraints.
Definition: X86.cpp:249
static void initFeatureMaps(const ASTContext &Ctx, llvm::StringMap< bool > &CallerMap, const FunctionDecl *Caller, llvm::StringMap< bool > &CalleeMap, const FunctionDecl *Callee)
Definition: X86.cpp:1480
static llvm::Type * GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, const llvm::DataLayout &TD)
GetX86_64ByValArgumentPair - Given a high and low type that can ideally be used as elements of a two ...
Definition: X86.cpp:2528
static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, bool IsArgument)
Definition: X86.cpp:1534
static bool checkAVXParamFeature(DiagnosticsEngine &Diag, SourceLocation CallLoc, const llvm::StringMap< bool > &CallerMap, const llvm::StringMap< bool > &CalleeMap, QualType Ty, StringRef Feature, bool IsArgument)
Definition: X86.cpp:1494
static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, uint64_t &Size)
Definition: X86.cpp:410
static llvm::Type * getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset, const llvm::DataLayout &TD)
getFPTypeAtOffset - Return a floating point type at the specified offset.
Definition: X86.cpp:2370
static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, uint64_t &Size)
Definition: X86.cpp:390
static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, unsigned EndBit, ASTContext &Context)
BitsContainNoUserData - Return true if the specified [start,end) bit range is known to either be off ...
Definition: X86.cpp:2292
static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, Address VAListAddr, QualType Ty)
Definition: X86.cpp:2974
static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM)
Definition: X86.cpp:1107
static bool isArgInAlloca(const ABIArgInfo &Info)
Definition: X86.cpp:992
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
TypeInfoChars getTypeInfoInChars(const Type *T) const
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2391
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getRequiredAlignment() const
Definition: RecordLayout.h:311
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
A fixed int type of a specified bitwidth.
Definition: Type.h:7626
This class is used for builtin types like 'int'.
Definition: Type.h:3000
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:619
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition: CharUnits.h:143
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
static ABIArgInfo getInAlloca(unsigned FieldIndex, bool Indirect=false)
static ABIArgInfo getIgnore()
static ABIArgInfo getExpand()
void setIndirectAlign(CharUnits IA)
static ABIArgInfo getExtendInReg(QualType Ty, llvm::Type *T=nullptr)
static ABIArgInfo getExpandWithPadding(bool PaddingInReg, llvm::Type *Padding)
static ABIArgInfo getIndirect(CharUnits Alignment, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
static ABIArgInfo getExtend(QualType Ty, llvm::Type *T=nullptr)
llvm::Type * getCoerceToType() const
static ABIArgInfo getDirectInReg(llvm::Type *T=nullptr)
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
Definition: ABIInfo.h:47
ASTContext & getContext() const
Definition: ABIInfo.cpp:20
virtual bool isHomogeneousAggregateBaseType(QualType Ty) const
Definition: ABIInfo.cpp:47
virtual RValue EmitMSVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const
Emit the target dependent code to load a value of.
Definition: ABIInfo.cpp:42
virtual bool isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const
Definition: ABIInfo.cpp:51
const TargetInfo & getTarget() const
Definition: ABIInfo.cpp:30
virtual RValue EmitVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const =0
EmitVAArg - Emit the target dependent code to load a value of.
virtual void computeInfo(CodeGen::CGFunctionInfo &FI) const =0
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
An aggregate value slot.
Definition: CGValue.h:504
RValue asRValue() const
Definition: CGValue.h:666
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:135
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:304
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:291
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:218
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:107
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:363
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:127
RecordArgABI
Specify how one should pass an argument of a record type.
Definition: CGCXXABI.h:150
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:161
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
const_arg_iterator arg_begin() const
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
const_arg_iterator arg_end() const
void setArgStruct(llvm::StructType *Ty, CharUnits Align)
unsigned getMaxVectorWidth() const
Return the maximum vector width in the arguments.
unsigned getNumRequiredArgs() const
void setMaxVectorWidth(unsigned Width)
Set the maximum vector width in the arguments.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::Type * ConvertTypeForMem(QualType T)
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
const CGFunctionInfo * CurFnInfo
llvm::LLVMContext & getLLVMContext()
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
This class organizes the cross-function state that is used while generating LLVM code.
DiagnosticsEngine & getDiags() const
const TargetInfo & getTarget() const
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
LValue - This represents an lvalue references.
Definition: CGValue.h:182
Address getAddress() const
Definition: CGValue.h:361
QualType getType() const
Definition: CGValue.h:291
void setAddress(Address address)
Definition: CGValue.h:363
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
A class for recording the number of arguments that a function signature requires.
Target specific hooks for defining how a type should be passed or returned from functions with one of...
Definition: ABIInfo.h:130
bool occupiesMoreThan(ArrayRef< llvm::Type * > scalarTypes, unsigned maxAllRegisters) const
Does the given lowering require more than the given number of registers when expanded?
Definition: ABIInfo.cpp:255
virtual bool shouldPassIndirectly(ArrayRef< llvm::Type * > ComponentTys, bool AsReturnValue) const
Returns true if an aggregate which expands to the given type sequence should be passed / returned ind...
Definition: ABIInfo.cpp:273
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition: TargetInfo.h:47
virtual void addReturnRegisterOutputs(CodeGen::CodeGenFunction &CGF, CodeGen::LValue ReturnValue, std::string &Constraints, std::vector< llvm::Type * > &ResultRegTypes, std::vector< llvm::Type * > &ResultTruncRegTypes, std::vector< CodeGen::LValue > &ResultRegDests, std::string &AsmString, unsigned NumOutputs) const
Adds constraints and types for result registers.
Definition: TargetInfo.h:186
virtual llvm::Type * adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, StringRef Constraint, llvm::Type *Ty) const
Corrects the low-level LLVM type for a given constraint and "usual" type.
Definition: TargetInfo.h:172
virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const
Retrieve the address of a function to call immediately before calling objc_retainAutoreleasedReturnVa...
Definition: TargetInfo.h:207
virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, const FunctionDecl *Callee, const CallArgList &Args, QualType ReturnType) const
Any further codegen related checks that need to be done on a function call in a target specific manne...
Definition: TargetInfo.h:95
virtual bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const
Initializes the given DWARF EH register-size table, a char*.
Definition: TargetInfo.h:132
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:76
static std::string qualifyWindowsLibrary(StringRef Lib)
Definition: X86.cpp:1601
virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const
Determines the DWARF register number for the stack pointer, for exception-handling purposes.
Definition: TargetInfo.h:124
virtual bool markARCOptimizedReturnCallsAsNoTail() const
Determine whether a call to objc_retainAutoreleasedReturnValue or objc_unsafeClaimAutoreleasedReturnV...
Definition: TargetInfo.h:213
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Definition: TargetInfo.cpp:87
Complex values, per C99 6.2.5p11.
Definition: Type.h:3108
QualType getElementType() const
Definition: Type.h:3118
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2359
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool hasAttr() const
Definition: DeclBase.h:583
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
CallingConv getCallConv() const
Definition: Type.h:4611
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
A (possibly-)qualified type.
Definition: Type.h:941
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
QualType getCanonicalType() const
Definition: Type.h:7795
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasFlexibleArrayMember() const
Definition: Decl.h:4174
field_iterator field_end() const
Definition: Decl.h:4350
field_range fields() const
Definition: Decl.h:4347
field_iterator field_begin() const
Definition: Decl.cpp:5057
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Encodes a location in the source.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
The base class of the type hierarchy.
Definition: Type.h:1829
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isFloat16Type() const
Definition: Type.h:8304
bool isPointerType() const
Definition: Type.h:7996
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool isBitIntType() const
Definition: Type.h:8230
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8264
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8088
bool isAnyComplexType() const
Definition: Type.h:8100
bool isMemberPointerType() const
Definition: Type.h:8046
bool isBFloat16Type() const
Definition: Type.h:8316
bool isMemberFunctionPointerType() const
Definition: Type.h:8050
bool isVectorType() const
Definition: Type.h:8104
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isRecordType() const
Definition: Type.h:8092
bool isUnionType() const
Definition: Type.cpp:671
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8457
QualType getType() const
Definition: Decl.h:678
Represents a GCC generic vector type.
Definition: Type.h:3991
#define UINT_MAX
Definition: limits.h:64
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition: X86.cpp:3437
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
Definition: X86.cpp:3426
bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty)
RValue emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, TypeInfoChars ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign, AggValueSlot Slot, bool ForceRightAdjust=false)
Emit va_arg for a platform using the common void* representation, where arguments are simply emitted ...
Address emitMergePHI(CodeGenFunction &CGF, Address Addr1, llvm::BasicBlock *Block1, Address Addr2, llvm::BasicBlock *Block2, const llvm::Twine &Name="")
X86AVXABILevel
The AVX ABI level for X86 targets.
Definition: TargetInfo.h:555
bool isEmptyField(ASTContext &Context, const FieldDecl *FD, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyField - Return true iff a the field is "empty", that is it is an unnamed bit-field or an (arra...
llvm::Value * emitRoundPointerUpToAlignment(CodeGenFunction &CGF, llvm::Value *Ptr, CharUnits Align)
bool isAggregateTypeForABI(QualType T)
const Type * isSingleElementStruct(QualType T, ASTContext &Context)
isSingleElementStruct - Determine if a structure is a "single element struct", i.e.
void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, llvm::Value *Array, llvm::Value *Value, unsigned FirstIndex, unsigned LastIndex)
Definition: ABIInfoImpl.cpp:92
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
Definition: X86.cpp:3416
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition: X86.cpp:3443
bool isSIMDVectorType(ASTContext &Context, QualType Ty)
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:275
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ Class
The "class" keyword introduces the elaborated-type-specifier.
unsigned long uint64_t
#define false
Definition: stdbool.h:26
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
bool isAlignRequired()
Definition: ASTContext.h:165
uint64_t Width
Definition: ASTContext.h:157
unsigned Align
Definition: ASTContext.h:158