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