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