xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/Targets/X86.cpp (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
106c3fb27SDimitry Andric //===- X86.cpp ------------------------------------------------------------===//
206c3fb27SDimitry Andric //
306c3fb27SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406c3fb27SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
506c3fb27SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606c3fb27SDimitry Andric //
706c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
806c3fb27SDimitry Andric 
906c3fb27SDimitry Andric #include "ABIInfoImpl.h"
1006c3fb27SDimitry Andric #include "TargetInfo.h"
1106c3fb27SDimitry Andric #include "clang/Basic/DiagnosticFrontend.h"
1206c3fb27SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
1306c3fb27SDimitry Andric 
1406c3fb27SDimitry Andric using namespace clang;
1506c3fb27SDimitry Andric using namespace clang::CodeGen;
1606c3fb27SDimitry Andric 
1706c3fb27SDimitry Andric namespace {
1806c3fb27SDimitry Andric 
1906c3fb27SDimitry Andric /// IsX86_MMXType - Return true if this is an MMX type.
2006c3fb27SDimitry Andric bool IsX86_MMXType(llvm::Type *IRType) {
2106c3fb27SDimitry Andric   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
2206c3fb27SDimitry Andric   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
2306c3fb27SDimitry Andric     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
2406c3fb27SDimitry Andric     IRType->getScalarSizeInBits() != 64;
2506c3fb27SDimitry Andric }
2606c3fb27SDimitry Andric 
2706c3fb27SDimitry Andric static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2806c3fb27SDimitry Andric                                           StringRef Constraint,
2906c3fb27SDimitry Andric                                           llvm::Type* Ty) {
3006c3fb27SDimitry Andric   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
3106c3fb27SDimitry Andric                      .Cases("y", "&y", "^Ym", true)
3206c3fb27SDimitry Andric                      .Default(false);
3306c3fb27SDimitry Andric   if (IsMMXCons && Ty->isVectorTy()) {
3406c3fb27SDimitry Andric     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedValue() !=
3506c3fb27SDimitry Andric         64) {
3606c3fb27SDimitry Andric       // Invalid MMX constraint
3706c3fb27SDimitry Andric       return nullptr;
3806c3fb27SDimitry Andric     }
3906c3fb27SDimitry Andric 
4006c3fb27SDimitry Andric     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
4106c3fb27SDimitry Andric   }
4206c3fb27SDimitry Andric 
43*7a6dacacSDimitry Andric   if (Constraint == "k") {
44*7a6dacacSDimitry Andric     llvm::Type *Int1Ty = llvm::Type::getInt1Ty(CGF.getLLVMContext());
45*7a6dacacSDimitry Andric     return llvm::FixedVectorType::get(Int1Ty, Ty->getScalarSizeInBits());
46*7a6dacacSDimitry Andric   }
47*7a6dacacSDimitry Andric 
4806c3fb27SDimitry Andric   // No operation needed
4906c3fb27SDimitry Andric   return Ty;
5006c3fb27SDimitry Andric }
5106c3fb27SDimitry Andric 
5206c3fb27SDimitry Andric /// Returns true if this type can be passed in SSE registers with the
5306c3fb27SDimitry Andric /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
5406c3fb27SDimitry Andric static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
5506c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5606c3fb27SDimitry Andric     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
5706c3fb27SDimitry Andric       if (BT->getKind() == BuiltinType::LongDouble) {
5806c3fb27SDimitry Andric         if (&Context.getTargetInfo().getLongDoubleFormat() ==
5906c3fb27SDimitry Andric             &llvm::APFloat::x87DoubleExtended())
6006c3fb27SDimitry Andric           return false;
6106c3fb27SDimitry Andric       }
6206c3fb27SDimitry Andric       return true;
6306c3fb27SDimitry Andric     }
6406c3fb27SDimitry Andric   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6506c3fb27SDimitry Andric     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
6606c3fb27SDimitry Andric     // registers specially.
6706c3fb27SDimitry Andric     unsigned VecSize = Context.getTypeSize(VT);
6806c3fb27SDimitry Andric     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
6906c3fb27SDimitry Andric       return true;
7006c3fb27SDimitry Andric   }
7106c3fb27SDimitry Andric   return false;
7206c3fb27SDimitry Andric }
7306c3fb27SDimitry Andric 
7406c3fb27SDimitry Andric /// Returns true if this aggregate is small enough to be passed in SSE registers
7506c3fb27SDimitry Andric /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
7606c3fb27SDimitry Andric static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
7706c3fb27SDimitry Andric   return NumMembers <= 4;
7806c3fb27SDimitry Andric }
7906c3fb27SDimitry Andric 
8006c3fb27SDimitry Andric /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
8106c3fb27SDimitry Andric static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
8206c3fb27SDimitry Andric   auto AI = ABIArgInfo::getDirect(T);
8306c3fb27SDimitry Andric   AI.setInReg(true);
8406c3fb27SDimitry Andric   AI.setCanBeFlattened(false);
8506c3fb27SDimitry Andric   return AI;
8606c3fb27SDimitry Andric }
8706c3fb27SDimitry Andric 
8806c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
8906c3fb27SDimitry Andric // X86-32 ABI Implementation
9006c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
9106c3fb27SDimitry Andric 
9206c3fb27SDimitry Andric /// Similar to llvm::CCState, but for Clang.
9306c3fb27SDimitry Andric struct CCState {
9406c3fb27SDimitry Andric   CCState(CGFunctionInfo &FI)
955f757f3fSDimitry Andric       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()),
965f757f3fSDimitry Andric 	Required(FI.getRequiredArgs()), IsDelegateCall(FI.isDelegateCall()) {}
9706c3fb27SDimitry Andric 
9806c3fb27SDimitry Andric   llvm::SmallBitVector IsPreassigned;
9906c3fb27SDimitry Andric   unsigned CC = CallingConv::CC_C;
10006c3fb27SDimitry Andric   unsigned FreeRegs = 0;
10106c3fb27SDimitry Andric   unsigned FreeSSERegs = 0;
1025f757f3fSDimitry Andric   RequiredArgs Required;
1035f757f3fSDimitry Andric   bool IsDelegateCall = false;
10406c3fb27SDimitry Andric };
10506c3fb27SDimitry Andric 
10606c3fb27SDimitry Andric /// X86_32ABIInfo - The X86-32 ABI information.
10706c3fb27SDimitry Andric class X86_32ABIInfo : public ABIInfo {
10806c3fb27SDimitry Andric   enum Class {
10906c3fb27SDimitry Andric     Integer,
11006c3fb27SDimitry Andric     Float
11106c3fb27SDimitry Andric   };
11206c3fb27SDimitry Andric 
11306c3fb27SDimitry Andric   static const unsigned MinABIStackAlignInBytes = 4;
11406c3fb27SDimitry Andric 
11506c3fb27SDimitry Andric   bool IsDarwinVectorABI;
11606c3fb27SDimitry Andric   bool IsRetSmallStructInRegABI;
11706c3fb27SDimitry Andric   bool IsWin32StructABI;
11806c3fb27SDimitry Andric   bool IsSoftFloatABI;
11906c3fb27SDimitry Andric   bool IsMCUABI;
12006c3fb27SDimitry Andric   bool IsLinuxABI;
12106c3fb27SDimitry Andric   unsigned DefaultNumRegisterParameters;
12206c3fb27SDimitry Andric 
12306c3fb27SDimitry Andric   static bool isRegisterSize(unsigned Size) {
12406c3fb27SDimitry Andric     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
12506c3fb27SDimitry Andric   }
12606c3fb27SDimitry Andric 
12706c3fb27SDimitry Andric   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
12806c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
12906c3fb27SDimitry Andric     return isX86VectorTypeForVectorCall(getContext(), Ty);
13006c3fb27SDimitry Andric   }
13106c3fb27SDimitry Andric 
13206c3fb27SDimitry Andric   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
13306c3fb27SDimitry Andric                                          uint64_t NumMembers) const override {
13406c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
13506c3fb27SDimitry Andric     return isX86VectorCallAggregateSmallEnough(NumMembers);
13606c3fb27SDimitry Andric   }
13706c3fb27SDimitry Andric 
13806c3fb27SDimitry Andric   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
13906c3fb27SDimitry Andric 
14006c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
14106c3fb27SDimitry Andric   /// such that the argument will be passed in memory.
14206c3fb27SDimitry Andric   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
14306c3fb27SDimitry Andric 
14406c3fb27SDimitry Andric   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
14506c3fb27SDimitry Andric 
14606c3fb27SDimitry Andric   /// Return the alignment to use for the given type on the stack.
14706c3fb27SDimitry Andric   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
14806c3fb27SDimitry Andric 
14906c3fb27SDimitry Andric   Class classify(QualType Ty) const;
15006c3fb27SDimitry Andric   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1518a4dda33SDimitry Andric   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
1525f757f3fSDimitry Andric                                   unsigned ArgIndex) const;
15306c3fb27SDimitry Andric 
15406c3fb27SDimitry Andric   /// Updates the number of available free registers, returns
15506c3fb27SDimitry Andric   /// true if any registers were allocated.
15606c3fb27SDimitry Andric   bool updateFreeRegs(QualType Ty, CCState &State) const;
15706c3fb27SDimitry Andric 
15806c3fb27SDimitry Andric   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
15906c3fb27SDimitry Andric                                 bool &NeedsPadding) const;
16006c3fb27SDimitry Andric   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
16106c3fb27SDimitry Andric 
16206c3fb27SDimitry Andric   bool canExpandIndirectArgument(QualType Ty) const;
16306c3fb27SDimitry Andric 
16406c3fb27SDimitry Andric   /// Rewrite the function info so that all memory arguments use
16506c3fb27SDimitry Andric   /// inalloca.
16606c3fb27SDimitry Andric   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
16706c3fb27SDimitry Andric 
16806c3fb27SDimitry Andric   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
16906c3fb27SDimitry Andric                            CharUnits &StackOffset, ABIArgInfo &Info,
17006c3fb27SDimitry Andric                            QualType Type) const;
17106c3fb27SDimitry Andric   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
17206c3fb27SDimitry Andric 
17306c3fb27SDimitry Andric public:
17406c3fb27SDimitry Andric 
17506c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
17606c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
17706c3fb27SDimitry Andric                     QualType Ty) const override;
17806c3fb27SDimitry Andric 
17906c3fb27SDimitry Andric   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
18006c3fb27SDimitry Andric                 bool RetSmallStructInRegABI, bool Win32StructABI,
18106c3fb27SDimitry Andric                 unsigned NumRegisterParameters, bool SoftFloatABI)
18206c3fb27SDimitry Andric       : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
18306c3fb27SDimitry Andric         IsRetSmallStructInRegABI(RetSmallStructInRegABI),
18406c3fb27SDimitry Andric         IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
18506c3fb27SDimitry Andric         IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
18606c3fb27SDimitry Andric         IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
18706c3fb27SDimitry Andric                    CGT.getTarget().getTriple().isOSCygMing()),
18806c3fb27SDimitry Andric         DefaultNumRegisterParameters(NumRegisterParameters) {}
18906c3fb27SDimitry Andric };
19006c3fb27SDimitry Andric 
19106c3fb27SDimitry Andric class X86_32SwiftABIInfo : public SwiftABIInfo {
19206c3fb27SDimitry Andric public:
19306c3fb27SDimitry Andric   explicit X86_32SwiftABIInfo(CodeGenTypes &CGT)
19406c3fb27SDimitry Andric       : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/false) {}
19506c3fb27SDimitry Andric 
19606c3fb27SDimitry Andric   bool shouldPassIndirectly(ArrayRef<llvm::Type *> ComponentTys,
19706c3fb27SDimitry Andric                             bool AsReturnValue) const override {
19806c3fb27SDimitry Andric     // LLVM's x86-32 lowering currently only assigns up to three
19906c3fb27SDimitry Andric     // integer registers and three fp registers.  Oddly, it'll use up to
20006c3fb27SDimitry Andric     // four vector registers for vectors, but those can overlap with the
20106c3fb27SDimitry Andric     // scalar registers.
20206c3fb27SDimitry Andric     return occupiesMoreThan(ComponentTys, /*total=*/3);
20306c3fb27SDimitry Andric   }
20406c3fb27SDimitry Andric };
20506c3fb27SDimitry Andric 
20606c3fb27SDimitry Andric class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
20706c3fb27SDimitry Andric public:
20806c3fb27SDimitry Andric   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
20906c3fb27SDimitry Andric                           bool RetSmallStructInRegABI, bool Win32StructABI,
21006c3fb27SDimitry Andric                           unsigned NumRegisterParameters, bool SoftFloatABI)
21106c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
21206c3fb27SDimitry Andric             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
21306c3fb27SDimitry Andric             NumRegisterParameters, SoftFloatABI)) {
21406c3fb27SDimitry Andric     SwiftInfo = std::make_unique<X86_32SwiftABIInfo>(CGT);
21506c3fb27SDimitry Andric   }
21606c3fb27SDimitry Andric 
21706c3fb27SDimitry Andric   static bool isStructReturnInRegABI(
21806c3fb27SDimitry Andric       const llvm::Triple &Triple, const CodeGenOptions &Opts);
21906c3fb27SDimitry Andric 
22006c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
22106c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
22206c3fb27SDimitry Andric 
22306c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
22406c3fb27SDimitry Andric     // Darwin uses different dwarf register numbers for EH.
22506c3fb27SDimitry Andric     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
22606c3fb27SDimitry Andric     return 4;
22706c3fb27SDimitry Andric   }
22806c3fb27SDimitry Andric 
22906c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
23006c3fb27SDimitry Andric                                llvm::Value *Address) const override;
23106c3fb27SDimitry Andric 
23206c3fb27SDimitry Andric   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
23306c3fb27SDimitry Andric                                   StringRef Constraint,
23406c3fb27SDimitry Andric                                   llvm::Type* Ty) const override {
23506c3fb27SDimitry Andric     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
23606c3fb27SDimitry Andric   }
23706c3fb27SDimitry Andric 
23806c3fb27SDimitry Andric   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
23906c3fb27SDimitry Andric                                 std::string &Constraints,
24006c3fb27SDimitry Andric                                 std::vector<llvm::Type *> &ResultRegTypes,
24106c3fb27SDimitry Andric                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
24206c3fb27SDimitry Andric                                 std::vector<LValue> &ResultRegDests,
24306c3fb27SDimitry Andric                                 std::string &AsmString,
24406c3fb27SDimitry Andric                                 unsigned NumOutputs) const override;
24506c3fb27SDimitry Andric 
24606c3fb27SDimitry Andric   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
24706c3fb27SDimitry Andric     return "movl\t%ebp, %ebp"
24806c3fb27SDimitry Andric            "\t\t// marker for objc_retainAutoreleaseReturnValue";
24906c3fb27SDimitry Andric   }
25006c3fb27SDimitry Andric };
25106c3fb27SDimitry Andric 
25206c3fb27SDimitry Andric }
25306c3fb27SDimitry Andric 
25406c3fb27SDimitry Andric /// Rewrite input constraint references after adding some output constraints.
25506c3fb27SDimitry Andric /// In the case where there is one output and one input and we add one output,
25606c3fb27SDimitry Andric /// we need to replace all operand references greater than or equal to 1:
25706c3fb27SDimitry Andric ///     mov $0, $1
25806c3fb27SDimitry Andric ///     mov eax, $1
25906c3fb27SDimitry Andric /// The result will be:
26006c3fb27SDimitry Andric ///     mov $0, $2
26106c3fb27SDimitry Andric ///     mov eax, $2
26206c3fb27SDimitry Andric static void rewriteInputConstraintReferences(unsigned FirstIn,
26306c3fb27SDimitry Andric                                              unsigned NumNewOuts,
26406c3fb27SDimitry Andric                                              std::string &AsmString) {
26506c3fb27SDimitry Andric   std::string Buf;
26606c3fb27SDimitry Andric   llvm::raw_string_ostream OS(Buf);
26706c3fb27SDimitry Andric   size_t Pos = 0;
26806c3fb27SDimitry Andric   while (Pos < AsmString.size()) {
26906c3fb27SDimitry Andric     size_t DollarStart = AsmString.find('$', Pos);
27006c3fb27SDimitry Andric     if (DollarStart == std::string::npos)
27106c3fb27SDimitry Andric       DollarStart = AsmString.size();
27206c3fb27SDimitry Andric     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
27306c3fb27SDimitry Andric     if (DollarEnd == std::string::npos)
27406c3fb27SDimitry Andric       DollarEnd = AsmString.size();
27506c3fb27SDimitry Andric     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
27606c3fb27SDimitry Andric     Pos = DollarEnd;
27706c3fb27SDimitry Andric     size_t NumDollars = DollarEnd - DollarStart;
27806c3fb27SDimitry Andric     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
27906c3fb27SDimitry Andric       // We have an operand reference.
28006c3fb27SDimitry Andric       size_t DigitStart = Pos;
28106c3fb27SDimitry Andric       if (AsmString[DigitStart] == '{') {
28206c3fb27SDimitry Andric         OS << '{';
28306c3fb27SDimitry Andric         ++DigitStart;
28406c3fb27SDimitry Andric       }
28506c3fb27SDimitry Andric       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
28606c3fb27SDimitry Andric       if (DigitEnd == std::string::npos)
28706c3fb27SDimitry Andric         DigitEnd = AsmString.size();
28806c3fb27SDimitry Andric       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
28906c3fb27SDimitry Andric       unsigned OperandIndex;
29006c3fb27SDimitry Andric       if (!OperandStr.getAsInteger(10, OperandIndex)) {
29106c3fb27SDimitry Andric         if (OperandIndex >= FirstIn)
29206c3fb27SDimitry Andric           OperandIndex += NumNewOuts;
29306c3fb27SDimitry Andric         OS << OperandIndex;
29406c3fb27SDimitry Andric       } else {
29506c3fb27SDimitry Andric         OS << OperandStr;
29606c3fb27SDimitry Andric       }
29706c3fb27SDimitry Andric       Pos = DigitEnd;
29806c3fb27SDimitry Andric     }
29906c3fb27SDimitry Andric   }
30006c3fb27SDimitry Andric   AsmString = std::move(OS.str());
30106c3fb27SDimitry Andric }
30206c3fb27SDimitry Andric 
30306c3fb27SDimitry Andric /// Add output constraints for EAX:EDX because they are return registers.
30406c3fb27SDimitry Andric void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
30506c3fb27SDimitry Andric     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
30606c3fb27SDimitry Andric     std::vector<llvm::Type *> &ResultRegTypes,
30706c3fb27SDimitry Andric     std::vector<llvm::Type *> &ResultTruncRegTypes,
30806c3fb27SDimitry Andric     std::vector<LValue> &ResultRegDests, std::string &AsmString,
30906c3fb27SDimitry Andric     unsigned NumOutputs) const {
31006c3fb27SDimitry Andric   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
31106c3fb27SDimitry Andric 
31206c3fb27SDimitry Andric   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
31306c3fb27SDimitry Andric   // larger.
31406c3fb27SDimitry Andric   if (!Constraints.empty())
31506c3fb27SDimitry Andric     Constraints += ',';
31606c3fb27SDimitry Andric   if (RetWidth <= 32) {
31706c3fb27SDimitry Andric     Constraints += "={eax}";
31806c3fb27SDimitry Andric     ResultRegTypes.push_back(CGF.Int32Ty);
31906c3fb27SDimitry Andric   } else {
32006c3fb27SDimitry Andric     // Use the 'A' constraint for EAX:EDX.
32106c3fb27SDimitry Andric     Constraints += "=A";
32206c3fb27SDimitry Andric     ResultRegTypes.push_back(CGF.Int64Ty);
32306c3fb27SDimitry Andric   }
32406c3fb27SDimitry Andric 
32506c3fb27SDimitry Andric   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
32606c3fb27SDimitry Andric   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
32706c3fb27SDimitry Andric   ResultTruncRegTypes.push_back(CoerceTy);
32806c3fb27SDimitry Andric 
32906c3fb27SDimitry Andric   // Coerce the integer by bitcasting the return slot pointer.
33006c3fb27SDimitry Andric   ReturnSlot.setAddress(ReturnSlot.getAddress(CGF).withElementType(CoerceTy));
33106c3fb27SDimitry Andric   ResultRegDests.push_back(ReturnSlot);
33206c3fb27SDimitry Andric 
33306c3fb27SDimitry Andric   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
33406c3fb27SDimitry Andric }
33506c3fb27SDimitry Andric 
33606c3fb27SDimitry Andric /// shouldReturnTypeInRegister - Determine if the given type should be
33706c3fb27SDimitry Andric /// returned in a register (for the Darwin and MCU ABI).
33806c3fb27SDimitry Andric bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
33906c3fb27SDimitry Andric                                                ASTContext &Context) const {
34006c3fb27SDimitry Andric   uint64_t Size = Context.getTypeSize(Ty);
34106c3fb27SDimitry Andric 
34206c3fb27SDimitry Andric   // For i386, type must be register sized.
34306c3fb27SDimitry Andric   // For the MCU ABI, it only needs to be <= 8-byte
34406c3fb27SDimitry Andric   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
34506c3fb27SDimitry Andric    return false;
34606c3fb27SDimitry Andric 
34706c3fb27SDimitry Andric   if (Ty->isVectorType()) {
34806c3fb27SDimitry Andric     // 64- and 128- bit vectors inside structures are not returned in
34906c3fb27SDimitry Andric     // registers.
35006c3fb27SDimitry Andric     if (Size == 64 || Size == 128)
35106c3fb27SDimitry Andric       return false;
35206c3fb27SDimitry Andric 
35306c3fb27SDimitry Andric     return true;
35406c3fb27SDimitry Andric   }
35506c3fb27SDimitry Andric 
35606c3fb27SDimitry Andric   // If this is a builtin, pointer, enum, complex type, member pointer, or
35706c3fb27SDimitry Andric   // member function pointer it is ok.
35806c3fb27SDimitry Andric   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
35906c3fb27SDimitry Andric       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
36006c3fb27SDimitry Andric       Ty->isBlockPointerType() || Ty->isMemberPointerType())
36106c3fb27SDimitry Andric     return true;
36206c3fb27SDimitry Andric 
36306c3fb27SDimitry Andric   // Arrays are treated like records.
36406c3fb27SDimitry Andric   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
36506c3fb27SDimitry Andric     return shouldReturnTypeInRegister(AT->getElementType(), Context);
36606c3fb27SDimitry Andric 
36706c3fb27SDimitry Andric   // Otherwise, it must be a record type.
36806c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
36906c3fb27SDimitry Andric   if (!RT) return false;
37006c3fb27SDimitry Andric 
37106c3fb27SDimitry Andric   // FIXME: Traverse bases here too.
37206c3fb27SDimitry Andric 
37306c3fb27SDimitry Andric   // Structure types are passed in register if all fields would be
37406c3fb27SDimitry Andric   // passed in a register.
37506c3fb27SDimitry Andric   for (const auto *FD : RT->getDecl()->fields()) {
37606c3fb27SDimitry Andric     // Empty fields are ignored.
37706c3fb27SDimitry Andric     if (isEmptyField(Context, FD, true))
37806c3fb27SDimitry Andric       continue;
37906c3fb27SDimitry Andric 
38006c3fb27SDimitry Andric     // Check fields recursively.
38106c3fb27SDimitry Andric     if (!shouldReturnTypeInRegister(FD->getType(), Context))
38206c3fb27SDimitry Andric       return false;
38306c3fb27SDimitry Andric   }
38406c3fb27SDimitry Andric   return true;
38506c3fb27SDimitry Andric }
38606c3fb27SDimitry Andric 
38706c3fb27SDimitry Andric static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
38806c3fb27SDimitry Andric   // Treat complex types as the element type.
38906c3fb27SDimitry Andric   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
39006c3fb27SDimitry Andric     Ty = CTy->getElementType();
39106c3fb27SDimitry Andric 
39206c3fb27SDimitry Andric   // Check for a type which we know has a simple scalar argument-passing
39306c3fb27SDimitry Andric   // convention without any padding.  (We're specifically looking for 32
39406c3fb27SDimitry Andric   // and 64-bit integer and integer-equivalents, float, and double.)
39506c3fb27SDimitry Andric   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
39606c3fb27SDimitry Andric       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
39706c3fb27SDimitry Andric     return false;
39806c3fb27SDimitry Andric 
39906c3fb27SDimitry Andric   uint64_t Size = Context.getTypeSize(Ty);
40006c3fb27SDimitry Andric   return Size == 32 || Size == 64;
40106c3fb27SDimitry Andric }
40206c3fb27SDimitry Andric 
40306c3fb27SDimitry Andric static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
40406c3fb27SDimitry Andric                           uint64_t &Size) {
40506c3fb27SDimitry Andric   for (const auto *FD : RD->fields()) {
40606c3fb27SDimitry Andric     // Scalar arguments on the stack get 4 byte alignment on x86. If the
40706c3fb27SDimitry Andric     // argument is smaller than 32-bits, expanding the struct will create
40806c3fb27SDimitry Andric     // alignment padding.
40906c3fb27SDimitry Andric     if (!is32Or64BitBasicType(FD->getType(), Context))
41006c3fb27SDimitry Andric       return false;
41106c3fb27SDimitry Andric 
41206c3fb27SDimitry Andric     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
41306c3fb27SDimitry Andric     // how to expand them yet, and the predicate for telling if a bitfield still
41406c3fb27SDimitry Andric     // counts as "basic" is more complicated than what we were doing previously.
41506c3fb27SDimitry Andric     if (FD->isBitField())
41606c3fb27SDimitry Andric       return false;
41706c3fb27SDimitry Andric 
41806c3fb27SDimitry Andric     Size += Context.getTypeSize(FD->getType());
41906c3fb27SDimitry Andric   }
42006c3fb27SDimitry Andric   return true;
42106c3fb27SDimitry Andric }
42206c3fb27SDimitry Andric 
42306c3fb27SDimitry Andric static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
42406c3fb27SDimitry Andric                                  uint64_t &Size) {
42506c3fb27SDimitry Andric   // Don't do this if there are any non-empty bases.
42606c3fb27SDimitry Andric   for (const CXXBaseSpecifier &Base : RD->bases()) {
42706c3fb27SDimitry Andric     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
42806c3fb27SDimitry Andric                               Size))
42906c3fb27SDimitry Andric       return false;
43006c3fb27SDimitry Andric   }
43106c3fb27SDimitry Andric   if (!addFieldSizes(Context, RD, Size))
43206c3fb27SDimitry Andric     return false;
43306c3fb27SDimitry Andric   return true;
43406c3fb27SDimitry Andric }
43506c3fb27SDimitry Andric 
43606c3fb27SDimitry Andric /// Test whether an argument type which is to be passed indirectly (on the
43706c3fb27SDimitry Andric /// stack) would have the equivalent layout if it was expanded into separate
43806c3fb27SDimitry Andric /// arguments. If so, we prefer to do the latter to avoid inhibiting
43906c3fb27SDimitry Andric /// optimizations.
44006c3fb27SDimitry Andric bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
44106c3fb27SDimitry Andric   // We can only expand structure types.
44206c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
44306c3fb27SDimitry Andric   if (!RT)
44406c3fb27SDimitry Andric     return false;
44506c3fb27SDimitry Andric   const RecordDecl *RD = RT->getDecl();
44606c3fb27SDimitry Andric   uint64_t Size = 0;
44706c3fb27SDimitry Andric   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
44806c3fb27SDimitry Andric     if (!IsWin32StructABI) {
44906c3fb27SDimitry Andric       // On non-Windows, we have to conservatively match our old bitcode
45006c3fb27SDimitry Andric       // prototypes in order to be ABI-compatible at the bitcode level.
45106c3fb27SDimitry Andric       if (!CXXRD->isCLike())
45206c3fb27SDimitry Andric         return false;
45306c3fb27SDimitry Andric     } else {
45406c3fb27SDimitry Andric       // Don't do this for dynamic classes.
45506c3fb27SDimitry Andric       if (CXXRD->isDynamicClass())
45606c3fb27SDimitry Andric         return false;
45706c3fb27SDimitry Andric     }
45806c3fb27SDimitry Andric     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
45906c3fb27SDimitry Andric       return false;
46006c3fb27SDimitry Andric   } else {
46106c3fb27SDimitry Andric     if (!addFieldSizes(getContext(), RD, Size))
46206c3fb27SDimitry Andric       return false;
46306c3fb27SDimitry Andric   }
46406c3fb27SDimitry Andric 
46506c3fb27SDimitry Andric   // We can do this if there was no alignment padding.
46606c3fb27SDimitry Andric   return Size == getContext().getTypeSize(Ty);
46706c3fb27SDimitry Andric }
46806c3fb27SDimitry Andric 
46906c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
47006c3fb27SDimitry Andric   // If the return value is indirect, then the hidden argument is consuming one
47106c3fb27SDimitry Andric   // integer register.
47206c3fb27SDimitry Andric   if (State.FreeRegs) {
47306c3fb27SDimitry Andric     --State.FreeRegs;
47406c3fb27SDimitry Andric     if (!IsMCUABI)
47506c3fb27SDimitry Andric       return getNaturalAlignIndirectInReg(RetTy);
47606c3fb27SDimitry Andric   }
47706c3fb27SDimitry Andric   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
47806c3fb27SDimitry Andric }
47906c3fb27SDimitry Andric 
48006c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
48106c3fb27SDimitry Andric                                              CCState &State) const {
48206c3fb27SDimitry Andric   if (RetTy->isVoidType())
48306c3fb27SDimitry Andric     return ABIArgInfo::getIgnore();
48406c3fb27SDimitry Andric 
48506c3fb27SDimitry Andric   const Type *Base = nullptr;
48606c3fb27SDimitry Andric   uint64_t NumElts = 0;
48706c3fb27SDimitry Andric   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
48806c3fb27SDimitry Andric        State.CC == llvm::CallingConv::X86_RegCall) &&
48906c3fb27SDimitry Andric       isHomogeneousAggregate(RetTy, Base, NumElts)) {
49006c3fb27SDimitry Andric     // The LLVM struct type for such an aggregate should lower properly.
49106c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
49206c3fb27SDimitry Andric   }
49306c3fb27SDimitry Andric 
49406c3fb27SDimitry Andric   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
49506c3fb27SDimitry Andric     // On Darwin, some vectors are returned in registers.
49606c3fb27SDimitry Andric     if (IsDarwinVectorABI) {
49706c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(RetTy);
49806c3fb27SDimitry Andric 
49906c3fb27SDimitry Andric       // 128-bit vectors are a special case; they are returned in
50006c3fb27SDimitry Andric       // registers and we need to make sure to pick a type the LLVM
50106c3fb27SDimitry Andric       // backend will like.
50206c3fb27SDimitry Andric       if (Size == 128)
50306c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
50406c3fb27SDimitry Andric             llvm::Type::getInt64Ty(getVMContext()), 2));
50506c3fb27SDimitry Andric 
50606c3fb27SDimitry Andric       // Always return in register if it fits in a general purpose
50706c3fb27SDimitry Andric       // register, or if it is 64 bits and has a single element.
50806c3fb27SDimitry Andric       if ((Size == 8 || Size == 16 || Size == 32) ||
50906c3fb27SDimitry Andric           (Size == 64 && VT->getNumElements() == 1))
51006c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
51106c3fb27SDimitry Andric                                                             Size));
51206c3fb27SDimitry Andric 
51306c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
51406c3fb27SDimitry Andric     }
51506c3fb27SDimitry Andric 
51606c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
51706c3fb27SDimitry Andric   }
51806c3fb27SDimitry Andric 
51906c3fb27SDimitry Andric   if (isAggregateTypeForABI(RetTy)) {
52006c3fb27SDimitry Andric     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
52106c3fb27SDimitry Andric       // Structures with flexible arrays are always indirect.
52206c3fb27SDimitry Andric       if (RT->getDecl()->hasFlexibleArrayMember())
52306c3fb27SDimitry Andric         return getIndirectReturnResult(RetTy, State);
52406c3fb27SDimitry Andric     }
52506c3fb27SDimitry Andric 
52606c3fb27SDimitry Andric     // If specified, structs and unions are always indirect.
52706c3fb27SDimitry Andric     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
52806c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
52906c3fb27SDimitry Andric 
53006c3fb27SDimitry Andric     // Ignore empty structs/unions.
53106c3fb27SDimitry Andric     if (isEmptyRecord(getContext(), RetTy, true))
53206c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
53306c3fb27SDimitry Andric 
53406c3fb27SDimitry Andric     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
53506c3fb27SDimitry Andric     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
53606c3fb27SDimitry Andric       QualType ET = getContext().getCanonicalType(CT->getElementType());
53706c3fb27SDimitry Andric       if (ET->isFloat16Type())
53806c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
53906c3fb27SDimitry Andric             llvm::Type::getHalfTy(getVMContext()), 2));
54006c3fb27SDimitry Andric     }
54106c3fb27SDimitry Andric 
54206c3fb27SDimitry Andric     // Small structures which are register sized are generally returned
54306c3fb27SDimitry Andric     // in a register.
54406c3fb27SDimitry Andric     if (shouldReturnTypeInRegister(RetTy, getContext())) {
54506c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(RetTy);
54606c3fb27SDimitry Andric 
54706c3fb27SDimitry Andric       // As a special-case, if the struct is a "single-element" struct, and
54806c3fb27SDimitry Andric       // the field is of type "float" or "double", return it in a
54906c3fb27SDimitry Andric       // floating-point register. (MSVC does not apply this special case.)
55006c3fb27SDimitry Andric       // We apply a similar transformation for pointer types to improve the
55106c3fb27SDimitry Andric       // quality of the generated IR.
55206c3fb27SDimitry Andric       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
55306c3fb27SDimitry Andric         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
55406c3fb27SDimitry Andric             || SeltTy->hasPointerRepresentation())
55506c3fb27SDimitry Andric           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
55606c3fb27SDimitry Andric 
55706c3fb27SDimitry Andric       // FIXME: We should be able to narrow this integer in cases with dead
55806c3fb27SDimitry Andric       // padding.
55906c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
56006c3fb27SDimitry Andric     }
56106c3fb27SDimitry Andric 
56206c3fb27SDimitry Andric     return getIndirectReturnResult(RetTy, State);
56306c3fb27SDimitry Andric   }
56406c3fb27SDimitry Andric 
56506c3fb27SDimitry Andric   // Treat an enum type as its underlying type.
56606c3fb27SDimitry Andric   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
56706c3fb27SDimitry Andric     RetTy = EnumTy->getDecl()->getIntegerType();
56806c3fb27SDimitry Andric 
56906c3fb27SDimitry Andric   if (const auto *EIT = RetTy->getAs<BitIntType>())
57006c3fb27SDimitry Andric     if (EIT->getNumBits() > 64)
57106c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
57206c3fb27SDimitry Andric 
57306c3fb27SDimitry Andric   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
57406c3fb27SDimitry Andric                                                : ABIArgInfo::getDirect());
57506c3fb27SDimitry Andric }
57606c3fb27SDimitry Andric 
57706c3fb27SDimitry Andric unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
57806c3fb27SDimitry Andric                                                  unsigned Align) const {
57906c3fb27SDimitry Andric   // Otherwise, if the alignment is less than or equal to the minimum ABI
58006c3fb27SDimitry Andric   // alignment, just use the default; the backend will handle this.
58106c3fb27SDimitry Andric   if (Align <= MinABIStackAlignInBytes)
58206c3fb27SDimitry Andric     return 0; // Use default alignment.
58306c3fb27SDimitry Andric 
58406c3fb27SDimitry Andric   if (IsLinuxABI) {
58506c3fb27SDimitry Andric     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
58606c3fb27SDimitry Andric     // want to spend any effort dealing with the ramifications of ABI breaks.
58706c3fb27SDimitry Andric     //
58806c3fb27SDimitry Andric     // If the vector type is __m128/__m256/__m512, return the default alignment.
58906c3fb27SDimitry Andric     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
59006c3fb27SDimitry Andric       return Align;
59106c3fb27SDimitry Andric   }
59206c3fb27SDimitry Andric   // On non-Darwin, the stack type alignment is always 4.
59306c3fb27SDimitry Andric   if (!IsDarwinVectorABI) {
59406c3fb27SDimitry Andric     // Set explicit alignment, since we may need to realign the top.
59506c3fb27SDimitry Andric     return MinABIStackAlignInBytes;
59606c3fb27SDimitry Andric   }
59706c3fb27SDimitry Andric 
59806c3fb27SDimitry Andric   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
59906c3fb27SDimitry Andric   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
60006c3fb27SDimitry Andric                       isRecordWithSIMDVectorType(getContext(), Ty)))
60106c3fb27SDimitry Andric     return 16;
60206c3fb27SDimitry Andric 
60306c3fb27SDimitry Andric   return MinABIStackAlignInBytes;
60406c3fb27SDimitry Andric }
60506c3fb27SDimitry Andric 
60606c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
60706c3fb27SDimitry Andric                                             CCState &State) const {
60806c3fb27SDimitry Andric   if (!ByVal) {
60906c3fb27SDimitry Andric     if (State.FreeRegs) {
61006c3fb27SDimitry Andric       --State.FreeRegs; // Non-byval indirects just use one pointer.
61106c3fb27SDimitry Andric       if (!IsMCUABI)
61206c3fb27SDimitry Andric         return getNaturalAlignIndirectInReg(Ty);
61306c3fb27SDimitry Andric     }
61406c3fb27SDimitry Andric     return getNaturalAlignIndirect(Ty, false);
61506c3fb27SDimitry Andric   }
61606c3fb27SDimitry Andric 
61706c3fb27SDimitry Andric   // Compute the byval alignment.
61806c3fb27SDimitry Andric   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
61906c3fb27SDimitry Andric   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
62006c3fb27SDimitry Andric   if (StackAlign == 0)
62106c3fb27SDimitry Andric     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
62206c3fb27SDimitry Andric 
62306c3fb27SDimitry Andric   // If the stack alignment is less than the type alignment, realign the
62406c3fb27SDimitry Andric   // argument.
62506c3fb27SDimitry Andric   bool Realign = TypeAlign > StackAlign;
62606c3fb27SDimitry Andric   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
62706c3fb27SDimitry Andric                                  /*ByVal=*/true, Realign);
62806c3fb27SDimitry Andric }
62906c3fb27SDimitry Andric 
63006c3fb27SDimitry Andric X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
63106c3fb27SDimitry Andric   const Type *T = isSingleElementStruct(Ty, getContext());
63206c3fb27SDimitry Andric   if (!T)
63306c3fb27SDimitry Andric     T = Ty.getTypePtr();
63406c3fb27SDimitry Andric 
63506c3fb27SDimitry Andric   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
63606c3fb27SDimitry Andric     BuiltinType::Kind K = BT->getKind();
63706c3fb27SDimitry Andric     if (K == BuiltinType::Float || K == BuiltinType::Double)
63806c3fb27SDimitry Andric       return Float;
63906c3fb27SDimitry Andric   }
64006c3fb27SDimitry Andric   return Integer;
64106c3fb27SDimitry Andric }
64206c3fb27SDimitry Andric 
64306c3fb27SDimitry Andric bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
64406c3fb27SDimitry Andric   if (!IsSoftFloatABI) {
64506c3fb27SDimitry Andric     Class C = classify(Ty);
64606c3fb27SDimitry Andric     if (C == Float)
64706c3fb27SDimitry Andric       return false;
64806c3fb27SDimitry Andric   }
64906c3fb27SDimitry Andric 
65006c3fb27SDimitry Andric   unsigned Size = getContext().getTypeSize(Ty);
65106c3fb27SDimitry Andric   unsigned SizeInRegs = (Size + 31) / 32;
65206c3fb27SDimitry Andric 
65306c3fb27SDimitry Andric   if (SizeInRegs == 0)
65406c3fb27SDimitry Andric     return false;
65506c3fb27SDimitry Andric 
65606c3fb27SDimitry Andric   if (!IsMCUABI) {
65706c3fb27SDimitry Andric     if (SizeInRegs > State.FreeRegs) {
65806c3fb27SDimitry Andric       State.FreeRegs = 0;
65906c3fb27SDimitry Andric       return false;
66006c3fb27SDimitry Andric     }
66106c3fb27SDimitry Andric   } else {
66206c3fb27SDimitry Andric     // The MCU psABI allows passing parameters in-reg even if there are
66306c3fb27SDimitry Andric     // earlier parameters that are passed on the stack. Also,
66406c3fb27SDimitry Andric     // it does not allow passing >8-byte structs in-register,
66506c3fb27SDimitry Andric     // even if there are 3 free registers available.
66606c3fb27SDimitry Andric     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
66706c3fb27SDimitry Andric       return false;
66806c3fb27SDimitry Andric   }
66906c3fb27SDimitry Andric 
67006c3fb27SDimitry Andric   State.FreeRegs -= SizeInRegs;
67106c3fb27SDimitry Andric   return true;
67206c3fb27SDimitry Andric }
67306c3fb27SDimitry Andric 
67406c3fb27SDimitry Andric bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
67506c3fb27SDimitry Andric                                              bool &InReg,
67606c3fb27SDimitry Andric                                              bool &NeedsPadding) const {
67706c3fb27SDimitry Andric   // On Windows, aggregates other than HFAs are never passed in registers, and
67806c3fb27SDimitry Andric   // they do not consume register slots. Homogenous floating-point aggregates
67906c3fb27SDimitry Andric   // (HFAs) have already been dealt with at this point.
68006c3fb27SDimitry Andric   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
68106c3fb27SDimitry Andric     return false;
68206c3fb27SDimitry Andric 
68306c3fb27SDimitry Andric   NeedsPadding = false;
68406c3fb27SDimitry Andric   InReg = !IsMCUABI;
68506c3fb27SDimitry Andric 
68606c3fb27SDimitry Andric   if (!updateFreeRegs(Ty, State))
68706c3fb27SDimitry Andric     return false;
68806c3fb27SDimitry Andric 
68906c3fb27SDimitry Andric   if (IsMCUABI)
69006c3fb27SDimitry Andric     return true;
69106c3fb27SDimitry Andric 
69206c3fb27SDimitry Andric   if (State.CC == llvm::CallingConv::X86_FastCall ||
69306c3fb27SDimitry Andric       State.CC == llvm::CallingConv::X86_VectorCall ||
69406c3fb27SDimitry Andric       State.CC == llvm::CallingConv::X86_RegCall) {
69506c3fb27SDimitry Andric     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
69606c3fb27SDimitry Andric       NeedsPadding = true;
69706c3fb27SDimitry Andric 
69806c3fb27SDimitry Andric     return false;
69906c3fb27SDimitry Andric   }
70006c3fb27SDimitry Andric 
70106c3fb27SDimitry Andric   return true;
70206c3fb27SDimitry Andric }
70306c3fb27SDimitry Andric 
70406c3fb27SDimitry Andric bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
70506c3fb27SDimitry Andric   bool IsPtrOrInt = (getContext().getTypeSize(Ty) <= 32) &&
70606c3fb27SDimitry Andric                     (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
70706c3fb27SDimitry Andric                      Ty->isReferenceType());
70806c3fb27SDimitry Andric 
70906c3fb27SDimitry Andric   if (!IsPtrOrInt && (State.CC == llvm::CallingConv::X86_FastCall ||
71006c3fb27SDimitry Andric                       State.CC == llvm::CallingConv::X86_VectorCall))
71106c3fb27SDimitry Andric     return false;
71206c3fb27SDimitry Andric 
71306c3fb27SDimitry Andric   if (!updateFreeRegs(Ty, State))
71406c3fb27SDimitry Andric     return false;
71506c3fb27SDimitry Andric 
71606c3fb27SDimitry Andric   if (!IsPtrOrInt && State.CC == llvm::CallingConv::X86_RegCall)
71706c3fb27SDimitry Andric     return false;
71806c3fb27SDimitry Andric 
71906c3fb27SDimitry Andric   // Return true to apply inreg to all legal parameters except for MCU targets.
72006c3fb27SDimitry Andric   return !IsMCUABI;
72106c3fb27SDimitry Andric }
72206c3fb27SDimitry Andric 
72306c3fb27SDimitry Andric void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
72406c3fb27SDimitry Andric   // Vectorcall x86 works subtly different than in x64, so the format is
72506c3fb27SDimitry Andric   // a bit different than the x64 version.  First, all vector types (not HVAs)
72606c3fb27SDimitry Andric   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
72706c3fb27SDimitry Andric   // This differs from the x64 implementation, where the first 6 by INDEX get
72806c3fb27SDimitry Andric   // registers.
72906c3fb27SDimitry Andric   // In the second pass over the arguments, HVAs are passed in the remaining
73006c3fb27SDimitry Andric   // vector registers if possible, or indirectly by address. The address will be
73106c3fb27SDimitry Andric   // passed in ECX/EDX if available. Any other arguments are passed according to
73206c3fb27SDimitry Andric   // the usual fastcall rules.
73306c3fb27SDimitry Andric   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
73406c3fb27SDimitry Andric   for (int I = 0, E = Args.size(); I < E; ++I) {
73506c3fb27SDimitry Andric     const Type *Base = nullptr;
73606c3fb27SDimitry Andric     uint64_t NumElts = 0;
73706c3fb27SDimitry Andric     const QualType &Ty = Args[I].type;
73806c3fb27SDimitry Andric     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
73906c3fb27SDimitry Andric         isHomogeneousAggregate(Ty, Base, NumElts)) {
74006c3fb27SDimitry Andric       if (State.FreeSSERegs >= NumElts) {
74106c3fb27SDimitry Andric         State.FreeSSERegs -= NumElts;
74206c3fb27SDimitry Andric         Args[I].info = ABIArgInfo::getDirectInReg();
74306c3fb27SDimitry Andric         State.IsPreassigned.set(I);
74406c3fb27SDimitry Andric       }
74506c3fb27SDimitry Andric     }
74606c3fb27SDimitry Andric   }
74706c3fb27SDimitry Andric }
74806c3fb27SDimitry Andric 
7498a4dda33SDimitry Andric ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State,
7505f757f3fSDimitry Andric                                                unsigned ArgIndex) const {
75106c3fb27SDimitry Andric   // FIXME: Set alignment on indirect arguments.
75206c3fb27SDimitry Andric   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
75306c3fb27SDimitry Andric   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
75406c3fb27SDimitry Andric   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
75506c3fb27SDimitry Andric 
75606c3fb27SDimitry Andric   Ty = useFirstFieldIfTransparentUnion(Ty);
75706c3fb27SDimitry Andric   TypeInfo TI = getContext().getTypeInfo(Ty);
75806c3fb27SDimitry Andric 
75906c3fb27SDimitry Andric   // Check with the C++ ABI first.
76006c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
76106c3fb27SDimitry Andric   if (RT) {
76206c3fb27SDimitry Andric     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
76306c3fb27SDimitry Andric     if (RAA == CGCXXABI::RAA_Indirect) {
76406c3fb27SDimitry Andric       return getIndirectResult(Ty, false, State);
7655f757f3fSDimitry Andric     } else if (State.IsDelegateCall) {
7668a4dda33SDimitry Andric       // Avoid having different alignments on delegate call args by always
7678a4dda33SDimitry Andric       // setting the alignment to 4, which is what we do for inallocas.
7688a4dda33SDimitry Andric       ABIArgInfo Res = getIndirectResult(Ty, false, State);
7698a4dda33SDimitry Andric       Res.setIndirectAlign(CharUnits::fromQuantity(4));
7708a4dda33SDimitry Andric       return Res;
77106c3fb27SDimitry Andric     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
77206c3fb27SDimitry Andric       // The field index doesn't matter, we'll fix it up later.
77306c3fb27SDimitry Andric       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
77406c3fb27SDimitry Andric     }
77506c3fb27SDimitry Andric   }
77606c3fb27SDimitry Andric 
77706c3fb27SDimitry Andric   // Regcall uses the concept of a homogenous vector aggregate, similar
77806c3fb27SDimitry Andric   // to other targets.
77906c3fb27SDimitry Andric   const Type *Base = nullptr;
78006c3fb27SDimitry Andric   uint64_t NumElts = 0;
78106c3fb27SDimitry Andric   if ((IsRegCall || IsVectorCall) &&
78206c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts)) {
78306c3fb27SDimitry Andric     if (State.FreeSSERegs >= NumElts) {
78406c3fb27SDimitry Andric       State.FreeSSERegs -= NumElts;
78506c3fb27SDimitry Andric 
78606c3fb27SDimitry Andric       // Vectorcall passes HVAs directly and does not flatten them, but regcall
78706c3fb27SDimitry Andric       // does.
78806c3fb27SDimitry Andric       if (IsVectorCall)
78906c3fb27SDimitry Andric         return getDirectX86Hva();
79006c3fb27SDimitry Andric 
79106c3fb27SDimitry Andric       if (Ty->isBuiltinType() || Ty->isVectorType())
79206c3fb27SDimitry Andric         return ABIArgInfo::getDirect();
79306c3fb27SDimitry Andric       return ABIArgInfo::getExpand();
79406c3fb27SDimitry Andric     }
79506c3fb27SDimitry Andric     return getIndirectResult(Ty, /*ByVal=*/false, State);
79606c3fb27SDimitry Andric   }
79706c3fb27SDimitry Andric 
79806c3fb27SDimitry Andric   if (isAggregateTypeForABI(Ty)) {
79906c3fb27SDimitry Andric     // Structures with flexible arrays are always indirect.
80006c3fb27SDimitry Andric     // FIXME: This should not be byval!
80106c3fb27SDimitry Andric     if (RT && RT->getDecl()->hasFlexibleArrayMember())
80206c3fb27SDimitry Andric       return getIndirectResult(Ty, true, State);
80306c3fb27SDimitry Andric 
80406c3fb27SDimitry Andric     // Ignore empty structs/unions on non-Windows.
80506c3fb27SDimitry Andric     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
80606c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
80706c3fb27SDimitry Andric 
80806c3fb27SDimitry Andric     llvm::LLVMContext &LLVMContext = getVMContext();
80906c3fb27SDimitry Andric     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
81006c3fb27SDimitry Andric     bool NeedsPadding = false;
81106c3fb27SDimitry Andric     bool InReg;
81206c3fb27SDimitry Andric     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
81306c3fb27SDimitry Andric       unsigned SizeInRegs = (TI.Width + 31) / 32;
81406c3fb27SDimitry Andric       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
81506c3fb27SDimitry Andric       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
81606c3fb27SDimitry Andric       if (InReg)
81706c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg(Result);
81806c3fb27SDimitry Andric       else
81906c3fb27SDimitry Andric         return ABIArgInfo::getDirect(Result);
82006c3fb27SDimitry Andric     }
82106c3fb27SDimitry Andric     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
82206c3fb27SDimitry Andric 
8235f757f3fSDimitry Andric     // Pass over-aligned aggregates to non-variadic functions on Windows
8245f757f3fSDimitry Andric     // indirectly. This behavior was added in MSVC 2015. Use the required
8255f757f3fSDimitry Andric     // alignment from the record layout, since that may be less than the
8265f757f3fSDimitry Andric     // regular type alignment, and types with required alignment of less than 4
8275f757f3fSDimitry Andric     // bytes are not passed indirectly.
8285f757f3fSDimitry Andric     if (IsWin32StructABI && State.Required.isRequiredArg(ArgIndex)) {
82906c3fb27SDimitry Andric       unsigned AlignInBits = 0;
83006c3fb27SDimitry Andric       if (RT) {
83106c3fb27SDimitry Andric         const ASTRecordLayout &Layout =
83206c3fb27SDimitry Andric           getContext().getASTRecordLayout(RT->getDecl());
83306c3fb27SDimitry Andric         AlignInBits = getContext().toBits(Layout.getRequiredAlignment());
83406c3fb27SDimitry Andric       } else if (TI.isAlignRequired()) {
83506c3fb27SDimitry Andric         AlignInBits = TI.Align;
83606c3fb27SDimitry Andric       }
83706c3fb27SDimitry Andric       if (AlignInBits > 32)
83806c3fb27SDimitry Andric         return getIndirectResult(Ty, /*ByVal=*/false, State);
83906c3fb27SDimitry Andric     }
84006c3fb27SDimitry Andric 
84106c3fb27SDimitry Andric     // Expand small (<= 128-bit) record types when we know that the stack layout
84206c3fb27SDimitry Andric     // of those arguments will match the struct. This is important because the
84306c3fb27SDimitry Andric     // LLVM backend isn't smart enough to remove byval, which inhibits many
84406c3fb27SDimitry Andric     // optimizations.
84506c3fb27SDimitry Andric     // Don't do this for the MCU if there are still free integer registers
84606c3fb27SDimitry Andric     // (see X86_64 ABI for full explanation).
84706c3fb27SDimitry Andric     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
84806c3fb27SDimitry Andric         canExpandIndirectArgument(Ty))
84906c3fb27SDimitry Andric       return ABIArgInfo::getExpandWithPadding(
85006c3fb27SDimitry Andric           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
85106c3fb27SDimitry Andric 
85206c3fb27SDimitry Andric     return getIndirectResult(Ty, true, State);
85306c3fb27SDimitry Andric   }
85406c3fb27SDimitry Andric 
85506c3fb27SDimitry Andric   if (const VectorType *VT = Ty->getAs<VectorType>()) {
85606c3fb27SDimitry Andric     // On Windows, vectors are passed directly if registers are available, or
85706c3fb27SDimitry Andric     // indirectly if not. This avoids the need to align argument memory. Pass
85806c3fb27SDimitry Andric     // user-defined vector types larger than 512 bits indirectly for simplicity.
85906c3fb27SDimitry Andric     if (IsWin32StructABI) {
86006c3fb27SDimitry Andric       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
86106c3fb27SDimitry Andric         --State.FreeSSERegs;
86206c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg();
86306c3fb27SDimitry Andric       }
86406c3fb27SDimitry Andric       return getIndirectResult(Ty, /*ByVal=*/false, State);
86506c3fb27SDimitry Andric     }
86606c3fb27SDimitry Andric 
86706c3fb27SDimitry Andric     // On Darwin, some vectors are passed in memory, we handle this by passing
86806c3fb27SDimitry Andric     // it as an i8/i16/i32/i64.
86906c3fb27SDimitry Andric     if (IsDarwinVectorABI) {
87006c3fb27SDimitry Andric       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
87106c3fb27SDimitry Andric           (TI.Width == 64 && VT->getNumElements() == 1))
87206c3fb27SDimitry Andric         return ABIArgInfo::getDirect(
87306c3fb27SDimitry Andric             llvm::IntegerType::get(getVMContext(), TI.Width));
87406c3fb27SDimitry Andric     }
87506c3fb27SDimitry Andric 
87606c3fb27SDimitry Andric     if (IsX86_MMXType(CGT.ConvertType(Ty)))
87706c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
87806c3fb27SDimitry Andric 
87906c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
88006c3fb27SDimitry Andric   }
88106c3fb27SDimitry Andric 
88206c3fb27SDimitry Andric 
88306c3fb27SDimitry Andric   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
88406c3fb27SDimitry Andric     Ty = EnumTy->getDecl()->getIntegerType();
88506c3fb27SDimitry Andric 
88606c3fb27SDimitry Andric   bool InReg = shouldPrimitiveUseInReg(Ty, State);
88706c3fb27SDimitry Andric 
88806c3fb27SDimitry Andric   if (isPromotableIntegerTypeForABI(Ty)) {
88906c3fb27SDimitry Andric     if (InReg)
89006c3fb27SDimitry Andric       return ABIArgInfo::getExtendInReg(Ty);
89106c3fb27SDimitry Andric     return ABIArgInfo::getExtend(Ty);
89206c3fb27SDimitry Andric   }
89306c3fb27SDimitry Andric 
89406c3fb27SDimitry Andric   if (const auto *EIT = Ty->getAs<BitIntType>()) {
89506c3fb27SDimitry Andric     if (EIT->getNumBits() <= 64) {
89606c3fb27SDimitry Andric       if (InReg)
89706c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg();
89806c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
89906c3fb27SDimitry Andric     }
90006c3fb27SDimitry Andric     return getIndirectResult(Ty, /*ByVal=*/false, State);
90106c3fb27SDimitry Andric   }
90206c3fb27SDimitry Andric 
90306c3fb27SDimitry Andric   if (InReg)
90406c3fb27SDimitry Andric     return ABIArgInfo::getDirectInReg();
90506c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
90606c3fb27SDimitry Andric }
90706c3fb27SDimitry Andric 
90806c3fb27SDimitry Andric void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
90906c3fb27SDimitry Andric   CCState State(FI);
91006c3fb27SDimitry Andric   if (IsMCUABI)
91106c3fb27SDimitry Andric     State.FreeRegs = 3;
91206c3fb27SDimitry Andric   else if (State.CC == llvm::CallingConv::X86_FastCall) {
91306c3fb27SDimitry Andric     State.FreeRegs = 2;
91406c3fb27SDimitry Andric     State.FreeSSERegs = 3;
91506c3fb27SDimitry Andric   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
91606c3fb27SDimitry Andric     State.FreeRegs = 2;
91706c3fb27SDimitry Andric     State.FreeSSERegs = 6;
91806c3fb27SDimitry Andric   } else if (FI.getHasRegParm())
91906c3fb27SDimitry Andric     State.FreeRegs = FI.getRegParm();
92006c3fb27SDimitry Andric   else if (State.CC == llvm::CallingConv::X86_RegCall) {
92106c3fb27SDimitry Andric     State.FreeRegs = 5;
92206c3fb27SDimitry Andric     State.FreeSSERegs = 8;
92306c3fb27SDimitry Andric   } else if (IsWin32StructABI) {
92406c3fb27SDimitry Andric     // Since MSVC 2015, the first three SSE vectors have been passed in
92506c3fb27SDimitry Andric     // registers. The rest are passed indirectly.
92606c3fb27SDimitry Andric     State.FreeRegs = DefaultNumRegisterParameters;
92706c3fb27SDimitry Andric     State.FreeSSERegs = 3;
92806c3fb27SDimitry Andric   } else
92906c3fb27SDimitry Andric     State.FreeRegs = DefaultNumRegisterParameters;
93006c3fb27SDimitry Andric 
93106c3fb27SDimitry Andric   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
93206c3fb27SDimitry Andric     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
93306c3fb27SDimitry Andric   } else if (FI.getReturnInfo().isIndirect()) {
93406c3fb27SDimitry Andric     // The C++ ABI is not aware of register usage, so we have to check if the
93506c3fb27SDimitry Andric     // return value was sret and put it in a register ourselves if appropriate.
93606c3fb27SDimitry Andric     if (State.FreeRegs) {
93706c3fb27SDimitry Andric       --State.FreeRegs;  // The sret parameter consumes a register.
93806c3fb27SDimitry Andric       if (!IsMCUABI)
93906c3fb27SDimitry Andric         FI.getReturnInfo().setInReg(true);
94006c3fb27SDimitry Andric     }
94106c3fb27SDimitry Andric   }
94206c3fb27SDimitry Andric 
94306c3fb27SDimitry Andric   // The chain argument effectively gives us another free register.
94406c3fb27SDimitry Andric   if (FI.isChainCall())
94506c3fb27SDimitry Andric     ++State.FreeRegs;
94606c3fb27SDimitry Andric 
94706c3fb27SDimitry Andric   // For vectorcall, do a first pass over the arguments, assigning FP and vector
94806c3fb27SDimitry Andric   // arguments to XMM registers as available.
94906c3fb27SDimitry Andric   if (State.CC == llvm::CallingConv::X86_VectorCall)
95006c3fb27SDimitry Andric     runVectorCallFirstPass(FI, State);
95106c3fb27SDimitry Andric 
95206c3fb27SDimitry Andric   bool UsedInAlloca = false;
95306c3fb27SDimitry Andric   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
9545f757f3fSDimitry Andric   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
95506c3fb27SDimitry Andric     // Skip arguments that have already been assigned.
95606c3fb27SDimitry Andric     if (State.IsPreassigned.test(I))
95706c3fb27SDimitry Andric       continue;
95806c3fb27SDimitry Andric 
9598a4dda33SDimitry Andric     Args[I].info =
9605f757f3fSDimitry Andric         classifyArgumentType(Args[I].type, State, I);
96106c3fb27SDimitry Andric     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
96206c3fb27SDimitry Andric   }
96306c3fb27SDimitry Andric 
96406c3fb27SDimitry Andric   // If we needed to use inalloca for any argument, do a second pass and rewrite
96506c3fb27SDimitry Andric   // all the memory arguments to use inalloca.
96606c3fb27SDimitry Andric   if (UsedInAlloca)
96706c3fb27SDimitry Andric     rewriteWithInAlloca(FI);
96806c3fb27SDimitry Andric }
96906c3fb27SDimitry Andric 
97006c3fb27SDimitry Andric void
97106c3fb27SDimitry Andric X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
97206c3fb27SDimitry Andric                                    CharUnits &StackOffset, ABIArgInfo &Info,
97306c3fb27SDimitry Andric                                    QualType Type) const {
97406c3fb27SDimitry Andric   // Arguments are always 4-byte-aligned.
97506c3fb27SDimitry Andric   CharUnits WordSize = CharUnits::fromQuantity(4);
97606c3fb27SDimitry Andric   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
97706c3fb27SDimitry Andric 
97806c3fb27SDimitry Andric   // sret pointers and indirect things will require an extra pointer
97906c3fb27SDimitry Andric   // indirection, unless they are byval. Most things are byval, and will not
98006c3fb27SDimitry Andric   // require this indirection.
98106c3fb27SDimitry Andric   bool IsIndirect = false;
98206c3fb27SDimitry Andric   if (Info.isIndirect() && !Info.getIndirectByVal())
98306c3fb27SDimitry Andric     IsIndirect = true;
98406c3fb27SDimitry Andric   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
98506c3fb27SDimitry Andric   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
98606c3fb27SDimitry Andric   if (IsIndirect)
98706c3fb27SDimitry Andric     LLTy = llvm::PointerType::getUnqual(getVMContext());
98806c3fb27SDimitry Andric   FrameFields.push_back(LLTy);
98906c3fb27SDimitry Andric   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
99006c3fb27SDimitry Andric 
99106c3fb27SDimitry Andric   // Insert padding bytes to respect alignment.
99206c3fb27SDimitry Andric   CharUnits FieldEnd = StackOffset;
99306c3fb27SDimitry Andric   StackOffset = FieldEnd.alignTo(WordSize);
99406c3fb27SDimitry Andric   if (StackOffset != FieldEnd) {
99506c3fb27SDimitry Andric     CharUnits NumBytes = StackOffset - FieldEnd;
99606c3fb27SDimitry Andric     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
99706c3fb27SDimitry Andric     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
99806c3fb27SDimitry Andric     FrameFields.push_back(Ty);
99906c3fb27SDimitry Andric   }
100006c3fb27SDimitry Andric }
100106c3fb27SDimitry Andric 
100206c3fb27SDimitry Andric static bool isArgInAlloca(const ABIArgInfo &Info) {
100306c3fb27SDimitry Andric   // Leave ignored and inreg arguments alone.
100406c3fb27SDimitry Andric   switch (Info.getKind()) {
100506c3fb27SDimitry Andric   case ABIArgInfo::InAlloca:
100606c3fb27SDimitry Andric     return true;
100706c3fb27SDimitry Andric   case ABIArgInfo::Ignore:
100806c3fb27SDimitry Andric   case ABIArgInfo::IndirectAliased:
100906c3fb27SDimitry Andric     return false;
101006c3fb27SDimitry Andric   case ABIArgInfo::Indirect:
101106c3fb27SDimitry Andric   case ABIArgInfo::Direct:
101206c3fb27SDimitry Andric   case ABIArgInfo::Extend:
101306c3fb27SDimitry Andric     return !Info.getInReg();
101406c3fb27SDimitry Andric   case ABIArgInfo::Expand:
101506c3fb27SDimitry Andric   case ABIArgInfo::CoerceAndExpand:
101606c3fb27SDimitry Andric     // These are aggregate types which are never passed in registers when
101706c3fb27SDimitry Andric     // inalloca is involved.
101806c3fb27SDimitry Andric     return true;
101906c3fb27SDimitry Andric   }
102006c3fb27SDimitry Andric   llvm_unreachable("invalid enum");
102106c3fb27SDimitry Andric }
102206c3fb27SDimitry Andric 
102306c3fb27SDimitry Andric void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
102406c3fb27SDimitry Andric   assert(IsWin32StructABI && "inalloca only supported on win32");
102506c3fb27SDimitry Andric 
102606c3fb27SDimitry Andric   // Build a packed struct type for all of the arguments in memory.
102706c3fb27SDimitry Andric   SmallVector<llvm::Type *, 6> FrameFields;
102806c3fb27SDimitry Andric 
102906c3fb27SDimitry Andric   // The stack alignment is always 4.
103006c3fb27SDimitry Andric   CharUnits StackAlign = CharUnits::fromQuantity(4);
103106c3fb27SDimitry Andric 
103206c3fb27SDimitry Andric   CharUnits StackOffset;
103306c3fb27SDimitry Andric   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
103406c3fb27SDimitry Andric 
103506c3fb27SDimitry Andric   // Put 'this' into the struct before 'sret', if necessary.
103606c3fb27SDimitry Andric   bool IsThisCall =
103706c3fb27SDimitry Andric       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
103806c3fb27SDimitry Andric   ABIArgInfo &Ret = FI.getReturnInfo();
103906c3fb27SDimitry Andric   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
104006c3fb27SDimitry Andric       isArgInAlloca(I->info)) {
104106c3fb27SDimitry Andric     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
104206c3fb27SDimitry Andric     ++I;
104306c3fb27SDimitry Andric   }
104406c3fb27SDimitry Andric 
104506c3fb27SDimitry Andric   // Put the sret parameter into the inalloca struct if it's in memory.
104606c3fb27SDimitry Andric   if (Ret.isIndirect() && !Ret.getInReg()) {
104706c3fb27SDimitry Andric     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
104806c3fb27SDimitry Andric     // On Windows, the hidden sret parameter is always returned in eax.
104906c3fb27SDimitry Andric     Ret.setInAllocaSRet(IsWin32StructABI);
105006c3fb27SDimitry Andric   }
105106c3fb27SDimitry Andric 
105206c3fb27SDimitry Andric   // Skip the 'this' parameter in ecx.
105306c3fb27SDimitry Andric   if (IsThisCall)
105406c3fb27SDimitry Andric     ++I;
105506c3fb27SDimitry Andric 
105606c3fb27SDimitry Andric   // Put arguments passed in memory into the struct.
105706c3fb27SDimitry Andric   for (; I != E; ++I) {
105806c3fb27SDimitry Andric     if (isArgInAlloca(I->info))
105906c3fb27SDimitry Andric       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
106006c3fb27SDimitry Andric   }
106106c3fb27SDimitry Andric 
106206c3fb27SDimitry Andric   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
106306c3fb27SDimitry Andric                                         /*isPacked=*/true),
106406c3fb27SDimitry Andric                   StackAlign);
106506c3fb27SDimitry Andric }
106606c3fb27SDimitry Andric 
106706c3fb27SDimitry Andric Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
106806c3fb27SDimitry Andric                                  Address VAListAddr, QualType Ty) const {
106906c3fb27SDimitry Andric 
107006c3fb27SDimitry Andric   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
107106c3fb27SDimitry Andric 
107206c3fb27SDimitry Andric   // x86-32 changes the alignment of certain arguments on the stack.
107306c3fb27SDimitry Andric   //
107406c3fb27SDimitry Andric   // Just messing with TypeInfo like this works because we never pass
107506c3fb27SDimitry Andric   // anything indirectly.
107606c3fb27SDimitry Andric   TypeInfo.Align = CharUnits::fromQuantity(
107706c3fb27SDimitry Andric                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
107806c3fb27SDimitry Andric 
107906c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
108006c3fb27SDimitry Andric                           TypeInfo, CharUnits::fromQuantity(4),
108106c3fb27SDimitry Andric                           /*AllowHigherAlign*/ true);
108206c3fb27SDimitry Andric }
108306c3fb27SDimitry Andric 
108406c3fb27SDimitry Andric bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
108506c3fb27SDimitry Andric     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
108606c3fb27SDimitry Andric   assert(Triple.getArch() == llvm::Triple::x86);
108706c3fb27SDimitry Andric 
108806c3fb27SDimitry Andric   switch (Opts.getStructReturnConvention()) {
108906c3fb27SDimitry Andric   case CodeGenOptions::SRCK_Default:
109006c3fb27SDimitry Andric     break;
109106c3fb27SDimitry Andric   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
109206c3fb27SDimitry Andric     return false;
109306c3fb27SDimitry Andric   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
109406c3fb27SDimitry Andric     return true;
109506c3fb27SDimitry Andric   }
109606c3fb27SDimitry Andric 
109706c3fb27SDimitry Andric   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
109806c3fb27SDimitry Andric     return true;
109906c3fb27SDimitry Andric 
110006c3fb27SDimitry Andric   switch (Triple.getOS()) {
110106c3fb27SDimitry Andric   case llvm::Triple::DragonFly:
110206c3fb27SDimitry Andric   case llvm::Triple::FreeBSD:
110306c3fb27SDimitry Andric   case llvm::Triple::OpenBSD:
110406c3fb27SDimitry Andric   case llvm::Triple::Win32:
110506c3fb27SDimitry Andric     return true;
110606c3fb27SDimitry Andric   default:
110706c3fb27SDimitry Andric     return false;
110806c3fb27SDimitry Andric   }
110906c3fb27SDimitry Andric }
111006c3fb27SDimitry Andric 
111106c3fb27SDimitry Andric static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
111206c3fb27SDimitry Andric                                  CodeGen::CodeGenModule &CGM) {
111306c3fb27SDimitry Andric   if (!FD->hasAttr<AnyX86InterruptAttr>())
111406c3fb27SDimitry Andric     return;
111506c3fb27SDimitry Andric 
111606c3fb27SDimitry Andric   llvm::Function *Fn = cast<llvm::Function>(GV);
111706c3fb27SDimitry Andric   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
111806c3fb27SDimitry Andric   if (FD->getNumParams() == 0)
111906c3fb27SDimitry Andric     return;
112006c3fb27SDimitry Andric 
112106c3fb27SDimitry Andric   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
112206c3fb27SDimitry Andric   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
112306c3fb27SDimitry Andric   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
112406c3fb27SDimitry Andric     Fn->getContext(), ByValTy);
112506c3fb27SDimitry Andric   Fn->addParamAttr(0, NewAttr);
112606c3fb27SDimitry Andric }
112706c3fb27SDimitry Andric 
112806c3fb27SDimitry Andric void X86_32TargetCodeGenInfo::setTargetAttributes(
112906c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
113006c3fb27SDimitry Andric   if (GV->isDeclaration())
113106c3fb27SDimitry Andric     return;
113206c3fb27SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
113306c3fb27SDimitry Andric     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
113406c3fb27SDimitry Andric       llvm::Function *Fn = cast<llvm::Function>(GV);
113506c3fb27SDimitry Andric       Fn->addFnAttr("stackrealign");
113606c3fb27SDimitry Andric     }
113706c3fb27SDimitry Andric 
113806c3fb27SDimitry Andric     addX86InterruptAttrs(FD, GV, CGM);
113906c3fb27SDimitry Andric   }
114006c3fb27SDimitry Andric }
114106c3fb27SDimitry Andric 
114206c3fb27SDimitry Andric bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
114306c3fb27SDimitry Andric                                                CodeGen::CodeGenFunction &CGF,
114406c3fb27SDimitry Andric                                                llvm::Value *Address) const {
114506c3fb27SDimitry Andric   CodeGen::CGBuilderTy &Builder = CGF.Builder;
114606c3fb27SDimitry Andric 
114706c3fb27SDimitry Andric   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
114806c3fb27SDimitry Andric 
114906c3fb27SDimitry Andric   // 0-7 are the eight integer registers;  the order is different
115006c3fb27SDimitry Andric   //   on Darwin (for EH), but the range is the same.
115106c3fb27SDimitry Andric   // 8 is %eip.
115206c3fb27SDimitry Andric   AssignToArrayRange(Builder, Address, Four8, 0, 8);
115306c3fb27SDimitry Andric 
115406c3fb27SDimitry Andric   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
115506c3fb27SDimitry Andric     // 12-16 are st(0..4).  Not sure why we stop at 4.
115606c3fb27SDimitry Andric     // These have size 16, which is sizeof(long double) on
115706c3fb27SDimitry Andric     // platforms with 8-byte alignment for that type.
115806c3fb27SDimitry Andric     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
115906c3fb27SDimitry Andric     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
116006c3fb27SDimitry Andric 
116106c3fb27SDimitry Andric   } else {
116206c3fb27SDimitry Andric     // 9 is %eflags, which doesn't get a size on Darwin for some
116306c3fb27SDimitry Andric     // reason.
116406c3fb27SDimitry Andric     Builder.CreateAlignedStore(
116506c3fb27SDimitry Andric         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
116606c3fb27SDimitry Andric                                CharUnits::One());
116706c3fb27SDimitry Andric 
116806c3fb27SDimitry Andric     // 11-16 are st(0..5).  Not sure why we stop at 5.
116906c3fb27SDimitry Andric     // These have size 12, which is sizeof(long double) on
117006c3fb27SDimitry Andric     // platforms with 4-byte alignment for that type.
117106c3fb27SDimitry Andric     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
117206c3fb27SDimitry Andric     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
117306c3fb27SDimitry Andric   }
117406c3fb27SDimitry Andric 
117506c3fb27SDimitry Andric   return false;
117606c3fb27SDimitry Andric }
117706c3fb27SDimitry Andric 
117806c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
117906c3fb27SDimitry Andric // X86-64 ABI Implementation
118006c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
118106c3fb27SDimitry Andric 
118206c3fb27SDimitry Andric 
118306c3fb27SDimitry Andric namespace {
118406c3fb27SDimitry Andric 
118506c3fb27SDimitry Andric /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
118606c3fb27SDimitry Andric static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
118706c3fb27SDimitry Andric   switch (AVXLevel) {
118806c3fb27SDimitry Andric   case X86AVXABILevel::AVX512:
118906c3fb27SDimitry Andric     return 512;
119006c3fb27SDimitry Andric   case X86AVXABILevel::AVX:
119106c3fb27SDimitry Andric     return 256;
119206c3fb27SDimitry Andric   case X86AVXABILevel::None:
119306c3fb27SDimitry Andric     return 128;
119406c3fb27SDimitry Andric   }
119506c3fb27SDimitry Andric   llvm_unreachable("Unknown AVXLevel");
119606c3fb27SDimitry Andric }
119706c3fb27SDimitry Andric 
119806c3fb27SDimitry Andric /// X86_64ABIInfo - The X86_64 ABI information.
119906c3fb27SDimitry Andric class X86_64ABIInfo : public ABIInfo {
120006c3fb27SDimitry Andric   enum Class {
120106c3fb27SDimitry Andric     Integer = 0,
120206c3fb27SDimitry Andric     SSE,
120306c3fb27SDimitry Andric     SSEUp,
120406c3fb27SDimitry Andric     X87,
120506c3fb27SDimitry Andric     X87Up,
120606c3fb27SDimitry Andric     ComplexX87,
120706c3fb27SDimitry Andric     NoClass,
120806c3fb27SDimitry Andric     Memory
120906c3fb27SDimitry Andric   };
121006c3fb27SDimitry Andric 
121106c3fb27SDimitry Andric   /// merge - Implement the X86_64 ABI merging algorithm.
121206c3fb27SDimitry Andric   ///
121306c3fb27SDimitry Andric   /// Merge an accumulating classification \arg Accum with a field
121406c3fb27SDimitry Andric   /// classification \arg Field.
121506c3fb27SDimitry Andric   ///
121606c3fb27SDimitry Andric   /// \param Accum - The accumulating classification. This should
121706c3fb27SDimitry Andric   /// always be either NoClass or the result of a previous merge
121806c3fb27SDimitry Andric   /// call. In addition, this should never be Memory (the caller
121906c3fb27SDimitry Andric   /// should just return Memory for the aggregate).
122006c3fb27SDimitry Andric   static Class merge(Class Accum, Class Field);
122106c3fb27SDimitry Andric 
122206c3fb27SDimitry Andric   /// postMerge - Implement the X86_64 ABI post merging algorithm.
122306c3fb27SDimitry Andric   ///
122406c3fb27SDimitry Andric   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
122506c3fb27SDimitry Andric   /// final MEMORY or SSE classes when necessary.
122606c3fb27SDimitry Andric   ///
122706c3fb27SDimitry Andric   /// \param AggregateSize - The size of the current aggregate in
122806c3fb27SDimitry Andric   /// the classification process.
122906c3fb27SDimitry Andric   ///
123006c3fb27SDimitry Andric   /// \param Lo - The classification for the parts of the type
123106c3fb27SDimitry Andric   /// residing in the low word of the containing object.
123206c3fb27SDimitry Andric   ///
123306c3fb27SDimitry Andric   /// \param Hi - The classification for the parts of the type
123406c3fb27SDimitry Andric   /// residing in the higher words of the containing object.
123506c3fb27SDimitry Andric   ///
123606c3fb27SDimitry Andric   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
123706c3fb27SDimitry Andric 
123806c3fb27SDimitry Andric   /// classify - Determine the x86_64 register classes in which the
123906c3fb27SDimitry Andric   /// given type T should be passed.
124006c3fb27SDimitry Andric   ///
124106c3fb27SDimitry Andric   /// \param Lo - The classification for the parts of the type
124206c3fb27SDimitry Andric   /// residing in the low word of the containing object.
124306c3fb27SDimitry Andric   ///
124406c3fb27SDimitry Andric   /// \param Hi - The classification for the parts of the type
124506c3fb27SDimitry Andric   /// residing in the high word of the containing object.
124606c3fb27SDimitry Andric   ///
124706c3fb27SDimitry Andric   /// \param OffsetBase - The bit offset of this type in the
124806c3fb27SDimitry Andric   /// containing object.  Some parameters are classified different
124906c3fb27SDimitry Andric   /// depending on whether they straddle an eightbyte boundary.
125006c3fb27SDimitry Andric   ///
125106c3fb27SDimitry Andric   /// \param isNamedArg - Whether the argument in question is a "named"
125206c3fb27SDimitry Andric   /// argument, as used in AMD64-ABI 3.5.7.
125306c3fb27SDimitry Andric   ///
125406c3fb27SDimitry Andric   /// \param IsRegCall - Whether the calling conversion is regcall.
125506c3fb27SDimitry Andric   ///
125606c3fb27SDimitry Andric   /// If a word is unused its result will be NoClass; if a type should
125706c3fb27SDimitry Andric   /// be passed in Memory then at least the classification of \arg Lo
125806c3fb27SDimitry Andric   /// will be Memory.
125906c3fb27SDimitry Andric   ///
126006c3fb27SDimitry Andric   /// The \arg Lo class will be NoClass iff the argument is ignored.
126106c3fb27SDimitry Andric   ///
126206c3fb27SDimitry Andric   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
126306c3fb27SDimitry Andric   /// also be ComplexX87.
126406c3fb27SDimitry Andric   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
126506c3fb27SDimitry Andric                 bool isNamedArg, bool IsRegCall = false) const;
126606c3fb27SDimitry Andric 
126706c3fb27SDimitry Andric   llvm::Type *GetByteVectorType(QualType Ty) const;
126806c3fb27SDimitry Andric   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
126906c3fb27SDimitry Andric                                  unsigned IROffset, QualType SourceTy,
127006c3fb27SDimitry Andric                                  unsigned SourceOffset) const;
127106c3fb27SDimitry Andric   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
127206c3fb27SDimitry Andric                                      unsigned IROffset, QualType SourceTy,
127306c3fb27SDimitry Andric                                      unsigned SourceOffset) const;
127406c3fb27SDimitry Andric 
127506c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
127606c3fb27SDimitry Andric   /// such that the argument will be returned in memory.
127706c3fb27SDimitry Andric   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
127806c3fb27SDimitry Andric 
127906c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
128006c3fb27SDimitry Andric   /// such that the argument will be passed in memory.
128106c3fb27SDimitry Andric   ///
128206c3fb27SDimitry Andric   /// \param freeIntRegs - The number of free integer registers remaining
128306c3fb27SDimitry Andric   /// available.
128406c3fb27SDimitry Andric   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
128506c3fb27SDimitry Andric 
128606c3fb27SDimitry Andric   ABIArgInfo classifyReturnType(QualType RetTy) const;
128706c3fb27SDimitry Andric 
128806c3fb27SDimitry Andric   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
128906c3fb27SDimitry Andric                                   unsigned &neededInt, unsigned &neededSSE,
129006c3fb27SDimitry Andric                                   bool isNamedArg,
129106c3fb27SDimitry Andric                                   bool IsRegCall = false) const;
129206c3fb27SDimitry Andric 
129306c3fb27SDimitry Andric   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
129406c3fb27SDimitry Andric                                        unsigned &NeededSSE,
129506c3fb27SDimitry Andric                                        unsigned &MaxVectorWidth) const;
129606c3fb27SDimitry Andric 
129706c3fb27SDimitry Andric   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
129806c3fb27SDimitry Andric                                            unsigned &NeededSSE,
129906c3fb27SDimitry Andric                                            unsigned &MaxVectorWidth) const;
130006c3fb27SDimitry Andric 
130106c3fb27SDimitry Andric   bool IsIllegalVectorType(QualType Ty) const;
130206c3fb27SDimitry Andric 
130306c3fb27SDimitry Andric   /// The 0.98 ABI revision clarified a lot of ambiguities,
130406c3fb27SDimitry Andric   /// unfortunately in ways that were not always consistent with
130506c3fb27SDimitry Andric   /// certain previous compilers.  In particular, platforms which
130606c3fb27SDimitry Andric   /// required strict binary compatibility with older versions of GCC
130706c3fb27SDimitry Andric   /// may need to exempt themselves.
130806c3fb27SDimitry Andric   bool honorsRevision0_98() const {
130906c3fb27SDimitry Andric     return !getTarget().getTriple().isOSDarwin();
131006c3fb27SDimitry Andric   }
131106c3fb27SDimitry Andric 
131206c3fb27SDimitry Andric   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
131306c3fb27SDimitry Andric   /// classify it as INTEGER (for compatibility with older clang compilers).
131406c3fb27SDimitry Andric   bool classifyIntegerMMXAsSSE() const {
131506c3fb27SDimitry Andric     // Clang <= 3.8 did not do this.
131606c3fb27SDimitry Andric     if (getContext().getLangOpts().getClangABICompat() <=
131706c3fb27SDimitry Andric         LangOptions::ClangABI::Ver3_8)
131806c3fb27SDimitry Andric       return false;
131906c3fb27SDimitry Andric 
132006c3fb27SDimitry Andric     const llvm::Triple &Triple = getTarget().getTriple();
132106c3fb27SDimitry Andric     if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD())
132206c3fb27SDimitry Andric       return false;
132306c3fb27SDimitry Andric     return true;
132406c3fb27SDimitry Andric   }
132506c3fb27SDimitry Andric 
132606c3fb27SDimitry Andric   // GCC classifies vectors of __int128 as memory.
132706c3fb27SDimitry Andric   bool passInt128VectorsInMem() const {
132806c3fb27SDimitry Andric     // Clang <= 9.0 did not do this.
132906c3fb27SDimitry Andric     if (getContext().getLangOpts().getClangABICompat() <=
133006c3fb27SDimitry Andric         LangOptions::ClangABI::Ver9)
133106c3fb27SDimitry Andric       return false;
133206c3fb27SDimitry Andric 
133306c3fb27SDimitry Andric     const llvm::Triple &T = getTarget().getTriple();
133406c3fb27SDimitry Andric     return T.isOSLinux() || T.isOSNetBSD();
133506c3fb27SDimitry Andric   }
133606c3fb27SDimitry Andric 
133706c3fb27SDimitry Andric   X86AVXABILevel AVXLevel;
133806c3fb27SDimitry Andric   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
133906c3fb27SDimitry Andric   // 64-bit hardware.
134006c3fb27SDimitry Andric   bool Has64BitPointers;
134106c3fb27SDimitry Andric 
134206c3fb27SDimitry Andric public:
134306c3fb27SDimitry Andric   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
134406c3fb27SDimitry Andric       : ABIInfo(CGT), AVXLevel(AVXLevel),
134506c3fb27SDimitry Andric         Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {}
134606c3fb27SDimitry Andric 
134706c3fb27SDimitry Andric   bool isPassedUsingAVXType(QualType type) const {
134806c3fb27SDimitry Andric     unsigned neededInt, neededSSE;
134906c3fb27SDimitry Andric     // The freeIntRegs argument doesn't matter here.
135006c3fb27SDimitry Andric     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
135106c3fb27SDimitry Andric                                            /*isNamedArg*/true);
135206c3fb27SDimitry Andric     if (info.isDirect()) {
135306c3fb27SDimitry Andric       llvm::Type *ty = info.getCoerceToType();
135406c3fb27SDimitry Andric       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
135506c3fb27SDimitry Andric         return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
135606c3fb27SDimitry Andric     }
135706c3fb27SDimitry Andric     return false;
135806c3fb27SDimitry Andric   }
135906c3fb27SDimitry Andric 
136006c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
136106c3fb27SDimitry Andric 
136206c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
136306c3fb27SDimitry Andric                     QualType Ty) const override;
136406c3fb27SDimitry Andric   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
136506c3fb27SDimitry Andric                       QualType Ty) const override;
136606c3fb27SDimitry Andric 
136706c3fb27SDimitry Andric   bool has64BitPointers() const {
136806c3fb27SDimitry Andric     return Has64BitPointers;
136906c3fb27SDimitry Andric   }
137006c3fb27SDimitry Andric };
137106c3fb27SDimitry Andric 
137206c3fb27SDimitry Andric /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
137306c3fb27SDimitry Andric class WinX86_64ABIInfo : public ABIInfo {
137406c3fb27SDimitry Andric public:
137506c3fb27SDimitry Andric   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
137606c3fb27SDimitry Andric       : ABIInfo(CGT), AVXLevel(AVXLevel),
137706c3fb27SDimitry Andric         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
137806c3fb27SDimitry Andric 
137906c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
138006c3fb27SDimitry Andric 
138106c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
138206c3fb27SDimitry Andric                     QualType Ty) const override;
138306c3fb27SDimitry Andric 
138406c3fb27SDimitry Andric   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
138506c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
138606c3fb27SDimitry Andric     return isX86VectorTypeForVectorCall(getContext(), Ty);
138706c3fb27SDimitry Andric   }
138806c3fb27SDimitry Andric 
138906c3fb27SDimitry Andric   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
139006c3fb27SDimitry Andric                                          uint64_t NumMembers) const override {
139106c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
139206c3fb27SDimitry Andric     return isX86VectorCallAggregateSmallEnough(NumMembers);
139306c3fb27SDimitry Andric   }
139406c3fb27SDimitry Andric 
139506c3fb27SDimitry Andric private:
139606c3fb27SDimitry Andric   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
139706c3fb27SDimitry Andric                       bool IsVectorCall, bool IsRegCall) const;
139806c3fb27SDimitry Andric   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
139906c3fb27SDimitry Andric                                            const ABIArgInfo &current) const;
140006c3fb27SDimitry Andric 
140106c3fb27SDimitry Andric   X86AVXABILevel AVXLevel;
140206c3fb27SDimitry Andric 
140306c3fb27SDimitry Andric   bool IsMingw64;
140406c3fb27SDimitry Andric };
140506c3fb27SDimitry Andric 
140606c3fb27SDimitry Andric class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
140706c3fb27SDimitry Andric public:
140806c3fb27SDimitry Andric   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
140906c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {
141006c3fb27SDimitry Andric     SwiftInfo =
141106c3fb27SDimitry Andric         std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
141206c3fb27SDimitry Andric   }
141306c3fb27SDimitry Andric 
141406c3fb27SDimitry Andric   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
141506c3fb27SDimitry Andric   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
141606c3fb27SDimitry Andric   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
141706c3fb27SDimitry Andric 
141806c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
141906c3fb27SDimitry Andric     return 7;
142006c3fb27SDimitry Andric   }
142106c3fb27SDimitry Andric 
142206c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
142306c3fb27SDimitry Andric                                llvm::Value *Address) const override {
142406c3fb27SDimitry Andric     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
142506c3fb27SDimitry Andric 
142606c3fb27SDimitry Andric     // 0-15 are the 16 integer registers.
142706c3fb27SDimitry Andric     // 16 is %rip.
142806c3fb27SDimitry Andric     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
142906c3fb27SDimitry Andric     return false;
143006c3fb27SDimitry Andric   }
143106c3fb27SDimitry Andric 
143206c3fb27SDimitry Andric   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
143306c3fb27SDimitry Andric                                   StringRef Constraint,
143406c3fb27SDimitry Andric                                   llvm::Type* Ty) const override {
143506c3fb27SDimitry Andric     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
143606c3fb27SDimitry Andric   }
143706c3fb27SDimitry Andric 
143806c3fb27SDimitry Andric   bool isNoProtoCallVariadic(const CallArgList &args,
143906c3fb27SDimitry Andric                              const FunctionNoProtoType *fnType) const override {
144006c3fb27SDimitry Andric     // The default CC on x86-64 sets %al to the number of SSA
144106c3fb27SDimitry Andric     // registers used, and GCC sets this when calling an unprototyped
144206c3fb27SDimitry Andric     // function, so we override the default behavior.  However, don't do
144306c3fb27SDimitry Andric     // that when AVX types are involved: the ABI explicitly states it is
144406c3fb27SDimitry Andric     // undefined, and it doesn't work in practice because of how the ABI
144506c3fb27SDimitry Andric     // defines varargs anyway.
144606c3fb27SDimitry Andric     if (fnType->getCallConv() == CC_C) {
144706c3fb27SDimitry Andric       bool HasAVXType = false;
144806c3fb27SDimitry Andric       for (CallArgList::const_iterator
144906c3fb27SDimitry Andric              it = args.begin(), ie = args.end(); it != ie; ++it) {
145006c3fb27SDimitry Andric         if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(it->Ty)) {
145106c3fb27SDimitry Andric           HasAVXType = true;
145206c3fb27SDimitry Andric           break;
145306c3fb27SDimitry Andric         }
145406c3fb27SDimitry Andric       }
145506c3fb27SDimitry Andric 
145606c3fb27SDimitry Andric       if (!HasAVXType)
145706c3fb27SDimitry Andric         return true;
145806c3fb27SDimitry Andric     }
145906c3fb27SDimitry Andric 
146006c3fb27SDimitry Andric     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
146106c3fb27SDimitry Andric   }
146206c3fb27SDimitry Andric 
146306c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
146406c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override {
146506c3fb27SDimitry Andric     if (GV->isDeclaration())
146606c3fb27SDimitry Andric       return;
146706c3fb27SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
146806c3fb27SDimitry Andric       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
146906c3fb27SDimitry Andric         llvm::Function *Fn = cast<llvm::Function>(GV);
147006c3fb27SDimitry Andric         Fn->addFnAttr("stackrealign");
147106c3fb27SDimitry Andric       }
147206c3fb27SDimitry Andric 
147306c3fb27SDimitry Andric       addX86InterruptAttrs(FD, GV, CGM);
147406c3fb27SDimitry Andric     }
147506c3fb27SDimitry Andric   }
147606c3fb27SDimitry Andric 
147706c3fb27SDimitry Andric   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
147806c3fb27SDimitry Andric                             const FunctionDecl *Caller,
147906c3fb27SDimitry Andric                             const FunctionDecl *Callee,
148006c3fb27SDimitry Andric                             const CallArgList &Args) const override;
148106c3fb27SDimitry Andric };
148206c3fb27SDimitry Andric } // namespace
148306c3fb27SDimitry Andric 
148406c3fb27SDimitry Andric static void initFeatureMaps(const ASTContext &Ctx,
148506c3fb27SDimitry Andric                             llvm::StringMap<bool> &CallerMap,
148606c3fb27SDimitry Andric                             const FunctionDecl *Caller,
148706c3fb27SDimitry Andric                             llvm::StringMap<bool> &CalleeMap,
148806c3fb27SDimitry Andric                             const FunctionDecl *Callee) {
148906c3fb27SDimitry Andric   if (CalleeMap.empty() && CallerMap.empty()) {
149006c3fb27SDimitry Andric     // The caller is potentially nullptr in the case where the call isn't in a
149106c3fb27SDimitry Andric     // function.  In this case, the getFunctionFeatureMap ensures we just get
149206c3fb27SDimitry Andric     // the TU level setting (since it cannot be modified by 'target'..
149306c3fb27SDimitry Andric     Ctx.getFunctionFeatureMap(CallerMap, Caller);
149406c3fb27SDimitry Andric     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
149506c3fb27SDimitry Andric   }
149606c3fb27SDimitry Andric }
149706c3fb27SDimitry Andric 
149806c3fb27SDimitry Andric static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
149906c3fb27SDimitry Andric                                  SourceLocation CallLoc,
150006c3fb27SDimitry Andric                                  const llvm::StringMap<bool> &CallerMap,
150106c3fb27SDimitry Andric                                  const llvm::StringMap<bool> &CalleeMap,
150206c3fb27SDimitry Andric                                  QualType Ty, StringRef Feature,
150306c3fb27SDimitry Andric                                  bool IsArgument) {
150406c3fb27SDimitry Andric   bool CallerHasFeat = CallerMap.lookup(Feature);
150506c3fb27SDimitry Andric   bool CalleeHasFeat = CalleeMap.lookup(Feature);
150606c3fb27SDimitry Andric   if (!CallerHasFeat && !CalleeHasFeat)
150706c3fb27SDimitry Andric     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
150806c3fb27SDimitry Andric            << IsArgument << Ty << Feature;
150906c3fb27SDimitry Andric 
151006c3fb27SDimitry Andric   // Mixing calling conventions here is very clearly an error.
151106c3fb27SDimitry Andric   if (!CallerHasFeat || !CalleeHasFeat)
151206c3fb27SDimitry Andric     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
151306c3fb27SDimitry Andric            << IsArgument << Ty << Feature;
151406c3fb27SDimitry Andric 
151506c3fb27SDimitry Andric   // Else, both caller and callee have the required feature, so there is no need
151606c3fb27SDimitry Andric   // to diagnose.
151706c3fb27SDimitry Andric   return false;
151806c3fb27SDimitry Andric }
151906c3fb27SDimitry Andric 
15205f757f3fSDimitry Andric static bool checkAVX512ParamFeature(DiagnosticsEngine &Diag,
15215f757f3fSDimitry Andric                                     SourceLocation CallLoc,
15225f757f3fSDimitry Andric                                     const llvm::StringMap<bool> &CallerMap,
15235f757f3fSDimitry Andric                                     const llvm::StringMap<bool> &CalleeMap,
15245f757f3fSDimitry Andric                                     QualType Ty, bool IsArgument) {
15255f757f3fSDimitry Andric   bool Caller256 = CallerMap.lookup("avx512f") && !CallerMap.lookup("evex512");
15265f757f3fSDimitry Andric   bool Callee256 = CalleeMap.lookup("avx512f") && !CalleeMap.lookup("evex512");
15275f757f3fSDimitry Andric 
15285f757f3fSDimitry Andric   // Forbid 512-bit or larger vector pass or return when we disabled ZMM
15295f757f3fSDimitry Andric   // instructions.
15305f757f3fSDimitry Andric   if (Caller256 || Callee256)
15315f757f3fSDimitry Andric     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
15325f757f3fSDimitry Andric            << IsArgument << Ty << "evex512";
15335f757f3fSDimitry Andric 
15345f757f3fSDimitry Andric   return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
15355f757f3fSDimitry Andric                               "avx512f", IsArgument);
15365f757f3fSDimitry Andric }
15375f757f3fSDimitry Andric 
153806c3fb27SDimitry Andric static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
153906c3fb27SDimitry Andric                           SourceLocation CallLoc,
154006c3fb27SDimitry Andric                           const llvm::StringMap<bool> &CallerMap,
154106c3fb27SDimitry Andric                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
154206c3fb27SDimitry Andric                           bool IsArgument) {
154306c3fb27SDimitry Andric   uint64_t Size = Ctx.getTypeSize(Ty);
154406c3fb27SDimitry Andric   if (Size > 256)
15455f757f3fSDimitry Andric     return checkAVX512ParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
15465f757f3fSDimitry Andric                                    IsArgument);
154706c3fb27SDimitry Andric 
154806c3fb27SDimitry Andric   if (Size > 128)
154906c3fb27SDimitry Andric     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
155006c3fb27SDimitry Andric                                 IsArgument);
155106c3fb27SDimitry Andric 
155206c3fb27SDimitry Andric   return false;
155306c3fb27SDimitry Andric }
155406c3fb27SDimitry Andric 
155506c3fb27SDimitry Andric void X86_64TargetCodeGenInfo::checkFunctionCallABI(
155606c3fb27SDimitry Andric     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
155706c3fb27SDimitry Andric     const FunctionDecl *Callee, const CallArgList &Args) const {
155806c3fb27SDimitry Andric   llvm::StringMap<bool> CallerMap;
155906c3fb27SDimitry Andric   llvm::StringMap<bool> CalleeMap;
156006c3fb27SDimitry Andric   unsigned ArgIndex = 0;
156106c3fb27SDimitry Andric 
156206c3fb27SDimitry Andric   // We need to loop through the actual call arguments rather than the
156306c3fb27SDimitry Andric   // function's parameters, in case this variadic.
156406c3fb27SDimitry Andric   for (const CallArg &Arg : Args) {
156506c3fb27SDimitry Andric     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
156606c3fb27SDimitry Andric     // additionally changes how vectors >256 in size are passed. Like GCC, we
156706c3fb27SDimitry Andric     // warn when a function is called with an argument where this will change.
156806c3fb27SDimitry Andric     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
156906c3fb27SDimitry Andric     // the caller and callee features are mismatched.
157006c3fb27SDimitry Andric     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
157106c3fb27SDimitry Andric     // change its ABI with attribute-target after this call.
157206c3fb27SDimitry Andric     if (Arg.getType()->isVectorType() &&
157306c3fb27SDimitry Andric         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
157406c3fb27SDimitry Andric       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
157506c3fb27SDimitry Andric       QualType Ty = Arg.getType();
157606c3fb27SDimitry Andric       // The CallArg seems to have desugared the type already, so for clearer
157706c3fb27SDimitry Andric       // diagnostics, replace it with the type in the FunctionDecl if possible.
157806c3fb27SDimitry Andric       if (ArgIndex < Callee->getNumParams())
157906c3fb27SDimitry Andric         Ty = Callee->getParamDecl(ArgIndex)->getType();
158006c3fb27SDimitry Andric 
158106c3fb27SDimitry Andric       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
158206c3fb27SDimitry Andric                         CalleeMap, Ty, /*IsArgument*/ true))
158306c3fb27SDimitry Andric         return;
158406c3fb27SDimitry Andric     }
158506c3fb27SDimitry Andric     ++ArgIndex;
158606c3fb27SDimitry Andric   }
158706c3fb27SDimitry Andric 
158806c3fb27SDimitry Andric   // Check return always, as we don't have a good way of knowing in codegen
158906c3fb27SDimitry Andric   // whether this value is used, tail-called, etc.
159006c3fb27SDimitry Andric   if (Callee->getReturnType()->isVectorType() &&
159106c3fb27SDimitry Andric       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
159206c3fb27SDimitry Andric     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
159306c3fb27SDimitry Andric     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
159406c3fb27SDimitry Andric                   CalleeMap, Callee->getReturnType(),
159506c3fb27SDimitry Andric                   /*IsArgument*/ false);
159606c3fb27SDimitry Andric   }
159706c3fb27SDimitry Andric }
159806c3fb27SDimitry Andric 
159906c3fb27SDimitry Andric std::string TargetCodeGenInfo::qualifyWindowsLibrary(StringRef Lib) {
160006c3fb27SDimitry Andric   // If the argument does not end in .lib, automatically add the suffix.
160106c3fb27SDimitry Andric   // If the argument contains a space, enclose it in quotes.
160206c3fb27SDimitry Andric   // This matches the behavior of MSVC.
160306c3fb27SDimitry Andric   bool Quote = Lib.contains(' ');
160406c3fb27SDimitry Andric   std::string ArgStr = Quote ? "\"" : "";
160506c3fb27SDimitry Andric   ArgStr += Lib;
160606c3fb27SDimitry Andric   if (!Lib.ends_with_insensitive(".lib") && !Lib.ends_with_insensitive(".a"))
160706c3fb27SDimitry Andric     ArgStr += ".lib";
160806c3fb27SDimitry Andric   ArgStr += Quote ? "\"" : "";
160906c3fb27SDimitry Andric   return ArgStr;
161006c3fb27SDimitry Andric }
161106c3fb27SDimitry Andric 
161206c3fb27SDimitry Andric namespace {
161306c3fb27SDimitry Andric class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
161406c3fb27SDimitry Andric public:
161506c3fb27SDimitry Andric   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
161606c3fb27SDimitry Andric         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
161706c3fb27SDimitry Andric         unsigned NumRegisterParameters)
161806c3fb27SDimitry Andric     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
161906c3fb27SDimitry Andric         Win32StructABI, NumRegisterParameters, false) {}
162006c3fb27SDimitry Andric 
162106c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
162206c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
162306c3fb27SDimitry Andric 
162406c3fb27SDimitry Andric   void getDependentLibraryOption(llvm::StringRef Lib,
162506c3fb27SDimitry Andric                                  llvm::SmallString<24> &Opt) const override {
162606c3fb27SDimitry Andric     Opt = "/DEFAULTLIB:";
162706c3fb27SDimitry Andric     Opt += qualifyWindowsLibrary(Lib);
162806c3fb27SDimitry Andric   }
162906c3fb27SDimitry Andric 
163006c3fb27SDimitry Andric   void getDetectMismatchOption(llvm::StringRef Name,
163106c3fb27SDimitry Andric                                llvm::StringRef Value,
163206c3fb27SDimitry Andric                                llvm::SmallString<32> &Opt) const override {
163306c3fb27SDimitry Andric     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
163406c3fb27SDimitry Andric   }
163506c3fb27SDimitry Andric };
163606c3fb27SDimitry Andric } // namespace
163706c3fb27SDimitry Andric 
163806c3fb27SDimitry Andric void WinX86_32TargetCodeGenInfo::setTargetAttributes(
163906c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
164006c3fb27SDimitry Andric   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
164106c3fb27SDimitry Andric   if (GV->isDeclaration())
164206c3fb27SDimitry Andric     return;
164306c3fb27SDimitry Andric   addStackProbeTargetAttributes(D, GV, CGM);
164406c3fb27SDimitry Andric }
164506c3fb27SDimitry Andric 
164606c3fb27SDimitry Andric namespace {
164706c3fb27SDimitry Andric class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
164806c3fb27SDimitry Andric public:
164906c3fb27SDimitry Andric   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
165006c3fb27SDimitry Andric                              X86AVXABILevel AVXLevel)
165106c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {
165206c3fb27SDimitry Andric     SwiftInfo =
165306c3fb27SDimitry Andric         std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
165406c3fb27SDimitry Andric   }
165506c3fb27SDimitry Andric 
165606c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
165706c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
165806c3fb27SDimitry Andric 
165906c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
166006c3fb27SDimitry Andric     return 7;
166106c3fb27SDimitry Andric   }
166206c3fb27SDimitry Andric 
166306c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
166406c3fb27SDimitry Andric                                llvm::Value *Address) const override {
166506c3fb27SDimitry Andric     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
166606c3fb27SDimitry Andric 
166706c3fb27SDimitry Andric     // 0-15 are the 16 integer registers.
166806c3fb27SDimitry Andric     // 16 is %rip.
166906c3fb27SDimitry Andric     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
167006c3fb27SDimitry Andric     return false;
167106c3fb27SDimitry Andric   }
167206c3fb27SDimitry Andric 
167306c3fb27SDimitry Andric   void getDependentLibraryOption(llvm::StringRef Lib,
167406c3fb27SDimitry Andric                                  llvm::SmallString<24> &Opt) const override {
167506c3fb27SDimitry Andric     Opt = "/DEFAULTLIB:";
167606c3fb27SDimitry Andric     Opt += qualifyWindowsLibrary(Lib);
167706c3fb27SDimitry Andric   }
167806c3fb27SDimitry Andric 
167906c3fb27SDimitry Andric   void getDetectMismatchOption(llvm::StringRef Name,
168006c3fb27SDimitry Andric                                llvm::StringRef Value,
168106c3fb27SDimitry Andric                                llvm::SmallString<32> &Opt) const override {
168206c3fb27SDimitry Andric     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
168306c3fb27SDimitry Andric   }
168406c3fb27SDimitry Andric };
168506c3fb27SDimitry Andric } // namespace
168606c3fb27SDimitry Andric 
168706c3fb27SDimitry Andric void WinX86_64TargetCodeGenInfo::setTargetAttributes(
168806c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
168906c3fb27SDimitry Andric   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
169006c3fb27SDimitry Andric   if (GV->isDeclaration())
169106c3fb27SDimitry Andric     return;
169206c3fb27SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
169306c3fb27SDimitry Andric     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
169406c3fb27SDimitry Andric       llvm::Function *Fn = cast<llvm::Function>(GV);
169506c3fb27SDimitry Andric       Fn->addFnAttr("stackrealign");
169606c3fb27SDimitry Andric     }
169706c3fb27SDimitry Andric 
169806c3fb27SDimitry Andric     addX86InterruptAttrs(FD, GV, CGM);
169906c3fb27SDimitry Andric   }
170006c3fb27SDimitry Andric 
170106c3fb27SDimitry Andric   addStackProbeTargetAttributes(D, GV, CGM);
170206c3fb27SDimitry Andric }
170306c3fb27SDimitry Andric 
170406c3fb27SDimitry Andric void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
170506c3fb27SDimitry Andric                               Class &Hi) const {
170606c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
170706c3fb27SDimitry Andric   //
170806c3fb27SDimitry Andric   // (a) If one of the classes is Memory, the whole argument is passed in
170906c3fb27SDimitry Andric   //     memory.
171006c3fb27SDimitry Andric   //
171106c3fb27SDimitry Andric   // (b) If X87UP is not preceded by X87, the whole argument is passed in
171206c3fb27SDimitry Andric   //     memory.
171306c3fb27SDimitry Andric   //
171406c3fb27SDimitry Andric   // (c) If the size of the aggregate exceeds two eightbytes and the first
171506c3fb27SDimitry Andric   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
171606c3fb27SDimitry Andric   //     argument is passed in memory. NOTE: This is necessary to keep the
171706c3fb27SDimitry Andric   //     ABI working for processors that don't support the __m256 type.
171806c3fb27SDimitry Andric   //
171906c3fb27SDimitry Andric   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
172006c3fb27SDimitry Andric   //
172106c3fb27SDimitry Andric   // Some of these are enforced by the merging logic.  Others can arise
172206c3fb27SDimitry Andric   // only with unions; for example:
172306c3fb27SDimitry Andric   //   union { _Complex double; unsigned; }
172406c3fb27SDimitry Andric   //
172506c3fb27SDimitry Andric   // Note that clauses (b) and (c) were added in 0.98.
172606c3fb27SDimitry Andric   //
172706c3fb27SDimitry Andric   if (Hi == Memory)
172806c3fb27SDimitry Andric     Lo = Memory;
172906c3fb27SDimitry Andric   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
173006c3fb27SDimitry Andric     Lo = Memory;
173106c3fb27SDimitry Andric   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
173206c3fb27SDimitry Andric     Lo = Memory;
173306c3fb27SDimitry Andric   if (Hi == SSEUp && Lo != SSE)
173406c3fb27SDimitry Andric     Hi = SSE;
173506c3fb27SDimitry Andric }
173606c3fb27SDimitry Andric 
173706c3fb27SDimitry Andric X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
173806c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
173906c3fb27SDimitry Andric   // classified recursively so that always two fields are
174006c3fb27SDimitry Andric   // considered. The resulting class is calculated according to
174106c3fb27SDimitry Andric   // the classes of the fields in the eightbyte:
174206c3fb27SDimitry Andric   //
174306c3fb27SDimitry Andric   // (a) If both classes are equal, this is the resulting class.
174406c3fb27SDimitry Andric   //
174506c3fb27SDimitry Andric   // (b) If one of the classes is NO_CLASS, the resulting class is
174606c3fb27SDimitry Andric   // the other class.
174706c3fb27SDimitry Andric   //
174806c3fb27SDimitry Andric   // (c) If one of the classes is MEMORY, the result is the MEMORY
174906c3fb27SDimitry Andric   // class.
175006c3fb27SDimitry Andric   //
175106c3fb27SDimitry Andric   // (d) If one of the classes is INTEGER, the result is the
175206c3fb27SDimitry Andric   // INTEGER.
175306c3fb27SDimitry Andric   //
175406c3fb27SDimitry Andric   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
175506c3fb27SDimitry Andric   // MEMORY is used as class.
175606c3fb27SDimitry Andric   //
175706c3fb27SDimitry Andric   // (f) Otherwise class SSE is used.
175806c3fb27SDimitry Andric 
175906c3fb27SDimitry Andric   // Accum should never be memory (we should have returned) or
176006c3fb27SDimitry Andric   // ComplexX87 (because this cannot be passed in a structure).
176106c3fb27SDimitry Andric   assert((Accum != Memory && Accum != ComplexX87) &&
176206c3fb27SDimitry Andric          "Invalid accumulated classification during merge.");
176306c3fb27SDimitry Andric   if (Accum == Field || Field == NoClass)
176406c3fb27SDimitry Andric     return Accum;
176506c3fb27SDimitry Andric   if (Field == Memory)
176606c3fb27SDimitry Andric     return Memory;
176706c3fb27SDimitry Andric   if (Accum == NoClass)
176806c3fb27SDimitry Andric     return Field;
176906c3fb27SDimitry Andric   if (Accum == Integer || Field == Integer)
177006c3fb27SDimitry Andric     return Integer;
177106c3fb27SDimitry Andric   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
177206c3fb27SDimitry Andric       Accum == X87 || Accum == X87Up)
177306c3fb27SDimitry Andric     return Memory;
177406c3fb27SDimitry Andric   return SSE;
177506c3fb27SDimitry Andric }
177606c3fb27SDimitry Andric 
177706c3fb27SDimitry Andric void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
177806c3fb27SDimitry Andric                              Class &Hi, bool isNamedArg, bool IsRegCall) const {
177906c3fb27SDimitry Andric   // FIXME: This code can be simplified by introducing a simple value class for
178006c3fb27SDimitry Andric   // Class pairs with appropriate constructor methods for the various
178106c3fb27SDimitry Andric   // situations.
178206c3fb27SDimitry Andric 
178306c3fb27SDimitry Andric   // FIXME: Some of the split computations are wrong; unaligned vectors
178406c3fb27SDimitry Andric   // shouldn't be passed in registers for example, so there is no chance they
178506c3fb27SDimitry Andric   // can straddle an eightbyte. Verify & simplify.
178606c3fb27SDimitry Andric 
178706c3fb27SDimitry Andric   Lo = Hi = NoClass;
178806c3fb27SDimitry Andric 
178906c3fb27SDimitry Andric   Class &Current = OffsetBase < 64 ? Lo : Hi;
179006c3fb27SDimitry Andric   Current = Memory;
179106c3fb27SDimitry Andric 
179206c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
179306c3fb27SDimitry Andric     BuiltinType::Kind k = BT->getKind();
179406c3fb27SDimitry Andric 
179506c3fb27SDimitry Andric     if (k == BuiltinType::Void) {
179606c3fb27SDimitry Andric       Current = NoClass;
179706c3fb27SDimitry Andric     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
179806c3fb27SDimitry Andric       Lo = Integer;
179906c3fb27SDimitry Andric       Hi = Integer;
180006c3fb27SDimitry Andric     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
180106c3fb27SDimitry Andric       Current = Integer;
180206c3fb27SDimitry Andric     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
180306c3fb27SDimitry Andric                k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
180406c3fb27SDimitry Andric       Current = SSE;
18051db9f3b2SDimitry Andric     } else if (k == BuiltinType::Float128) {
18061db9f3b2SDimitry Andric       Lo = SSE;
18071db9f3b2SDimitry Andric       Hi = SSEUp;
180806c3fb27SDimitry Andric     } else if (k == BuiltinType::LongDouble) {
180906c3fb27SDimitry Andric       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
181006c3fb27SDimitry Andric       if (LDF == &llvm::APFloat::IEEEquad()) {
181106c3fb27SDimitry Andric         Lo = SSE;
181206c3fb27SDimitry Andric         Hi = SSEUp;
181306c3fb27SDimitry Andric       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
181406c3fb27SDimitry Andric         Lo = X87;
181506c3fb27SDimitry Andric         Hi = X87Up;
181606c3fb27SDimitry Andric       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
181706c3fb27SDimitry Andric         Current = SSE;
181806c3fb27SDimitry Andric       } else
181906c3fb27SDimitry Andric         llvm_unreachable("unexpected long double representation!");
182006c3fb27SDimitry Andric     }
182106c3fb27SDimitry Andric     // FIXME: _Decimal32 and _Decimal64 are SSE.
182206c3fb27SDimitry Andric     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
182306c3fb27SDimitry Andric     return;
182406c3fb27SDimitry Andric   }
182506c3fb27SDimitry Andric 
182606c3fb27SDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>()) {
182706c3fb27SDimitry Andric     // Classify the underlying integer type.
182806c3fb27SDimitry Andric     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
182906c3fb27SDimitry Andric     return;
183006c3fb27SDimitry Andric   }
183106c3fb27SDimitry Andric 
183206c3fb27SDimitry Andric   if (Ty->hasPointerRepresentation()) {
183306c3fb27SDimitry Andric     Current = Integer;
183406c3fb27SDimitry Andric     return;
183506c3fb27SDimitry Andric   }
183606c3fb27SDimitry Andric 
183706c3fb27SDimitry Andric   if (Ty->isMemberPointerType()) {
183806c3fb27SDimitry Andric     if (Ty->isMemberFunctionPointerType()) {
183906c3fb27SDimitry Andric       if (Has64BitPointers) {
184006c3fb27SDimitry Andric         // If Has64BitPointers, this is an {i64, i64}, so classify both
184106c3fb27SDimitry Andric         // Lo and Hi now.
184206c3fb27SDimitry Andric         Lo = Hi = Integer;
184306c3fb27SDimitry Andric       } else {
184406c3fb27SDimitry Andric         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
184506c3fb27SDimitry Andric         // straddles an eightbyte boundary, Hi should be classified as well.
184606c3fb27SDimitry Andric         uint64_t EB_FuncPtr = (OffsetBase) / 64;
184706c3fb27SDimitry Andric         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
184806c3fb27SDimitry Andric         if (EB_FuncPtr != EB_ThisAdj) {
184906c3fb27SDimitry Andric           Lo = Hi = Integer;
185006c3fb27SDimitry Andric         } else {
185106c3fb27SDimitry Andric           Current = Integer;
185206c3fb27SDimitry Andric         }
185306c3fb27SDimitry Andric       }
185406c3fb27SDimitry Andric     } else {
185506c3fb27SDimitry Andric       Current = Integer;
185606c3fb27SDimitry Andric     }
185706c3fb27SDimitry Andric     return;
185806c3fb27SDimitry Andric   }
185906c3fb27SDimitry Andric 
186006c3fb27SDimitry Andric   if (const VectorType *VT = Ty->getAs<VectorType>()) {
186106c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(VT);
186206c3fb27SDimitry Andric     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
186306c3fb27SDimitry Andric       // gcc passes the following as integer:
186406c3fb27SDimitry Andric       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
186506c3fb27SDimitry Andric       // 2 bytes - <2 x char>, <1 x short>
186606c3fb27SDimitry Andric       // 1 byte  - <1 x char>
186706c3fb27SDimitry Andric       Current = Integer;
186806c3fb27SDimitry Andric 
186906c3fb27SDimitry Andric       // If this type crosses an eightbyte boundary, it should be
187006c3fb27SDimitry Andric       // split.
187106c3fb27SDimitry Andric       uint64_t EB_Lo = (OffsetBase) / 64;
187206c3fb27SDimitry Andric       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
187306c3fb27SDimitry Andric       if (EB_Lo != EB_Hi)
187406c3fb27SDimitry Andric         Hi = Lo;
187506c3fb27SDimitry Andric     } else if (Size == 64) {
187606c3fb27SDimitry Andric       QualType ElementType = VT->getElementType();
187706c3fb27SDimitry Andric 
187806c3fb27SDimitry Andric       // gcc passes <1 x double> in memory. :(
187906c3fb27SDimitry Andric       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
188006c3fb27SDimitry Andric         return;
188106c3fb27SDimitry Andric 
188206c3fb27SDimitry Andric       // gcc passes <1 x long long> as SSE but clang used to unconditionally
188306c3fb27SDimitry Andric       // pass them as integer.  For platforms where clang is the de facto
188406c3fb27SDimitry Andric       // platform compiler, we must continue to use integer.
188506c3fb27SDimitry Andric       if (!classifyIntegerMMXAsSSE() &&
188606c3fb27SDimitry Andric           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
188706c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
188806c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
188906c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
189006c3fb27SDimitry Andric         Current = Integer;
189106c3fb27SDimitry Andric       else
189206c3fb27SDimitry Andric         Current = SSE;
189306c3fb27SDimitry Andric 
189406c3fb27SDimitry Andric       // If this type crosses an eightbyte boundary, it should be
189506c3fb27SDimitry Andric       // split.
189606c3fb27SDimitry Andric       if (OffsetBase && OffsetBase != 64)
189706c3fb27SDimitry Andric         Hi = Lo;
189806c3fb27SDimitry Andric     } else if (Size == 128 ||
189906c3fb27SDimitry Andric                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
190006c3fb27SDimitry Andric       QualType ElementType = VT->getElementType();
190106c3fb27SDimitry Andric 
190206c3fb27SDimitry Andric       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
190306c3fb27SDimitry Andric       if (passInt128VectorsInMem() && Size != 128 &&
190406c3fb27SDimitry Andric           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
190506c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
190606c3fb27SDimitry Andric         return;
190706c3fb27SDimitry Andric 
190806c3fb27SDimitry Andric       // Arguments of 256-bits are split into four eightbyte chunks. The
190906c3fb27SDimitry Andric       // least significant one belongs to class SSE and all the others to class
191006c3fb27SDimitry Andric       // SSEUP. The original Lo and Hi design considers that types can't be
191106c3fb27SDimitry Andric       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
191206c3fb27SDimitry Andric       // This design isn't correct for 256-bits, but since there're no cases
191306c3fb27SDimitry Andric       // where the upper parts would need to be inspected, avoid adding
191406c3fb27SDimitry Andric       // complexity and just consider Hi to match the 64-256 part.
191506c3fb27SDimitry Andric       //
191606c3fb27SDimitry Andric       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
191706c3fb27SDimitry Andric       // registers if they are "named", i.e. not part of the "..." of a
191806c3fb27SDimitry Andric       // variadic function.
191906c3fb27SDimitry Andric       //
192006c3fb27SDimitry Andric       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
192106c3fb27SDimitry Andric       // split into eight eightbyte chunks, one SSE and seven SSEUP.
192206c3fb27SDimitry Andric       Lo = SSE;
192306c3fb27SDimitry Andric       Hi = SSEUp;
192406c3fb27SDimitry Andric     }
192506c3fb27SDimitry Andric     return;
192606c3fb27SDimitry Andric   }
192706c3fb27SDimitry Andric 
192806c3fb27SDimitry Andric   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
192906c3fb27SDimitry Andric     QualType ET = getContext().getCanonicalType(CT->getElementType());
193006c3fb27SDimitry Andric 
193106c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
193206c3fb27SDimitry Andric     if (ET->isIntegralOrEnumerationType()) {
193306c3fb27SDimitry Andric       if (Size <= 64)
193406c3fb27SDimitry Andric         Current = Integer;
193506c3fb27SDimitry Andric       else if (Size <= 128)
193606c3fb27SDimitry Andric         Lo = Hi = Integer;
193706c3fb27SDimitry Andric     } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
193806c3fb27SDimitry Andric                ET->isBFloat16Type()) {
193906c3fb27SDimitry Andric       Current = SSE;
194006c3fb27SDimitry Andric     } else if (ET == getContext().DoubleTy) {
194106c3fb27SDimitry Andric       Lo = Hi = SSE;
194206c3fb27SDimitry Andric     } else if (ET == getContext().LongDoubleTy) {
194306c3fb27SDimitry Andric       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
194406c3fb27SDimitry Andric       if (LDF == &llvm::APFloat::IEEEquad())
194506c3fb27SDimitry Andric         Current = Memory;
194606c3fb27SDimitry Andric       else if (LDF == &llvm::APFloat::x87DoubleExtended())
194706c3fb27SDimitry Andric         Current = ComplexX87;
194806c3fb27SDimitry Andric       else if (LDF == &llvm::APFloat::IEEEdouble())
194906c3fb27SDimitry Andric         Lo = Hi = SSE;
195006c3fb27SDimitry Andric       else
195106c3fb27SDimitry Andric         llvm_unreachable("unexpected long double representation!");
195206c3fb27SDimitry Andric     }
195306c3fb27SDimitry Andric 
195406c3fb27SDimitry Andric     // If this complex type crosses an eightbyte boundary then it
195506c3fb27SDimitry Andric     // should be split.
195606c3fb27SDimitry Andric     uint64_t EB_Real = (OffsetBase) / 64;
195706c3fb27SDimitry Andric     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
195806c3fb27SDimitry Andric     if (Hi == NoClass && EB_Real != EB_Imag)
195906c3fb27SDimitry Andric       Hi = Lo;
196006c3fb27SDimitry Andric 
196106c3fb27SDimitry Andric     return;
196206c3fb27SDimitry Andric   }
196306c3fb27SDimitry Andric 
196406c3fb27SDimitry Andric   if (const auto *EITy = Ty->getAs<BitIntType>()) {
196506c3fb27SDimitry Andric     if (EITy->getNumBits() <= 64)
196606c3fb27SDimitry Andric       Current = Integer;
196706c3fb27SDimitry Andric     else if (EITy->getNumBits() <= 128)
196806c3fb27SDimitry Andric       Lo = Hi = Integer;
196906c3fb27SDimitry Andric     // Larger values need to get passed in memory.
197006c3fb27SDimitry Andric     return;
197106c3fb27SDimitry Andric   }
197206c3fb27SDimitry Andric 
197306c3fb27SDimitry Andric   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
197406c3fb27SDimitry Andric     // Arrays are treated like structures.
197506c3fb27SDimitry Andric 
197606c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
197706c3fb27SDimitry Andric 
197806c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
197906c3fb27SDimitry Andric     // than eight eightbytes, ..., it has class MEMORY.
198006c3fb27SDimitry Andric     // regcall ABI doesn't have limitation to an object. The only limitation
198106c3fb27SDimitry Andric     // is the free registers, which will be checked in computeInfo.
198206c3fb27SDimitry Andric     if (!IsRegCall && Size > 512)
198306c3fb27SDimitry Andric       return;
198406c3fb27SDimitry Andric 
198506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
198606c3fb27SDimitry Andric     // fields, it has class MEMORY.
198706c3fb27SDimitry Andric     //
198806c3fb27SDimitry Andric     // Only need to check alignment of array base.
198906c3fb27SDimitry Andric     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
199006c3fb27SDimitry Andric       return;
199106c3fb27SDimitry Andric 
199206c3fb27SDimitry Andric     // Otherwise implement simplified merge. We could be smarter about
199306c3fb27SDimitry Andric     // this, but it isn't worth it and would be harder to verify.
199406c3fb27SDimitry Andric     Current = NoClass;
199506c3fb27SDimitry Andric     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
199606c3fb27SDimitry Andric     uint64_t ArraySize = AT->getSize().getZExtValue();
199706c3fb27SDimitry Andric 
199806c3fb27SDimitry Andric     // The only case a 256-bit wide vector could be used is when the array
199906c3fb27SDimitry Andric     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
200006c3fb27SDimitry Andric     // to work for sizes wider than 128, early check and fallback to memory.
200106c3fb27SDimitry Andric     //
200206c3fb27SDimitry Andric     if (Size > 128 &&
200306c3fb27SDimitry Andric         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
200406c3fb27SDimitry Andric       return;
200506c3fb27SDimitry Andric 
200606c3fb27SDimitry Andric     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
200706c3fb27SDimitry Andric       Class FieldLo, FieldHi;
200806c3fb27SDimitry Andric       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
200906c3fb27SDimitry Andric       Lo = merge(Lo, FieldLo);
201006c3fb27SDimitry Andric       Hi = merge(Hi, FieldHi);
201106c3fb27SDimitry Andric       if (Lo == Memory || Hi == Memory)
201206c3fb27SDimitry Andric         break;
201306c3fb27SDimitry Andric     }
201406c3fb27SDimitry Andric 
201506c3fb27SDimitry Andric     postMerge(Size, Lo, Hi);
201606c3fb27SDimitry Andric     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
201706c3fb27SDimitry Andric     return;
201806c3fb27SDimitry Andric   }
201906c3fb27SDimitry Andric 
202006c3fb27SDimitry Andric   if (const RecordType *RT = Ty->getAs<RecordType>()) {
202106c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
202206c3fb27SDimitry Andric 
202306c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
202406c3fb27SDimitry Andric     // than eight eightbytes, ..., it has class MEMORY.
202506c3fb27SDimitry Andric     if (Size > 512)
202606c3fb27SDimitry Andric       return;
202706c3fb27SDimitry Andric 
202806c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
202906c3fb27SDimitry Andric     // copy constructor or a non-trivial destructor, it is passed by invisible
203006c3fb27SDimitry Andric     // reference.
203106c3fb27SDimitry Andric     if (getRecordArgABI(RT, getCXXABI()))
203206c3fb27SDimitry Andric       return;
203306c3fb27SDimitry Andric 
203406c3fb27SDimitry Andric     const RecordDecl *RD = RT->getDecl();
203506c3fb27SDimitry Andric 
203606c3fb27SDimitry Andric     // Assume variable sized types are passed in memory.
203706c3fb27SDimitry Andric     if (RD->hasFlexibleArrayMember())
203806c3fb27SDimitry Andric       return;
203906c3fb27SDimitry Andric 
204006c3fb27SDimitry Andric     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
204106c3fb27SDimitry Andric 
204206c3fb27SDimitry Andric     // Reset Lo class, this will be recomputed.
204306c3fb27SDimitry Andric     Current = NoClass;
204406c3fb27SDimitry Andric 
204506c3fb27SDimitry Andric     // If this is a C++ record, classify the bases first.
204606c3fb27SDimitry Andric     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
204706c3fb27SDimitry Andric       for (const auto &I : CXXRD->bases()) {
204806c3fb27SDimitry Andric         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
204906c3fb27SDimitry Andric                "Unexpected base class!");
205006c3fb27SDimitry Andric         const auto *Base =
205106c3fb27SDimitry Andric             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
205206c3fb27SDimitry Andric 
205306c3fb27SDimitry Andric         // Classify this field.
205406c3fb27SDimitry Andric         //
205506c3fb27SDimitry Andric         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
205606c3fb27SDimitry Andric         // single eightbyte, each is classified separately. Each eightbyte gets
205706c3fb27SDimitry Andric         // initialized to class NO_CLASS.
205806c3fb27SDimitry Andric         Class FieldLo, FieldHi;
205906c3fb27SDimitry Andric         uint64_t Offset =
206006c3fb27SDimitry Andric           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
206106c3fb27SDimitry Andric         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
206206c3fb27SDimitry Andric         Lo = merge(Lo, FieldLo);
206306c3fb27SDimitry Andric         Hi = merge(Hi, FieldHi);
206406c3fb27SDimitry Andric         if (Lo == Memory || Hi == Memory) {
206506c3fb27SDimitry Andric           postMerge(Size, Lo, Hi);
206606c3fb27SDimitry Andric           return;
206706c3fb27SDimitry Andric         }
206806c3fb27SDimitry Andric       }
206906c3fb27SDimitry Andric     }
207006c3fb27SDimitry Andric 
207106c3fb27SDimitry Andric     // Classify the fields one at a time, merging the results.
207206c3fb27SDimitry Andric     unsigned idx = 0;
207306c3fb27SDimitry Andric     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
207406c3fb27SDimitry Andric                                 LangOptions::ClangABI::Ver11 ||
207506c3fb27SDimitry Andric                             getContext().getTargetInfo().getTriple().isPS();
207606c3fb27SDimitry Andric     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
207706c3fb27SDimitry Andric 
207806c3fb27SDimitry Andric     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
207906c3fb27SDimitry Andric            i != e; ++i, ++idx) {
208006c3fb27SDimitry Andric       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
208106c3fb27SDimitry Andric       bool BitField = i->isBitField();
208206c3fb27SDimitry Andric 
208306c3fb27SDimitry Andric       // Ignore padding bit-fields.
208406c3fb27SDimitry Andric       if (BitField && i->isUnnamedBitfield())
208506c3fb27SDimitry Andric         continue;
208606c3fb27SDimitry Andric 
208706c3fb27SDimitry Andric       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
208806c3fb27SDimitry Andric       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
208906c3fb27SDimitry Andric       //
209006c3fb27SDimitry Andric       // The only case a 256-bit or a 512-bit wide vector could be used is when
209106c3fb27SDimitry Andric       // the struct contains a single 256-bit or 512-bit element. Early check
209206c3fb27SDimitry Andric       // and fallback to memory.
209306c3fb27SDimitry Andric       //
209406c3fb27SDimitry Andric       // FIXME: Extended the Lo and Hi logic properly to work for size wider
209506c3fb27SDimitry Andric       // than 128.
209606c3fb27SDimitry Andric       if (Size > 128 &&
209706c3fb27SDimitry Andric           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
209806c3fb27SDimitry Andric            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
209906c3fb27SDimitry Andric         Lo = Memory;
210006c3fb27SDimitry Andric         postMerge(Size, Lo, Hi);
210106c3fb27SDimitry Andric         return;
210206c3fb27SDimitry Andric       }
210306c3fb27SDimitry Andric       // Note, skip this test for bit-fields, see below.
210406c3fb27SDimitry Andric       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
210506c3fb27SDimitry Andric         Lo = Memory;
210606c3fb27SDimitry Andric         postMerge(Size, Lo, Hi);
210706c3fb27SDimitry Andric         return;
210806c3fb27SDimitry Andric       }
210906c3fb27SDimitry Andric 
211006c3fb27SDimitry Andric       // Classify this field.
211106c3fb27SDimitry Andric       //
211206c3fb27SDimitry Andric       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
211306c3fb27SDimitry Andric       // exceeds a single eightbyte, each is classified
211406c3fb27SDimitry Andric       // separately. Each eightbyte gets initialized to class
211506c3fb27SDimitry Andric       // NO_CLASS.
211606c3fb27SDimitry Andric       Class FieldLo, FieldHi;
211706c3fb27SDimitry Andric 
211806c3fb27SDimitry Andric       // Bit-fields require special handling, they do not force the
211906c3fb27SDimitry Andric       // structure to be passed in memory even if unaligned, and
212006c3fb27SDimitry Andric       // therefore they can straddle an eightbyte.
212106c3fb27SDimitry Andric       if (BitField) {
212206c3fb27SDimitry Andric         assert(!i->isUnnamedBitfield());
212306c3fb27SDimitry Andric         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
212406c3fb27SDimitry Andric         uint64_t Size = i->getBitWidthValue(getContext());
212506c3fb27SDimitry Andric 
212606c3fb27SDimitry Andric         uint64_t EB_Lo = Offset / 64;
212706c3fb27SDimitry Andric         uint64_t EB_Hi = (Offset + Size - 1) / 64;
212806c3fb27SDimitry Andric 
212906c3fb27SDimitry Andric         if (EB_Lo) {
213006c3fb27SDimitry Andric           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
213106c3fb27SDimitry Andric           FieldLo = NoClass;
213206c3fb27SDimitry Andric           FieldHi = Integer;
213306c3fb27SDimitry Andric         } else {
213406c3fb27SDimitry Andric           FieldLo = Integer;
213506c3fb27SDimitry Andric           FieldHi = EB_Hi ? Integer : NoClass;
213606c3fb27SDimitry Andric         }
213706c3fb27SDimitry Andric       } else
213806c3fb27SDimitry Andric         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
213906c3fb27SDimitry Andric       Lo = merge(Lo, FieldLo);
214006c3fb27SDimitry Andric       Hi = merge(Hi, FieldHi);
214106c3fb27SDimitry Andric       if (Lo == Memory || Hi == Memory)
214206c3fb27SDimitry Andric         break;
214306c3fb27SDimitry Andric     }
214406c3fb27SDimitry Andric 
214506c3fb27SDimitry Andric     postMerge(Size, Lo, Hi);
214606c3fb27SDimitry Andric   }
214706c3fb27SDimitry Andric }
214806c3fb27SDimitry Andric 
214906c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
215006c3fb27SDimitry Andric   // If this is a scalar LLVM value then assume LLVM will pass it in the right
215106c3fb27SDimitry Andric   // place naturally.
215206c3fb27SDimitry Andric   if (!isAggregateTypeForABI(Ty)) {
215306c3fb27SDimitry Andric     // Treat an enum type as its underlying type.
215406c3fb27SDimitry Andric     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
215506c3fb27SDimitry Andric       Ty = EnumTy->getDecl()->getIntegerType();
215606c3fb27SDimitry Andric 
215706c3fb27SDimitry Andric     if (Ty->isBitIntType())
215806c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty);
215906c3fb27SDimitry Andric 
216006c3fb27SDimitry Andric     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
216106c3fb27SDimitry Andric                                               : ABIArgInfo::getDirect());
216206c3fb27SDimitry Andric   }
216306c3fb27SDimitry Andric 
216406c3fb27SDimitry Andric   return getNaturalAlignIndirect(Ty);
216506c3fb27SDimitry Andric }
216606c3fb27SDimitry Andric 
216706c3fb27SDimitry Andric bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
216806c3fb27SDimitry Andric   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
216906c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(VecTy);
217006c3fb27SDimitry Andric     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
217106c3fb27SDimitry Andric     if (Size <= 64 || Size > LargestVector)
217206c3fb27SDimitry Andric       return true;
217306c3fb27SDimitry Andric     QualType EltTy = VecTy->getElementType();
217406c3fb27SDimitry Andric     if (passInt128VectorsInMem() &&
217506c3fb27SDimitry Andric         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
217606c3fb27SDimitry Andric          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
217706c3fb27SDimitry Andric       return true;
217806c3fb27SDimitry Andric   }
217906c3fb27SDimitry Andric 
218006c3fb27SDimitry Andric   return false;
218106c3fb27SDimitry Andric }
218206c3fb27SDimitry Andric 
218306c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
218406c3fb27SDimitry Andric                                             unsigned freeIntRegs) const {
218506c3fb27SDimitry Andric   // If this is a scalar LLVM value then assume LLVM will pass it in the right
218606c3fb27SDimitry Andric   // place naturally.
218706c3fb27SDimitry Andric   //
218806c3fb27SDimitry Andric   // This assumption is optimistic, as there could be free registers available
218906c3fb27SDimitry Andric   // when we need to pass this argument in memory, and LLVM could try to pass
219006c3fb27SDimitry Andric   // the argument in the free register. This does not seem to happen currently,
219106c3fb27SDimitry Andric   // but this code would be much safer if we could mark the argument with
219206c3fb27SDimitry Andric   // 'onstack'. See PR12193.
219306c3fb27SDimitry Andric   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
219406c3fb27SDimitry Andric       !Ty->isBitIntType()) {
219506c3fb27SDimitry Andric     // Treat an enum type as its underlying type.
219606c3fb27SDimitry Andric     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
219706c3fb27SDimitry Andric       Ty = EnumTy->getDecl()->getIntegerType();
219806c3fb27SDimitry Andric 
219906c3fb27SDimitry Andric     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
220006c3fb27SDimitry Andric                                               : ABIArgInfo::getDirect());
220106c3fb27SDimitry Andric   }
220206c3fb27SDimitry Andric 
220306c3fb27SDimitry Andric   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
220406c3fb27SDimitry Andric     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
220506c3fb27SDimitry Andric 
220606c3fb27SDimitry Andric   // Compute the byval alignment. We specify the alignment of the byval in all
220706c3fb27SDimitry Andric   // cases so that the mid-level optimizer knows the alignment of the byval.
220806c3fb27SDimitry Andric   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
220906c3fb27SDimitry Andric 
221006c3fb27SDimitry Andric   // Attempt to avoid passing indirect results using byval when possible. This
221106c3fb27SDimitry Andric   // is important for good codegen.
221206c3fb27SDimitry Andric   //
221306c3fb27SDimitry Andric   // We do this by coercing the value into a scalar type which the backend can
221406c3fb27SDimitry Andric   // handle naturally (i.e., without using byval).
221506c3fb27SDimitry Andric   //
221606c3fb27SDimitry Andric   // For simplicity, we currently only do this when we have exhausted all of the
221706c3fb27SDimitry Andric   // free integer registers. Doing this when there are free integer registers
221806c3fb27SDimitry Andric   // would require more care, as we would have to ensure that the coerced value
221906c3fb27SDimitry Andric   // did not claim the unused register. That would require either reording the
222006c3fb27SDimitry Andric   // arguments to the function (so that any subsequent inreg values came first),
222106c3fb27SDimitry Andric   // or only doing this optimization when there were no following arguments that
222206c3fb27SDimitry Andric   // might be inreg.
222306c3fb27SDimitry Andric   //
222406c3fb27SDimitry Andric   // We currently expect it to be rare (particularly in well written code) for
222506c3fb27SDimitry Andric   // arguments to be passed on the stack when there are still free integer
222606c3fb27SDimitry Andric   // registers available (this would typically imply large structs being passed
222706c3fb27SDimitry Andric   // by value), so this seems like a fair tradeoff for now.
222806c3fb27SDimitry Andric   //
222906c3fb27SDimitry Andric   // We can revisit this if the backend grows support for 'onstack' parameter
223006c3fb27SDimitry Andric   // attributes. See PR12193.
223106c3fb27SDimitry Andric   if (freeIntRegs == 0) {
223206c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
223306c3fb27SDimitry Andric 
223406c3fb27SDimitry Andric     // If this type fits in an eightbyte, coerce it into the matching integral
223506c3fb27SDimitry Andric     // type, which will end up on the stack (with alignment 8).
223606c3fb27SDimitry Andric     if (Align == 8 && Size <= 64)
223706c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
223806c3fb27SDimitry Andric                                                           Size));
223906c3fb27SDimitry Andric   }
224006c3fb27SDimitry Andric 
224106c3fb27SDimitry Andric   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
224206c3fb27SDimitry Andric }
224306c3fb27SDimitry Andric 
224406c3fb27SDimitry Andric /// The ABI specifies that a value should be passed in a full vector XMM/YMM
224506c3fb27SDimitry Andric /// register. Pick an LLVM IR type that will be passed as a vector register.
224606c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
224706c3fb27SDimitry Andric   // Wrapper structs/arrays that only contain vectors are passed just like
224806c3fb27SDimitry Andric   // vectors; strip them off if present.
224906c3fb27SDimitry Andric   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
225006c3fb27SDimitry Andric     Ty = QualType(InnerTy, 0);
225106c3fb27SDimitry Andric 
225206c3fb27SDimitry Andric   llvm::Type *IRType = CGT.ConvertType(Ty);
225306c3fb27SDimitry Andric   if (isa<llvm::VectorType>(IRType)) {
225406c3fb27SDimitry Andric     // Don't pass vXi128 vectors in their native type, the backend can't
225506c3fb27SDimitry Andric     // legalize them.
225606c3fb27SDimitry Andric     if (passInt128VectorsInMem() &&
225706c3fb27SDimitry Andric         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
225806c3fb27SDimitry Andric       // Use a vXi64 vector.
225906c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(Ty);
226006c3fb27SDimitry Andric       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
226106c3fb27SDimitry Andric                                         Size / 64);
226206c3fb27SDimitry Andric     }
226306c3fb27SDimitry Andric 
226406c3fb27SDimitry Andric     return IRType;
226506c3fb27SDimitry Andric   }
226606c3fb27SDimitry Andric 
226706c3fb27SDimitry Andric   if (IRType->getTypeID() == llvm::Type::FP128TyID)
226806c3fb27SDimitry Andric     return IRType;
226906c3fb27SDimitry Andric 
227006c3fb27SDimitry Andric   // We couldn't find the preferred IR vector type for 'Ty'.
227106c3fb27SDimitry Andric   uint64_t Size = getContext().getTypeSize(Ty);
227206c3fb27SDimitry Andric   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
227306c3fb27SDimitry Andric 
227406c3fb27SDimitry Andric 
227506c3fb27SDimitry Andric   // Return a LLVM IR vector type based on the size of 'Ty'.
227606c3fb27SDimitry Andric   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
227706c3fb27SDimitry Andric                                     Size / 64);
227806c3fb27SDimitry Andric }
227906c3fb27SDimitry Andric 
228006c3fb27SDimitry Andric /// BitsContainNoUserData - Return true if the specified [start,end) bit range
228106c3fb27SDimitry Andric /// is known to either be off the end of the specified type or being in
228206c3fb27SDimitry Andric /// alignment padding.  The user type specified is known to be at most 128 bits
228306c3fb27SDimitry Andric /// in size, and have passed through X86_64ABIInfo::classify with a successful
228406c3fb27SDimitry Andric /// classification that put one of the two halves in the INTEGER class.
228506c3fb27SDimitry Andric ///
228606c3fb27SDimitry Andric /// It is conservatively correct to return false.
228706c3fb27SDimitry Andric static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
228806c3fb27SDimitry Andric                                   unsigned EndBit, ASTContext &Context) {
228906c3fb27SDimitry Andric   // If the bytes being queried are off the end of the type, there is no user
229006c3fb27SDimitry Andric   // data hiding here.  This handles analysis of builtins, vectors and other
229106c3fb27SDimitry Andric   // types that don't contain interesting padding.
229206c3fb27SDimitry Andric   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
229306c3fb27SDimitry Andric   if (TySize <= StartBit)
229406c3fb27SDimitry Andric     return true;
229506c3fb27SDimitry Andric 
229606c3fb27SDimitry Andric   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
229706c3fb27SDimitry Andric     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
229806c3fb27SDimitry Andric     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
229906c3fb27SDimitry Andric 
230006c3fb27SDimitry Andric     // Check each element to see if the element overlaps with the queried range.
230106c3fb27SDimitry Andric     for (unsigned i = 0; i != NumElts; ++i) {
230206c3fb27SDimitry Andric       // If the element is after the span we care about, then we're done..
230306c3fb27SDimitry Andric       unsigned EltOffset = i*EltSize;
230406c3fb27SDimitry Andric       if (EltOffset >= EndBit) break;
230506c3fb27SDimitry Andric 
230606c3fb27SDimitry Andric       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
230706c3fb27SDimitry Andric       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
230806c3fb27SDimitry Andric                                  EndBit-EltOffset, Context))
230906c3fb27SDimitry Andric         return false;
231006c3fb27SDimitry Andric     }
231106c3fb27SDimitry Andric     // If it overlaps no elements, then it is safe to process as padding.
231206c3fb27SDimitry Andric     return true;
231306c3fb27SDimitry Andric   }
231406c3fb27SDimitry Andric 
231506c3fb27SDimitry Andric   if (const RecordType *RT = Ty->getAs<RecordType>()) {
231606c3fb27SDimitry Andric     const RecordDecl *RD = RT->getDecl();
231706c3fb27SDimitry Andric     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
231806c3fb27SDimitry Andric 
231906c3fb27SDimitry Andric     // If this is a C++ record, check the bases first.
232006c3fb27SDimitry Andric     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
232106c3fb27SDimitry Andric       for (const auto &I : CXXRD->bases()) {
232206c3fb27SDimitry Andric         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
232306c3fb27SDimitry Andric                "Unexpected base class!");
232406c3fb27SDimitry Andric         const auto *Base =
232506c3fb27SDimitry Andric             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
232606c3fb27SDimitry Andric 
232706c3fb27SDimitry Andric         // If the base is after the span we care about, ignore it.
232806c3fb27SDimitry Andric         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
232906c3fb27SDimitry Andric         if (BaseOffset >= EndBit) continue;
233006c3fb27SDimitry Andric 
233106c3fb27SDimitry Andric         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
233206c3fb27SDimitry Andric         if (!BitsContainNoUserData(I.getType(), BaseStart,
233306c3fb27SDimitry Andric                                    EndBit-BaseOffset, Context))
233406c3fb27SDimitry Andric           return false;
233506c3fb27SDimitry Andric       }
233606c3fb27SDimitry Andric     }
233706c3fb27SDimitry Andric 
233806c3fb27SDimitry Andric     // Verify that no field has data that overlaps the region of interest.  Yes
233906c3fb27SDimitry Andric     // this could be sped up a lot by being smarter about queried fields,
234006c3fb27SDimitry Andric     // however we're only looking at structs up to 16 bytes, so we don't care
234106c3fb27SDimitry Andric     // much.
234206c3fb27SDimitry Andric     unsigned idx = 0;
234306c3fb27SDimitry Andric     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
234406c3fb27SDimitry Andric          i != e; ++i, ++idx) {
234506c3fb27SDimitry Andric       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
234606c3fb27SDimitry Andric 
234706c3fb27SDimitry Andric       // If we found a field after the region we care about, then we're done.
234806c3fb27SDimitry Andric       if (FieldOffset >= EndBit) break;
234906c3fb27SDimitry Andric 
235006c3fb27SDimitry Andric       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
235106c3fb27SDimitry Andric       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
235206c3fb27SDimitry Andric                                  Context))
235306c3fb27SDimitry Andric         return false;
235406c3fb27SDimitry Andric     }
235506c3fb27SDimitry Andric 
235606c3fb27SDimitry Andric     // If nothing in this record overlapped the area of interest, then we're
235706c3fb27SDimitry Andric     // clean.
235806c3fb27SDimitry Andric     return true;
235906c3fb27SDimitry Andric   }
236006c3fb27SDimitry Andric 
236106c3fb27SDimitry Andric   return false;
236206c3fb27SDimitry Andric }
236306c3fb27SDimitry Andric 
236406c3fb27SDimitry Andric /// getFPTypeAtOffset - Return a floating point type at the specified offset.
236506c3fb27SDimitry Andric static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
236606c3fb27SDimitry Andric                                      const llvm::DataLayout &TD) {
236706c3fb27SDimitry Andric   if (IROffset == 0 && IRType->isFloatingPointTy())
236806c3fb27SDimitry Andric     return IRType;
236906c3fb27SDimitry Andric 
237006c3fb27SDimitry Andric   // If this is a struct, recurse into the field at the specified offset.
237106c3fb27SDimitry Andric   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
237206c3fb27SDimitry Andric     if (!STy->getNumContainedTypes())
237306c3fb27SDimitry Andric       return nullptr;
237406c3fb27SDimitry Andric 
237506c3fb27SDimitry Andric     const llvm::StructLayout *SL = TD.getStructLayout(STy);
237606c3fb27SDimitry Andric     unsigned Elt = SL->getElementContainingOffset(IROffset);
237706c3fb27SDimitry Andric     IROffset -= SL->getElementOffset(Elt);
237806c3fb27SDimitry Andric     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
237906c3fb27SDimitry Andric   }
238006c3fb27SDimitry Andric 
238106c3fb27SDimitry Andric   // If this is an array, recurse into the field at the specified offset.
238206c3fb27SDimitry Andric   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
238306c3fb27SDimitry Andric     llvm::Type *EltTy = ATy->getElementType();
238406c3fb27SDimitry Andric     unsigned EltSize = TD.getTypeAllocSize(EltTy);
238506c3fb27SDimitry Andric     IROffset -= IROffset / EltSize * EltSize;
238606c3fb27SDimitry Andric     return getFPTypeAtOffset(EltTy, IROffset, TD);
238706c3fb27SDimitry Andric   }
238806c3fb27SDimitry Andric 
238906c3fb27SDimitry Andric   return nullptr;
239006c3fb27SDimitry Andric }
239106c3fb27SDimitry Andric 
239206c3fb27SDimitry Andric /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
239306c3fb27SDimitry Andric /// low 8 bytes of an XMM register, corresponding to the SSE class.
239406c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::
239506c3fb27SDimitry Andric GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
239606c3fb27SDimitry Andric                    QualType SourceTy, unsigned SourceOffset) const {
239706c3fb27SDimitry Andric   const llvm::DataLayout &TD = getDataLayout();
239806c3fb27SDimitry Andric   unsigned SourceSize =
239906c3fb27SDimitry Andric       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
240006c3fb27SDimitry Andric   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
240106c3fb27SDimitry Andric   if (!T0 || T0->isDoubleTy())
240206c3fb27SDimitry Andric     return llvm::Type::getDoubleTy(getVMContext());
240306c3fb27SDimitry Andric 
240406c3fb27SDimitry Andric   // Get the adjacent FP type.
240506c3fb27SDimitry Andric   llvm::Type *T1 = nullptr;
240606c3fb27SDimitry Andric   unsigned T0Size = TD.getTypeAllocSize(T0);
240706c3fb27SDimitry Andric   if (SourceSize > T0Size)
240806c3fb27SDimitry Andric       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
240906c3fb27SDimitry Andric   if (T1 == nullptr) {
241006c3fb27SDimitry Andric     // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
241106c3fb27SDimitry Andric     // to its alignment.
241206c3fb27SDimitry Andric     if (T0->is16bitFPTy() && SourceSize > 4)
241306c3fb27SDimitry Andric       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
241406c3fb27SDimitry Andric     // If we can't get a second FP type, return a simple half or float.
241506c3fb27SDimitry Andric     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
241606c3fb27SDimitry Andric     // {float, i8} too.
241706c3fb27SDimitry Andric     if (T1 == nullptr)
241806c3fb27SDimitry Andric       return T0;
241906c3fb27SDimitry Andric   }
242006c3fb27SDimitry Andric 
242106c3fb27SDimitry Andric   if (T0->isFloatTy() && T1->isFloatTy())
242206c3fb27SDimitry Andric     return llvm::FixedVectorType::get(T0, 2);
242306c3fb27SDimitry Andric 
242406c3fb27SDimitry Andric   if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
242506c3fb27SDimitry Andric     llvm::Type *T2 = nullptr;
242606c3fb27SDimitry Andric     if (SourceSize > 4)
242706c3fb27SDimitry Andric       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
242806c3fb27SDimitry Andric     if (T2 == nullptr)
242906c3fb27SDimitry Andric       return llvm::FixedVectorType::get(T0, 2);
243006c3fb27SDimitry Andric     return llvm::FixedVectorType::get(T0, 4);
243106c3fb27SDimitry Andric   }
243206c3fb27SDimitry Andric 
243306c3fb27SDimitry Andric   if (T0->is16bitFPTy() || T1->is16bitFPTy())
243406c3fb27SDimitry Andric     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
243506c3fb27SDimitry Andric 
243606c3fb27SDimitry Andric   return llvm::Type::getDoubleTy(getVMContext());
243706c3fb27SDimitry Andric }
243806c3fb27SDimitry Andric 
243906c3fb27SDimitry Andric 
244006c3fb27SDimitry Andric /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
244106c3fb27SDimitry Andric /// an 8-byte GPR.  This means that we either have a scalar or we are talking
244206c3fb27SDimitry Andric /// about the high or low part of an up-to-16-byte struct.  This routine picks
244306c3fb27SDimitry Andric /// the best LLVM IR type to represent this, which may be i64 or may be anything
244406c3fb27SDimitry Andric /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
244506c3fb27SDimitry Andric /// etc).
244606c3fb27SDimitry Andric ///
244706c3fb27SDimitry Andric /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
244806c3fb27SDimitry Andric /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
244906c3fb27SDimitry Andric /// the 8-byte value references.  PrefType may be null.
245006c3fb27SDimitry Andric ///
245106c3fb27SDimitry Andric /// SourceTy is the source-level type for the entire argument.  SourceOffset is
245206c3fb27SDimitry Andric /// an offset into this that we're processing (which is always either 0 or 8).
245306c3fb27SDimitry Andric ///
245406c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::
245506c3fb27SDimitry Andric GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
245606c3fb27SDimitry Andric                        QualType SourceTy, unsigned SourceOffset) const {
245706c3fb27SDimitry Andric   // If we're dealing with an un-offset LLVM IR type, then it means that we're
245806c3fb27SDimitry Andric   // returning an 8-byte unit starting with it.  See if we can safely use it.
245906c3fb27SDimitry Andric   if (IROffset == 0) {
246006c3fb27SDimitry Andric     // Pointers and int64's always fill the 8-byte unit.
246106c3fb27SDimitry Andric     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
246206c3fb27SDimitry Andric         IRType->isIntegerTy(64))
246306c3fb27SDimitry Andric       return IRType;
246406c3fb27SDimitry Andric 
246506c3fb27SDimitry Andric     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
246606c3fb27SDimitry Andric     // goodness in the source type is just tail padding.  This is allowed to
246706c3fb27SDimitry Andric     // kick in for struct {double,int} on the int, but not on
246806c3fb27SDimitry Andric     // struct{double,int,int} because we wouldn't return the second int.  We
246906c3fb27SDimitry Andric     // have to do this analysis on the source type because we can't depend on
247006c3fb27SDimitry Andric     // unions being lowered a specific way etc.
247106c3fb27SDimitry Andric     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
247206c3fb27SDimitry Andric         IRType->isIntegerTy(32) ||
247306c3fb27SDimitry Andric         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
247406c3fb27SDimitry Andric       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
247506c3fb27SDimitry Andric           cast<llvm::IntegerType>(IRType)->getBitWidth();
247606c3fb27SDimitry Andric 
247706c3fb27SDimitry Andric       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
247806c3fb27SDimitry Andric                                 SourceOffset*8+64, getContext()))
247906c3fb27SDimitry Andric         return IRType;
248006c3fb27SDimitry Andric     }
248106c3fb27SDimitry Andric   }
248206c3fb27SDimitry Andric 
248306c3fb27SDimitry Andric   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
248406c3fb27SDimitry Andric     // If this is a struct, recurse into the field at the specified offset.
248506c3fb27SDimitry Andric     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
248606c3fb27SDimitry Andric     if (IROffset < SL->getSizeInBytes()) {
248706c3fb27SDimitry Andric       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
248806c3fb27SDimitry Andric       IROffset -= SL->getElementOffset(FieldIdx);
248906c3fb27SDimitry Andric 
249006c3fb27SDimitry Andric       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
249106c3fb27SDimitry Andric                                     SourceTy, SourceOffset);
249206c3fb27SDimitry Andric     }
249306c3fb27SDimitry Andric   }
249406c3fb27SDimitry Andric 
249506c3fb27SDimitry Andric   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
249606c3fb27SDimitry Andric     llvm::Type *EltTy = ATy->getElementType();
249706c3fb27SDimitry Andric     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
249806c3fb27SDimitry Andric     unsigned EltOffset = IROffset/EltSize*EltSize;
249906c3fb27SDimitry Andric     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
250006c3fb27SDimitry Andric                                   SourceOffset);
250106c3fb27SDimitry Andric   }
250206c3fb27SDimitry Andric 
250306c3fb27SDimitry Andric   // Okay, we don't have any better idea of what to pass, so we pass this in an
250406c3fb27SDimitry Andric   // integer register that isn't too big to fit the rest of the struct.
250506c3fb27SDimitry Andric   unsigned TySizeInBytes =
250606c3fb27SDimitry Andric     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
250706c3fb27SDimitry Andric 
250806c3fb27SDimitry Andric   assert(TySizeInBytes != SourceOffset && "Empty field?");
250906c3fb27SDimitry Andric 
251006c3fb27SDimitry Andric   // It is always safe to classify this as an integer type up to i64 that
251106c3fb27SDimitry Andric   // isn't larger than the structure.
251206c3fb27SDimitry Andric   return llvm::IntegerType::get(getVMContext(),
251306c3fb27SDimitry Andric                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
251406c3fb27SDimitry Andric }
251506c3fb27SDimitry Andric 
251606c3fb27SDimitry Andric 
251706c3fb27SDimitry Andric /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
251806c3fb27SDimitry Andric /// be used as elements of a two register pair to pass or return, return a
251906c3fb27SDimitry Andric /// first class aggregate to represent them.  For example, if the low part of
252006c3fb27SDimitry Andric /// a by-value argument should be passed as i32* and the high part as float,
252106c3fb27SDimitry Andric /// return {i32*, float}.
252206c3fb27SDimitry Andric static llvm::Type *
252306c3fb27SDimitry Andric GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
252406c3fb27SDimitry Andric                            const llvm::DataLayout &TD) {
252506c3fb27SDimitry Andric   // In order to correctly satisfy the ABI, we need to the high part to start
252606c3fb27SDimitry Andric   // at offset 8.  If the high and low parts we inferred are both 4-byte types
252706c3fb27SDimitry Andric   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
252806c3fb27SDimitry Andric   // the second element at offset 8.  Check for this:
252906c3fb27SDimitry Andric   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
253006c3fb27SDimitry Andric   llvm::Align HiAlign = TD.getABITypeAlign(Hi);
253106c3fb27SDimitry Andric   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
253206c3fb27SDimitry Andric   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
253306c3fb27SDimitry Andric 
253406c3fb27SDimitry Andric   // To handle this, we have to increase the size of the low part so that the
253506c3fb27SDimitry Andric   // second element will start at an 8 byte offset.  We can't increase the size
253606c3fb27SDimitry Andric   // of the second element because it might make us access off the end of the
253706c3fb27SDimitry Andric   // struct.
253806c3fb27SDimitry Andric   if (HiStart != 8) {
253906c3fb27SDimitry Andric     // There are usually two sorts of types the ABI generation code can produce
254006c3fb27SDimitry Andric     // for the low part of a pair that aren't 8 bytes in size: half, float or
254106c3fb27SDimitry Andric     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
254206c3fb27SDimitry Andric     // NaCl).
254306c3fb27SDimitry Andric     // Promote these to a larger type.
254406c3fb27SDimitry Andric     if (Lo->isHalfTy() || Lo->isFloatTy())
254506c3fb27SDimitry Andric       Lo = llvm::Type::getDoubleTy(Lo->getContext());
254606c3fb27SDimitry Andric     else {
254706c3fb27SDimitry Andric       assert((Lo->isIntegerTy() || Lo->isPointerTy())
254806c3fb27SDimitry Andric              && "Invalid/unknown lo type");
254906c3fb27SDimitry Andric       Lo = llvm::Type::getInt64Ty(Lo->getContext());
255006c3fb27SDimitry Andric     }
255106c3fb27SDimitry Andric   }
255206c3fb27SDimitry Andric 
255306c3fb27SDimitry Andric   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
255406c3fb27SDimitry Andric 
255506c3fb27SDimitry Andric   // Verify that the second element is at an 8-byte offset.
255606c3fb27SDimitry Andric   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
255706c3fb27SDimitry Andric          "Invalid x86-64 argument pair!");
255806c3fb27SDimitry Andric   return Result;
255906c3fb27SDimitry Andric }
256006c3fb27SDimitry Andric 
256106c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::
256206c3fb27SDimitry Andric classifyReturnType(QualType RetTy) const {
256306c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
256406c3fb27SDimitry Andric   // classification algorithm.
256506c3fb27SDimitry Andric   X86_64ABIInfo::Class Lo, Hi;
256606c3fb27SDimitry Andric   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
256706c3fb27SDimitry Andric 
256806c3fb27SDimitry Andric   // Check some invariants.
256906c3fb27SDimitry Andric   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
257006c3fb27SDimitry Andric   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
257106c3fb27SDimitry Andric 
257206c3fb27SDimitry Andric   llvm::Type *ResType = nullptr;
257306c3fb27SDimitry Andric   switch (Lo) {
257406c3fb27SDimitry Andric   case NoClass:
257506c3fb27SDimitry Andric     if (Hi == NoClass)
257606c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
257706c3fb27SDimitry Andric     // If the low part is just padding, it takes no register, leave ResType
257806c3fb27SDimitry Andric     // null.
257906c3fb27SDimitry Andric     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
258006c3fb27SDimitry Andric            "Unknown missing lo part");
258106c3fb27SDimitry Andric     break;
258206c3fb27SDimitry Andric 
258306c3fb27SDimitry Andric   case SSEUp:
258406c3fb27SDimitry Andric   case X87Up:
258506c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for lo word.");
258606c3fb27SDimitry Andric 
258706c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
258806c3fb27SDimitry Andric     // hidden argument.
258906c3fb27SDimitry Andric   case Memory:
259006c3fb27SDimitry Andric     return getIndirectReturnResult(RetTy);
259106c3fb27SDimitry Andric 
259206c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
259306c3fb27SDimitry Andric     // available register of the sequence %rax, %rdx is used.
259406c3fb27SDimitry Andric   case Integer:
259506c3fb27SDimitry Andric     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
259606c3fb27SDimitry Andric 
259706c3fb27SDimitry Andric     // If we have a sign or zero extended integer, make sure to return Extend
259806c3fb27SDimitry Andric     // so that the parameter gets the right LLVM IR attributes.
259906c3fb27SDimitry Andric     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
260006c3fb27SDimitry Andric       // Treat an enum type as its underlying type.
260106c3fb27SDimitry Andric       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
260206c3fb27SDimitry Andric         RetTy = EnumTy->getDecl()->getIntegerType();
260306c3fb27SDimitry Andric 
260406c3fb27SDimitry Andric       if (RetTy->isIntegralOrEnumerationType() &&
260506c3fb27SDimitry Andric           isPromotableIntegerTypeForABI(RetTy))
260606c3fb27SDimitry Andric         return ABIArgInfo::getExtend(RetTy);
260706c3fb27SDimitry Andric     }
260806c3fb27SDimitry Andric     break;
260906c3fb27SDimitry Andric 
261006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
261106c3fb27SDimitry Andric     // available SSE register of the sequence %xmm0, %xmm1 is used.
261206c3fb27SDimitry Andric   case SSE:
261306c3fb27SDimitry Andric     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
261406c3fb27SDimitry Andric     break;
261506c3fb27SDimitry Andric 
261606c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
261706c3fb27SDimitry Andric     // returned on the X87 stack in %st0 as 80-bit x87 number.
261806c3fb27SDimitry Andric   case X87:
261906c3fb27SDimitry Andric     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
262006c3fb27SDimitry Andric     break;
262106c3fb27SDimitry Andric 
262206c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
262306c3fb27SDimitry Andric     // part of the value is returned in %st0 and the imaginary part in
262406c3fb27SDimitry Andric     // %st1.
262506c3fb27SDimitry Andric   case ComplexX87:
262606c3fb27SDimitry Andric     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
262706c3fb27SDimitry Andric     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
262806c3fb27SDimitry Andric                                     llvm::Type::getX86_FP80Ty(getVMContext()));
262906c3fb27SDimitry Andric     break;
263006c3fb27SDimitry Andric   }
263106c3fb27SDimitry Andric 
263206c3fb27SDimitry Andric   llvm::Type *HighPart = nullptr;
263306c3fb27SDimitry Andric   switch (Hi) {
263406c3fb27SDimitry Andric     // Memory was handled previously and X87 should
263506c3fb27SDimitry Andric     // never occur as a hi class.
263606c3fb27SDimitry Andric   case Memory:
263706c3fb27SDimitry Andric   case X87:
263806c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for hi word.");
263906c3fb27SDimitry Andric 
264006c3fb27SDimitry Andric   case ComplexX87: // Previously handled.
264106c3fb27SDimitry Andric   case NoClass:
264206c3fb27SDimitry Andric     break;
264306c3fb27SDimitry Andric 
264406c3fb27SDimitry Andric   case Integer:
264506c3fb27SDimitry Andric     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
264606c3fb27SDimitry Andric     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
264706c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
264806c3fb27SDimitry Andric     break;
264906c3fb27SDimitry Andric   case SSE:
265006c3fb27SDimitry Andric     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
265106c3fb27SDimitry Andric     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
265206c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
265306c3fb27SDimitry Andric     break;
265406c3fb27SDimitry Andric 
265506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
265606c3fb27SDimitry Andric     // is passed in the next available eightbyte chunk if the last used
265706c3fb27SDimitry Andric     // vector register.
265806c3fb27SDimitry Andric     //
265906c3fb27SDimitry Andric     // SSEUP should always be preceded by SSE, just widen.
266006c3fb27SDimitry Andric   case SSEUp:
266106c3fb27SDimitry Andric     assert(Lo == SSE && "Unexpected SSEUp classification.");
266206c3fb27SDimitry Andric     ResType = GetByteVectorType(RetTy);
266306c3fb27SDimitry Andric     break;
266406c3fb27SDimitry Andric 
266506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
266606c3fb27SDimitry Andric     // returned together with the previous X87 value in %st0.
266706c3fb27SDimitry Andric   case X87Up:
266806c3fb27SDimitry Andric     // If X87Up is preceded by X87, we don't need to do
266906c3fb27SDimitry Andric     // anything. However, in some cases with unions it may not be
267006c3fb27SDimitry Andric     // preceded by X87. In such situations we follow gcc and pass the
267106c3fb27SDimitry Andric     // extra bits in an SSE reg.
267206c3fb27SDimitry Andric     if (Lo != X87) {
267306c3fb27SDimitry Andric       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
267406c3fb27SDimitry Andric       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
267506c3fb27SDimitry Andric         return ABIArgInfo::getDirect(HighPart, 8);
267606c3fb27SDimitry Andric     }
267706c3fb27SDimitry Andric     break;
267806c3fb27SDimitry Andric   }
267906c3fb27SDimitry Andric 
268006c3fb27SDimitry Andric   // If a high part was specified, merge it together with the low part.  It is
268106c3fb27SDimitry Andric   // known to pass in the high eightbyte of the result.  We do this by forming a
268206c3fb27SDimitry Andric   // first class struct aggregate with the high and low part: {low, high}
268306c3fb27SDimitry Andric   if (HighPart)
268406c3fb27SDimitry Andric     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
268506c3fb27SDimitry Andric 
268606c3fb27SDimitry Andric   return ABIArgInfo::getDirect(ResType);
268706c3fb27SDimitry Andric }
268806c3fb27SDimitry Andric 
268906c3fb27SDimitry Andric ABIArgInfo
269006c3fb27SDimitry Andric X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
269106c3fb27SDimitry Andric                                     unsigned &neededInt, unsigned &neededSSE,
269206c3fb27SDimitry Andric                                     bool isNamedArg, bool IsRegCall) const {
269306c3fb27SDimitry Andric   Ty = useFirstFieldIfTransparentUnion(Ty);
269406c3fb27SDimitry Andric 
269506c3fb27SDimitry Andric   X86_64ABIInfo::Class Lo, Hi;
269606c3fb27SDimitry Andric   classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
269706c3fb27SDimitry Andric 
269806c3fb27SDimitry Andric   // Check some invariants.
269906c3fb27SDimitry Andric   // FIXME: Enforce these by construction.
270006c3fb27SDimitry Andric   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
270106c3fb27SDimitry Andric   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
270206c3fb27SDimitry Andric 
270306c3fb27SDimitry Andric   neededInt = 0;
270406c3fb27SDimitry Andric   neededSSE = 0;
270506c3fb27SDimitry Andric   llvm::Type *ResType = nullptr;
270606c3fb27SDimitry Andric   switch (Lo) {
270706c3fb27SDimitry Andric   case NoClass:
270806c3fb27SDimitry Andric     if (Hi == NoClass)
270906c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
271006c3fb27SDimitry Andric     // If the low part is just padding, it takes no register, leave ResType
271106c3fb27SDimitry Andric     // null.
271206c3fb27SDimitry Andric     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
271306c3fb27SDimitry Andric            "Unknown missing lo part");
271406c3fb27SDimitry Andric     break;
271506c3fb27SDimitry Andric 
271606c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
271706c3fb27SDimitry Andric     // on the stack.
271806c3fb27SDimitry Andric   case Memory:
271906c3fb27SDimitry Andric 
272006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
272106c3fb27SDimitry Andric     // COMPLEX_X87, it is passed in memory.
272206c3fb27SDimitry Andric   case X87:
272306c3fb27SDimitry Andric   case ComplexX87:
272406c3fb27SDimitry Andric     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
272506c3fb27SDimitry Andric       ++neededInt;
272606c3fb27SDimitry Andric     return getIndirectResult(Ty, freeIntRegs);
272706c3fb27SDimitry Andric 
272806c3fb27SDimitry Andric   case SSEUp:
272906c3fb27SDimitry Andric   case X87Up:
273006c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for lo word.");
273106c3fb27SDimitry Andric 
273206c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
273306c3fb27SDimitry Andric     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
273406c3fb27SDimitry Andric     // and %r9 is used.
273506c3fb27SDimitry Andric   case Integer:
273606c3fb27SDimitry Andric     ++neededInt;
273706c3fb27SDimitry Andric 
273806c3fb27SDimitry Andric     // Pick an 8-byte type based on the preferred type.
273906c3fb27SDimitry Andric     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
274006c3fb27SDimitry Andric 
274106c3fb27SDimitry Andric     // If we have a sign or zero extended integer, make sure to return Extend
274206c3fb27SDimitry Andric     // so that the parameter gets the right LLVM IR attributes.
274306c3fb27SDimitry Andric     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
274406c3fb27SDimitry Andric       // Treat an enum type as its underlying type.
274506c3fb27SDimitry Andric       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
274606c3fb27SDimitry Andric         Ty = EnumTy->getDecl()->getIntegerType();
274706c3fb27SDimitry Andric 
274806c3fb27SDimitry Andric       if (Ty->isIntegralOrEnumerationType() &&
274906c3fb27SDimitry Andric           isPromotableIntegerTypeForABI(Ty))
275006c3fb27SDimitry Andric         return ABIArgInfo::getExtend(Ty);
275106c3fb27SDimitry Andric     }
275206c3fb27SDimitry Andric 
275306c3fb27SDimitry Andric     break;
275406c3fb27SDimitry Andric 
275506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
275606c3fb27SDimitry Andric     // available SSE register is used, the registers are taken in the
275706c3fb27SDimitry Andric     // order from %xmm0 to %xmm7.
275806c3fb27SDimitry Andric   case SSE: {
275906c3fb27SDimitry Andric     llvm::Type *IRType = CGT.ConvertType(Ty);
276006c3fb27SDimitry Andric     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
276106c3fb27SDimitry Andric     ++neededSSE;
276206c3fb27SDimitry Andric     break;
276306c3fb27SDimitry Andric   }
276406c3fb27SDimitry Andric   }
276506c3fb27SDimitry Andric 
276606c3fb27SDimitry Andric   llvm::Type *HighPart = nullptr;
276706c3fb27SDimitry Andric   switch (Hi) {
276806c3fb27SDimitry Andric     // Memory was handled previously, ComplexX87 and X87 should
276906c3fb27SDimitry Andric     // never occur as hi classes, and X87Up must be preceded by X87,
277006c3fb27SDimitry Andric     // which is passed in memory.
277106c3fb27SDimitry Andric   case Memory:
277206c3fb27SDimitry Andric   case X87:
277306c3fb27SDimitry Andric   case ComplexX87:
277406c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for hi word.");
277506c3fb27SDimitry Andric 
277606c3fb27SDimitry Andric   case NoClass: break;
277706c3fb27SDimitry Andric 
277806c3fb27SDimitry Andric   case Integer:
277906c3fb27SDimitry Andric     ++neededInt;
278006c3fb27SDimitry Andric     // Pick an 8-byte type based on the preferred type.
278106c3fb27SDimitry Andric     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
278206c3fb27SDimitry Andric 
278306c3fb27SDimitry Andric     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
278406c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
278506c3fb27SDimitry Andric     break;
278606c3fb27SDimitry Andric 
278706c3fb27SDimitry Andric     // X87Up generally doesn't occur here (long double is passed in
278806c3fb27SDimitry Andric     // memory), except in situations involving unions.
278906c3fb27SDimitry Andric   case X87Up:
279006c3fb27SDimitry Andric   case SSE:
279106c3fb27SDimitry Andric     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
279206c3fb27SDimitry Andric 
279306c3fb27SDimitry Andric     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
279406c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
279506c3fb27SDimitry Andric 
279606c3fb27SDimitry Andric     ++neededSSE;
279706c3fb27SDimitry Andric     break;
279806c3fb27SDimitry Andric 
279906c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
280006c3fb27SDimitry Andric     // eightbyte is passed in the upper half of the last used SSE
280106c3fb27SDimitry Andric     // register.  This only happens when 128-bit vectors are passed.
280206c3fb27SDimitry Andric   case SSEUp:
280306c3fb27SDimitry Andric     assert(Lo == SSE && "Unexpected SSEUp classification");
280406c3fb27SDimitry Andric     ResType = GetByteVectorType(Ty);
280506c3fb27SDimitry Andric     break;
280606c3fb27SDimitry Andric   }
280706c3fb27SDimitry Andric 
280806c3fb27SDimitry Andric   // If a high part was specified, merge it together with the low part.  It is
280906c3fb27SDimitry Andric   // known to pass in the high eightbyte of the result.  We do this by forming a
281006c3fb27SDimitry Andric   // first class struct aggregate with the high and low part: {low, high}
281106c3fb27SDimitry Andric   if (HighPart)
281206c3fb27SDimitry Andric     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
281306c3fb27SDimitry Andric 
281406c3fb27SDimitry Andric   return ABIArgInfo::getDirect(ResType);
281506c3fb27SDimitry Andric }
281606c3fb27SDimitry Andric 
281706c3fb27SDimitry Andric ABIArgInfo
281806c3fb27SDimitry Andric X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
281906c3fb27SDimitry Andric                                              unsigned &NeededSSE,
282006c3fb27SDimitry Andric                                              unsigned &MaxVectorWidth) const {
282106c3fb27SDimitry Andric   auto RT = Ty->getAs<RecordType>();
282206c3fb27SDimitry Andric   assert(RT && "classifyRegCallStructType only valid with struct types");
282306c3fb27SDimitry Andric 
282406c3fb27SDimitry Andric   if (RT->getDecl()->hasFlexibleArrayMember())
282506c3fb27SDimitry Andric     return getIndirectReturnResult(Ty);
282606c3fb27SDimitry Andric 
282706c3fb27SDimitry Andric   // Sum up bases
282806c3fb27SDimitry Andric   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
282906c3fb27SDimitry Andric     if (CXXRD->isDynamicClass()) {
283006c3fb27SDimitry Andric       NeededInt = NeededSSE = 0;
283106c3fb27SDimitry Andric       return getIndirectReturnResult(Ty);
283206c3fb27SDimitry Andric     }
283306c3fb27SDimitry Andric 
283406c3fb27SDimitry Andric     for (const auto &I : CXXRD->bases())
283506c3fb27SDimitry Andric       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
283606c3fb27SDimitry Andric                                         MaxVectorWidth)
283706c3fb27SDimitry Andric               .isIndirect()) {
283806c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
283906c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
284006c3fb27SDimitry Andric       }
284106c3fb27SDimitry Andric   }
284206c3fb27SDimitry Andric 
284306c3fb27SDimitry Andric   // Sum up members
284406c3fb27SDimitry Andric   for (const auto *FD : RT->getDecl()->fields()) {
284506c3fb27SDimitry Andric     QualType MTy = FD->getType();
284606c3fb27SDimitry Andric     if (MTy->isRecordType() && !MTy->isUnionType()) {
284706c3fb27SDimitry Andric       if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
284806c3fb27SDimitry Andric                                         MaxVectorWidth)
284906c3fb27SDimitry Andric               .isIndirect()) {
285006c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
285106c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
285206c3fb27SDimitry Andric       }
285306c3fb27SDimitry Andric     } else {
285406c3fb27SDimitry Andric       unsigned LocalNeededInt, LocalNeededSSE;
285506c3fb27SDimitry Andric       if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
285606c3fb27SDimitry Andric                                true, true)
285706c3fb27SDimitry Andric               .isIndirect()) {
285806c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
285906c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
286006c3fb27SDimitry Andric       }
286106c3fb27SDimitry Andric       if (const auto *AT = getContext().getAsConstantArrayType(MTy))
286206c3fb27SDimitry Andric         MTy = AT->getElementType();
286306c3fb27SDimitry Andric       if (const auto *VT = MTy->getAs<VectorType>())
286406c3fb27SDimitry Andric         if (getContext().getTypeSize(VT) > MaxVectorWidth)
286506c3fb27SDimitry Andric           MaxVectorWidth = getContext().getTypeSize(VT);
286606c3fb27SDimitry Andric       NeededInt += LocalNeededInt;
286706c3fb27SDimitry Andric       NeededSSE += LocalNeededSSE;
286806c3fb27SDimitry Andric     }
286906c3fb27SDimitry Andric   }
287006c3fb27SDimitry Andric 
287106c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
287206c3fb27SDimitry Andric }
287306c3fb27SDimitry Andric 
287406c3fb27SDimitry Andric ABIArgInfo
287506c3fb27SDimitry Andric X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
287606c3fb27SDimitry Andric                                          unsigned &NeededSSE,
287706c3fb27SDimitry Andric                                          unsigned &MaxVectorWidth) const {
287806c3fb27SDimitry Andric 
287906c3fb27SDimitry Andric   NeededInt = 0;
288006c3fb27SDimitry Andric   NeededSSE = 0;
288106c3fb27SDimitry Andric   MaxVectorWidth = 0;
288206c3fb27SDimitry Andric 
288306c3fb27SDimitry Andric   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
288406c3fb27SDimitry Andric                                        MaxVectorWidth);
288506c3fb27SDimitry Andric }
288606c3fb27SDimitry Andric 
288706c3fb27SDimitry Andric void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
288806c3fb27SDimitry Andric 
288906c3fb27SDimitry Andric   const unsigned CallingConv = FI.getCallingConvention();
289006c3fb27SDimitry Andric   // It is possible to force Win64 calling convention on any x86_64 target by
289106c3fb27SDimitry Andric   // using __attribute__((ms_abi)). In such case to correctly emit Win64
289206c3fb27SDimitry Andric   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
289306c3fb27SDimitry Andric   if (CallingConv == llvm::CallingConv::Win64) {
289406c3fb27SDimitry Andric     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
289506c3fb27SDimitry Andric     Win64ABIInfo.computeInfo(FI);
289606c3fb27SDimitry Andric     return;
289706c3fb27SDimitry Andric   }
289806c3fb27SDimitry Andric 
289906c3fb27SDimitry Andric   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
290006c3fb27SDimitry Andric 
290106c3fb27SDimitry Andric   // Keep track of the number of assigned registers.
290206c3fb27SDimitry Andric   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
290306c3fb27SDimitry Andric   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
290406c3fb27SDimitry Andric   unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
290506c3fb27SDimitry Andric 
290606c3fb27SDimitry Andric   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
290706c3fb27SDimitry Andric     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
290806c3fb27SDimitry Andric         !FI.getReturnType()->getTypePtr()->isUnionType()) {
290906c3fb27SDimitry Andric       FI.getReturnInfo() = classifyRegCallStructType(
291006c3fb27SDimitry Andric           FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
291106c3fb27SDimitry Andric       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
291206c3fb27SDimitry Andric         FreeIntRegs -= NeededInt;
291306c3fb27SDimitry Andric         FreeSSERegs -= NeededSSE;
291406c3fb27SDimitry Andric       } else {
291506c3fb27SDimitry Andric         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
291606c3fb27SDimitry Andric       }
291706c3fb27SDimitry Andric     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
291806c3fb27SDimitry Andric                getContext().getCanonicalType(FI.getReturnType()
291906c3fb27SDimitry Andric                                                  ->getAs<ComplexType>()
292006c3fb27SDimitry Andric                                                  ->getElementType()) ==
292106c3fb27SDimitry Andric                    getContext().LongDoubleTy)
292206c3fb27SDimitry Andric       // Complex Long Double Type is passed in Memory when Regcall
292306c3fb27SDimitry Andric       // calling convention is used.
292406c3fb27SDimitry Andric       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
292506c3fb27SDimitry Andric     else
292606c3fb27SDimitry Andric       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
292706c3fb27SDimitry Andric   }
292806c3fb27SDimitry Andric 
292906c3fb27SDimitry Andric   // If the return value is indirect, then the hidden argument is consuming one
293006c3fb27SDimitry Andric   // integer register.
293106c3fb27SDimitry Andric   if (FI.getReturnInfo().isIndirect())
293206c3fb27SDimitry Andric     --FreeIntRegs;
293306c3fb27SDimitry Andric   else if (NeededSSE && MaxVectorWidth > 0)
293406c3fb27SDimitry Andric     FI.setMaxVectorWidth(MaxVectorWidth);
293506c3fb27SDimitry Andric 
293606c3fb27SDimitry Andric   // The chain argument effectively gives us another free register.
293706c3fb27SDimitry Andric   if (FI.isChainCall())
293806c3fb27SDimitry Andric     ++FreeIntRegs;
293906c3fb27SDimitry Andric 
294006c3fb27SDimitry Andric   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
294106c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
294206c3fb27SDimitry Andric   // get assigned (in left-to-right order) for passing as follows...
294306c3fb27SDimitry Andric   unsigned ArgNo = 0;
294406c3fb27SDimitry Andric   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
294506c3fb27SDimitry Andric        it != ie; ++it, ++ArgNo) {
294606c3fb27SDimitry Andric     bool IsNamedArg = ArgNo < NumRequiredArgs;
294706c3fb27SDimitry Andric 
294806c3fb27SDimitry Andric     if (IsRegCall && it->type->isStructureOrClassType())
294906c3fb27SDimitry Andric       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
295006c3fb27SDimitry Andric                                            MaxVectorWidth);
295106c3fb27SDimitry Andric     else
295206c3fb27SDimitry Andric       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
295306c3fb27SDimitry Andric                                       NeededSSE, IsNamedArg);
295406c3fb27SDimitry Andric 
295506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: If there are no registers available for any
295606c3fb27SDimitry Andric     // eightbyte of an argument, the whole argument is passed on the
295706c3fb27SDimitry Andric     // stack. If registers have already been assigned for some
295806c3fb27SDimitry Andric     // eightbytes of such an argument, the assignments get reverted.
295906c3fb27SDimitry Andric     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
296006c3fb27SDimitry Andric       FreeIntRegs -= NeededInt;
296106c3fb27SDimitry Andric       FreeSSERegs -= NeededSSE;
296206c3fb27SDimitry Andric       if (MaxVectorWidth > FI.getMaxVectorWidth())
296306c3fb27SDimitry Andric         FI.setMaxVectorWidth(MaxVectorWidth);
296406c3fb27SDimitry Andric     } else {
296506c3fb27SDimitry Andric       it->info = getIndirectResult(it->type, FreeIntRegs);
296606c3fb27SDimitry Andric     }
296706c3fb27SDimitry Andric   }
296806c3fb27SDimitry Andric }
296906c3fb27SDimitry Andric 
297006c3fb27SDimitry Andric static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
297106c3fb27SDimitry Andric                                          Address VAListAddr, QualType Ty) {
297206c3fb27SDimitry Andric   Address overflow_arg_area_p =
297306c3fb27SDimitry Andric       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
297406c3fb27SDimitry Andric   llvm::Value *overflow_arg_area =
297506c3fb27SDimitry Andric     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
297606c3fb27SDimitry Andric 
297706c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
297806c3fb27SDimitry Andric   // byte boundary if alignment needed by type exceeds 8 byte boundary.
297906c3fb27SDimitry Andric   // It isn't stated explicitly in the standard, but in practice we use
298006c3fb27SDimitry Andric   // alignment greater than 16 where necessary.
298106c3fb27SDimitry Andric   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
298206c3fb27SDimitry Andric   if (Align > CharUnits::fromQuantity(8)) {
298306c3fb27SDimitry Andric     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
298406c3fb27SDimitry Andric                                                       Align);
298506c3fb27SDimitry Andric   }
298606c3fb27SDimitry Andric 
298706c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
298806c3fb27SDimitry Andric   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
29895f757f3fSDimitry Andric   llvm::Value *Res = overflow_arg_area;
299006c3fb27SDimitry Andric 
299106c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
299206c3fb27SDimitry Andric   // l->overflow_arg_area + sizeof(type).
299306c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
299406c3fb27SDimitry Andric   // an 8 byte boundary.
299506c3fb27SDimitry Andric 
299606c3fb27SDimitry Andric   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
299706c3fb27SDimitry Andric   llvm::Value *Offset =
299806c3fb27SDimitry Andric       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
299906c3fb27SDimitry Andric   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
300006c3fb27SDimitry Andric                                             Offset, "overflow_arg_area.next");
300106c3fb27SDimitry Andric   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
300206c3fb27SDimitry Andric 
300306c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
300406c3fb27SDimitry Andric   return Address(Res, LTy, Align);
300506c3fb27SDimitry Andric }
300606c3fb27SDimitry Andric 
300706c3fb27SDimitry Andric Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
300806c3fb27SDimitry Andric                                  QualType Ty) const {
300906c3fb27SDimitry Andric   // Assume that va_list type is correct; should be pointer to LLVM type:
301006c3fb27SDimitry Andric   // struct {
301106c3fb27SDimitry Andric   //   i32 gp_offset;
301206c3fb27SDimitry Andric   //   i32 fp_offset;
301306c3fb27SDimitry Andric   //   i8* overflow_arg_area;
301406c3fb27SDimitry Andric   //   i8* reg_save_area;
301506c3fb27SDimitry Andric   // };
301606c3fb27SDimitry Andric   unsigned neededInt, neededSSE;
301706c3fb27SDimitry Andric 
301806c3fb27SDimitry Andric   Ty = getContext().getCanonicalType(Ty);
301906c3fb27SDimitry Andric   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
302006c3fb27SDimitry Andric                                        /*isNamedArg*/false);
302106c3fb27SDimitry Andric 
302206c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
302306c3fb27SDimitry Andric   // in the registers. If not go to step 7.
302406c3fb27SDimitry Andric   if (!neededInt && !neededSSE)
302506c3fb27SDimitry Andric     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
302606c3fb27SDimitry Andric 
302706c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
302806c3fb27SDimitry Andric   // general purpose registers needed to pass type and num_fp to hold
302906c3fb27SDimitry Andric   // the number of floating point registers needed.
303006c3fb27SDimitry Andric 
303106c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
303206c3fb27SDimitry Andric   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
303306c3fb27SDimitry Andric   // l->fp_offset > 304 - num_fp * 16 go to step 7.
303406c3fb27SDimitry Andric   //
303506c3fb27SDimitry Andric   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
303606c3fb27SDimitry Andric   // register save space).
303706c3fb27SDimitry Andric 
303806c3fb27SDimitry Andric   llvm::Value *InRegs = nullptr;
303906c3fb27SDimitry Andric   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
304006c3fb27SDimitry Andric   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
304106c3fb27SDimitry Andric   if (neededInt) {
304206c3fb27SDimitry Andric     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
304306c3fb27SDimitry Andric     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
304406c3fb27SDimitry Andric     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
304506c3fb27SDimitry Andric     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
304606c3fb27SDimitry Andric   }
304706c3fb27SDimitry Andric 
304806c3fb27SDimitry Andric   if (neededSSE) {
304906c3fb27SDimitry Andric     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
305006c3fb27SDimitry Andric     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
305106c3fb27SDimitry Andric     llvm::Value *FitsInFP =
305206c3fb27SDimitry Andric       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
305306c3fb27SDimitry Andric     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
305406c3fb27SDimitry Andric     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
305506c3fb27SDimitry Andric   }
305606c3fb27SDimitry Andric 
305706c3fb27SDimitry Andric   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
305806c3fb27SDimitry Andric   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
305906c3fb27SDimitry Andric   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
306006c3fb27SDimitry Andric   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
306106c3fb27SDimitry Andric 
306206c3fb27SDimitry Andric   // Emit code to load the value if it was passed in registers.
306306c3fb27SDimitry Andric 
306406c3fb27SDimitry Andric   CGF.EmitBlock(InRegBlock);
306506c3fb27SDimitry Andric 
306606c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
306706c3fb27SDimitry Andric   // an offset of l->gp_offset and/or l->fp_offset. This may require
306806c3fb27SDimitry Andric   // copying to a temporary location in case the parameter is passed
306906c3fb27SDimitry Andric   // in different register classes or requires an alignment greater
307006c3fb27SDimitry Andric   // than 8 for general purpose registers and 16 for XMM registers.
307106c3fb27SDimitry Andric   //
307206c3fb27SDimitry Andric   // FIXME: This really results in shameful code when we end up needing to
307306c3fb27SDimitry Andric   // collect arguments from different places; often what should result in a
307406c3fb27SDimitry Andric   // simple assembling of a structure from scattered addresses has many more
307506c3fb27SDimitry Andric   // loads than necessary. Can we clean this up?
307606c3fb27SDimitry Andric   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
307706c3fb27SDimitry Andric   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
307806c3fb27SDimitry Andric       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
307906c3fb27SDimitry Andric 
308006c3fb27SDimitry Andric   Address RegAddr = Address::invalid();
308106c3fb27SDimitry Andric   if (neededInt && neededSSE) {
308206c3fb27SDimitry Andric     // FIXME: Cleanup.
308306c3fb27SDimitry Andric     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
308406c3fb27SDimitry Andric     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
308506c3fb27SDimitry Andric     Address Tmp = CGF.CreateMemTemp(Ty);
308606c3fb27SDimitry Andric     Tmp = Tmp.withElementType(ST);
308706c3fb27SDimitry Andric     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
308806c3fb27SDimitry Andric     llvm::Type *TyLo = ST->getElementType(0);
308906c3fb27SDimitry Andric     llvm::Type *TyHi = ST->getElementType(1);
309006c3fb27SDimitry Andric     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
309106c3fb27SDimitry Andric            "Unexpected ABI info for mixed regs");
309206c3fb27SDimitry Andric     llvm::Value *GPAddr =
309306c3fb27SDimitry Andric         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
309406c3fb27SDimitry Andric     llvm::Value *FPAddr =
309506c3fb27SDimitry Andric         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
309606c3fb27SDimitry Andric     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
309706c3fb27SDimitry Andric     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
309806c3fb27SDimitry Andric 
309906c3fb27SDimitry Andric     // Copy the first element.
310006c3fb27SDimitry Andric     // FIXME: Our choice of alignment here and below is probably pessimistic.
310106c3fb27SDimitry Andric     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
31025f757f3fSDimitry Andric         TyLo, RegLoAddr,
310306c3fb27SDimitry Andric         CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyLo)));
310406c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
310506c3fb27SDimitry Andric 
310606c3fb27SDimitry Andric     // Copy the second element.
310706c3fb27SDimitry Andric     V = CGF.Builder.CreateAlignedLoad(
31085f757f3fSDimitry Andric         TyHi, RegHiAddr,
310906c3fb27SDimitry Andric         CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
311006c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
311106c3fb27SDimitry Andric 
311206c3fb27SDimitry Andric     RegAddr = Tmp.withElementType(LTy);
311306c3fb27SDimitry Andric   } else if (neededInt) {
311406c3fb27SDimitry Andric     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
311506c3fb27SDimitry Andric                       LTy, CharUnits::fromQuantity(8));
311606c3fb27SDimitry Andric 
311706c3fb27SDimitry Andric     // Copy to a temporary if necessary to ensure the appropriate alignment.
311806c3fb27SDimitry Andric     auto TInfo = getContext().getTypeInfoInChars(Ty);
311906c3fb27SDimitry Andric     uint64_t TySize = TInfo.Width.getQuantity();
312006c3fb27SDimitry Andric     CharUnits TyAlign = TInfo.Align;
312106c3fb27SDimitry Andric 
312206c3fb27SDimitry Andric     // Copy into a temporary if the type is more aligned than the
312306c3fb27SDimitry Andric     // register save area.
312406c3fb27SDimitry Andric     if (TyAlign.getQuantity() > 8) {
312506c3fb27SDimitry Andric       Address Tmp = CGF.CreateMemTemp(Ty);
312606c3fb27SDimitry Andric       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
312706c3fb27SDimitry Andric       RegAddr = Tmp;
312806c3fb27SDimitry Andric     }
312906c3fb27SDimitry Andric 
313006c3fb27SDimitry Andric   } else if (neededSSE == 1) {
313106c3fb27SDimitry Andric     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
313206c3fb27SDimitry Andric                       LTy, CharUnits::fromQuantity(16));
313306c3fb27SDimitry Andric   } else {
313406c3fb27SDimitry Andric     assert(neededSSE == 2 && "Invalid number of needed registers!");
313506c3fb27SDimitry Andric     // SSE registers are spaced 16 bytes apart in the register save
313606c3fb27SDimitry Andric     // area, we need to collect the two eightbytes together.
313706c3fb27SDimitry Andric     // The ABI isn't explicit about this, but it seems reasonable
313806c3fb27SDimitry Andric     // to assume that the slots are 16-byte aligned, since the stack is
313906c3fb27SDimitry Andric     // naturally 16-byte aligned and the prologue is expected to store
314006c3fb27SDimitry Andric     // all the SSE registers to the RSA.
314106c3fb27SDimitry Andric     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
314206c3fb27SDimitry Andric                                                       fp_offset),
314306c3fb27SDimitry Andric                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
314406c3fb27SDimitry Andric     Address RegAddrHi =
314506c3fb27SDimitry Andric       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
314606c3fb27SDimitry Andric                                              CharUnits::fromQuantity(16));
314706c3fb27SDimitry Andric     llvm::Type *ST = AI.canHaveCoerceToType()
314806c3fb27SDimitry Andric                          ? AI.getCoerceToType()
314906c3fb27SDimitry Andric                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
315006c3fb27SDimitry Andric     llvm::Value *V;
315106c3fb27SDimitry Andric     Address Tmp = CGF.CreateMemTemp(Ty);
315206c3fb27SDimitry Andric     Tmp = Tmp.withElementType(ST);
315306c3fb27SDimitry Andric     V = CGF.Builder.CreateLoad(
315406c3fb27SDimitry Andric         RegAddrLo.withElementType(ST->getStructElementType(0)));
315506c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
315606c3fb27SDimitry Andric     V = CGF.Builder.CreateLoad(
315706c3fb27SDimitry Andric         RegAddrHi.withElementType(ST->getStructElementType(1)));
315806c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
315906c3fb27SDimitry Andric 
316006c3fb27SDimitry Andric     RegAddr = Tmp.withElementType(LTy);
316106c3fb27SDimitry Andric   }
316206c3fb27SDimitry Andric 
316306c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 5. Set:
316406c3fb27SDimitry Andric   // l->gp_offset = l->gp_offset + num_gp * 8
316506c3fb27SDimitry Andric   // l->fp_offset = l->fp_offset + num_fp * 16.
316606c3fb27SDimitry Andric   if (neededInt) {
316706c3fb27SDimitry Andric     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
316806c3fb27SDimitry Andric     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
316906c3fb27SDimitry Andric                             gp_offset_p);
317006c3fb27SDimitry Andric   }
317106c3fb27SDimitry Andric   if (neededSSE) {
317206c3fb27SDimitry Andric     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
317306c3fb27SDimitry Andric     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
317406c3fb27SDimitry Andric                             fp_offset_p);
317506c3fb27SDimitry Andric   }
317606c3fb27SDimitry Andric   CGF.EmitBranch(ContBlock);
317706c3fb27SDimitry Andric 
317806c3fb27SDimitry Andric   // Emit code to load the value if it was passed in memory.
317906c3fb27SDimitry Andric 
318006c3fb27SDimitry Andric   CGF.EmitBlock(InMemBlock);
318106c3fb27SDimitry Andric   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
318206c3fb27SDimitry Andric 
318306c3fb27SDimitry Andric   // Return the appropriate result.
318406c3fb27SDimitry Andric 
318506c3fb27SDimitry Andric   CGF.EmitBlock(ContBlock);
318606c3fb27SDimitry Andric   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
318706c3fb27SDimitry Andric                                  "vaarg.addr");
318806c3fb27SDimitry Andric   return ResAddr;
318906c3fb27SDimitry Andric }
319006c3fb27SDimitry Andric 
319106c3fb27SDimitry Andric Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
319206c3fb27SDimitry Andric                                    QualType Ty) const {
319306c3fb27SDimitry Andric   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
319406c3fb27SDimitry Andric   // not 1, 2, 4, or 8 bytes, must be passed by reference."
319506c3fb27SDimitry Andric   uint64_t Width = getContext().getTypeSize(Ty);
319606c3fb27SDimitry Andric   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
319706c3fb27SDimitry Andric 
319806c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
319906c3fb27SDimitry Andric                           CGF.getContext().getTypeInfoInChars(Ty),
320006c3fb27SDimitry Andric                           CharUnits::fromQuantity(8),
320106c3fb27SDimitry Andric                           /*allowHigherAlign*/ false);
320206c3fb27SDimitry Andric }
320306c3fb27SDimitry Andric 
320406c3fb27SDimitry Andric ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
320506c3fb27SDimitry Andric     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
320606c3fb27SDimitry Andric   const Type *Base = nullptr;
320706c3fb27SDimitry Andric   uint64_t NumElts = 0;
320806c3fb27SDimitry Andric 
320906c3fb27SDimitry Andric   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
321006c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
321106c3fb27SDimitry Andric     FreeSSERegs -= NumElts;
321206c3fb27SDimitry Andric     return getDirectX86Hva();
321306c3fb27SDimitry Andric   }
321406c3fb27SDimitry Andric   return current;
321506c3fb27SDimitry Andric }
321606c3fb27SDimitry Andric 
321706c3fb27SDimitry Andric ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
321806c3fb27SDimitry Andric                                       bool IsReturnType, bool IsVectorCall,
321906c3fb27SDimitry Andric                                       bool IsRegCall) const {
322006c3fb27SDimitry Andric 
322106c3fb27SDimitry Andric   if (Ty->isVoidType())
322206c3fb27SDimitry Andric     return ABIArgInfo::getIgnore();
322306c3fb27SDimitry Andric 
322406c3fb27SDimitry Andric   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
322506c3fb27SDimitry Andric     Ty = EnumTy->getDecl()->getIntegerType();
322606c3fb27SDimitry Andric 
322706c3fb27SDimitry Andric   TypeInfo Info = getContext().getTypeInfo(Ty);
322806c3fb27SDimitry Andric   uint64_t Width = Info.Width;
322906c3fb27SDimitry Andric   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
323006c3fb27SDimitry Andric 
323106c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
323206c3fb27SDimitry Andric   if (RT) {
323306c3fb27SDimitry Andric     if (!IsReturnType) {
323406c3fb27SDimitry Andric       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
323506c3fb27SDimitry Andric         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
323606c3fb27SDimitry Andric     }
323706c3fb27SDimitry Andric 
323806c3fb27SDimitry Andric     if (RT->getDecl()->hasFlexibleArrayMember())
323906c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
324006c3fb27SDimitry Andric 
324106c3fb27SDimitry Andric   }
324206c3fb27SDimitry Andric 
324306c3fb27SDimitry Andric   const Type *Base = nullptr;
324406c3fb27SDimitry Andric   uint64_t NumElts = 0;
324506c3fb27SDimitry Andric   // vectorcall adds the concept of a homogenous vector aggregate, similar to
324606c3fb27SDimitry Andric   // other targets.
324706c3fb27SDimitry Andric   if ((IsVectorCall || IsRegCall) &&
324806c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts)) {
324906c3fb27SDimitry Andric     if (IsRegCall) {
325006c3fb27SDimitry Andric       if (FreeSSERegs >= NumElts) {
325106c3fb27SDimitry Andric         FreeSSERegs -= NumElts;
325206c3fb27SDimitry Andric         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
325306c3fb27SDimitry Andric           return ABIArgInfo::getDirect();
325406c3fb27SDimitry Andric         return ABIArgInfo::getExpand();
325506c3fb27SDimitry Andric       }
325606c3fb27SDimitry Andric       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
325706c3fb27SDimitry Andric     } else if (IsVectorCall) {
325806c3fb27SDimitry Andric       if (FreeSSERegs >= NumElts &&
325906c3fb27SDimitry Andric           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
326006c3fb27SDimitry Andric         FreeSSERegs -= NumElts;
326106c3fb27SDimitry Andric         return ABIArgInfo::getDirect();
326206c3fb27SDimitry Andric       } else if (IsReturnType) {
326306c3fb27SDimitry Andric         return ABIArgInfo::getExpand();
326406c3fb27SDimitry Andric       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
326506c3fb27SDimitry Andric         // HVAs are delayed and reclassified in the 2nd step.
326606c3fb27SDimitry Andric         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
326706c3fb27SDimitry Andric       }
326806c3fb27SDimitry Andric     }
326906c3fb27SDimitry Andric   }
327006c3fb27SDimitry Andric 
327106c3fb27SDimitry Andric   if (Ty->isMemberPointerType()) {
327206c3fb27SDimitry Andric     // If the member pointer is represented by an LLVM int or ptr, pass it
327306c3fb27SDimitry Andric     // directly.
327406c3fb27SDimitry Andric     llvm::Type *LLTy = CGT.ConvertType(Ty);
327506c3fb27SDimitry Andric     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
327606c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
327706c3fb27SDimitry Andric   }
327806c3fb27SDimitry Andric 
327906c3fb27SDimitry Andric   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
328006c3fb27SDimitry Andric     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
328106c3fb27SDimitry Andric     // not 1, 2, 4, or 8 bytes, must be passed by reference."
328206c3fb27SDimitry Andric     if (Width > 64 || !llvm::isPowerOf2_64(Width))
328306c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
328406c3fb27SDimitry Andric 
328506c3fb27SDimitry Andric     // Otherwise, coerce it to a small integer.
328606c3fb27SDimitry Andric     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
328706c3fb27SDimitry Andric   }
328806c3fb27SDimitry Andric 
328906c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
329006c3fb27SDimitry Andric     switch (BT->getKind()) {
329106c3fb27SDimitry Andric     case BuiltinType::Bool:
329206c3fb27SDimitry Andric       // Bool type is always extended to the ABI, other builtin types are not
329306c3fb27SDimitry Andric       // extended.
329406c3fb27SDimitry Andric       return ABIArgInfo::getExtend(Ty);
329506c3fb27SDimitry Andric 
329606c3fb27SDimitry Andric     case BuiltinType::LongDouble:
329706c3fb27SDimitry Andric       // Mingw64 GCC uses the old 80 bit extended precision floating point
329806c3fb27SDimitry Andric       // unit. It passes them indirectly through memory.
329906c3fb27SDimitry Andric       if (IsMingw64) {
330006c3fb27SDimitry Andric         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
330106c3fb27SDimitry Andric         if (LDF == &llvm::APFloat::x87DoubleExtended())
330206c3fb27SDimitry Andric           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
330306c3fb27SDimitry Andric       }
330406c3fb27SDimitry Andric       break;
330506c3fb27SDimitry Andric 
330606c3fb27SDimitry Andric     case BuiltinType::Int128:
330706c3fb27SDimitry Andric     case BuiltinType::UInt128:
330806c3fb27SDimitry Andric       // If it's a parameter type, the normal ABI rule is that arguments larger
330906c3fb27SDimitry Andric       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
331006c3fb27SDimitry Andric       // even though it isn't particularly efficient.
331106c3fb27SDimitry Andric       if (!IsReturnType)
331206c3fb27SDimitry Andric         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
331306c3fb27SDimitry Andric 
331406c3fb27SDimitry Andric       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
331506c3fb27SDimitry Andric       // Clang matches them for compatibility.
331606c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
331706c3fb27SDimitry Andric           llvm::Type::getInt64Ty(getVMContext()), 2));
331806c3fb27SDimitry Andric 
331906c3fb27SDimitry Andric     default:
332006c3fb27SDimitry Andric       break;
332106c3fb27SDimitry Andric     }
332206c3fb27SDimitry Andric   }
332306c3fb27SDimitry Andric 
332406c3fb27SDimitry Andric   if (Ty->isBitIntType()) {
332506c3fb27SDimitry Andric     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
332606c3fb27SDimitry Andric     // not 1, 2, 4, or 8 bytes, must be passed by reference."
332706c3fb27SDimitry Andric     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
332806c3fb27SDimitry Andric     // or 8 bytes anyway as long is it fits in them, so we don't have to check
332906c3fb27SDimitry Andric     // the power of 2.
333006c3fb27SDimitry Andric     if (Width <= 64)
333106c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
333206c3fb27SDimitry Andric     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
333306c3fb27SDimitry Andric   }
333406c3fb27SDimitry Andric 
333506c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
333606c3fb27SDimitry Andric }
333706c3fb27SDimitry Andric 
333806c3fb27SDimitry Andric void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
333906c3fb27SDimitry Andric   const unsigned CC = FI.getCallingConvention();
334006c3fb27SDimitry Andric   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
334106c3fb27SDimitry Andric   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
334206c3fb27SDimitry Andric 
334306c3fb27SDimitry Andric   // If __attribute__((sysv_abi)) is in use, use the SysV argument
334406c3fb27SDimitry Andric   // classification rules.
334506c3fb27SDimitry Andric   if (CC == llvm::CallingConv::X86_64_SysV) {
334606c3fb27SDimitry Andric     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
334706c3fb27SDimitry Andric     SysVABIInfo.computeInfo(FI);
334806c3fb27SDimitry Andric     return;
334906c3fb27SDimitry Andric   }
335006c3fb27SDimitry Andric 
335106c3fb27SDimitry Andric   unsigned FreeSSERegs = 0;
335206c3fb27SDimitry Andric   if (IsVectorCall) {
335306c3fb27SDimitry Andric     // We can use up to 4 SSE return registers with vectorcall.
335406c3fb27SDimitry Andric     FreeSSERegs = 4;
335506c3fb27SDimitry Andric   } else if (IsRegCall) {
335606c3fb27SDimitry Andric     // RegCall gives us 16 SSE registers.
335706c3fb27SDimitry Andric     FreeSSERegs = 16;
335806c3fb27SDimitry Andric   }
335906c3fb27SDimitry Andric 
336006c3fb27SDimitry Andric   if (!getCXXABI().classifyReturnType(FI))
336106c3fb27SDimitry Andric     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
336206c3fb27SDimitry Andric                                   IsVectorCall, IsRegCall);
336306c3fb27SDimitry Andric 
336406c3fb27SDimitry Andric   if (IsVectorCall) {
336506c3fb27SDimitry Andric     // We can use up to 6 SSE register parameters with vectorcall.
336606c3fb27SDimitry Andric     FreeSSERegs = 6;
336706c3fb27SDimitry Andric   } else if (IsRegCall) {
336806c3fb27SDimitry Andric     // RegCall gives us 16 SSE registers, we can reuse the return registers.
336906c3fb27SDimitry Andric     FreeSSERegs = 16;
337006c3fb27SDimitry Andric   }
337106c3fb27SDimitry Andric 
337206c3fb27SDimitry Andric   unsigned ArgNum = 0;
337306c3fb27SDimitry Andric   unsigned ZeroSSERegs = 0;
337406c3fb27SDimitry Andric   for (auto &I : FI.arguments()) {
337506c3fb27SDimitry Andric     // Vectorcall in x64 only permits the first 6 arguments to be passed as
337606c3fb27SDimitry Andric     // XMM/YMM registers. After the sixth argument, pretend no vector
337706c3fb27SDimitry Andric     // registers are left.
337806c3fb27SDimitry Andric     unsigned *MaybeFreeSSERegs =
337906c3fb27SDimitry Andric         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
338006c3fb27SDimitry Andric     I.info =
338106c3fb27SDimitry Andric         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
338206c3fb27SDimitry Andric     ++ArgNum;
338306c3fb27SDimitry Andric   }
338406c3fb27SDimitry Andric 
338506c3fb27SDimitry Andric   if (IsVectorCall) {
338606c3fb27SDimitry Andric     // For vectorcall, assign aggregate HVAs to any free vector registers in a
338706c3fb27SDimitry Andric     // second pass.
338806c3fb27SDimitry Andric     for (auto &I : FI.arguments())
338906c3fb27SDimitry Andric       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
339006c3fb27SDimitry Andric   }
339106c3fb27SDimitry Andric }
339206c3fb27SDimitry Andric 
339306c3fb27SDimitry Andric Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
339406c3fb27SDimitry Andric                                     QualType Ty) const {
339506c3fb27SDimitry Andric   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
339606c3fb27SDimitry Andric   // not 1, 2, 4, or 8 bytes, must be passed by reference."
339706c3fb27SDimitry Andric   uint64_t Width = getContext().getTypeSize(Ty);
339806c3fb27SDimitry Andric   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
339906c3fb27SDimitry Andric 
340006c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
340106c3fb27SDimitry Andric                           CGF.getContext().getTypeInfoInChars(Ty),
340206c3fb27SDimitry Andric                           CharUnits::fromQuantity(8),
340306c3fb27SDimitry Andric                           /*allowHigherAlign*/ false);
340406c3fb27SDimitry Andric }
340506c3fb27SDimitry Andric 
340606c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
340706c3fb27SDimitry Andric     CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
340806c3fb27SDimitry Andric     unsigned NumRegisterParameters, bool SoftFloatABI) {
340906c3fb27SDimitry Andric   bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
341006c3fb27SDimitry Andric       CGM.getTriple(), CGM.getCodeGenOpts());
341106c3fb27SDimitry Andric   return std::make_unique<X86_32TargetCodeGenInfo>(
341206c3fb27SDimitry Andric       CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
341306c3fb27SDimitry Andric       NumRegisterParameters, SoftFloatABI);
341406c3fb27SDimitry Andric }
341506c3fb27SDimitry Andric 
341606c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
341706c3fb27SDimitry Andric     CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
341806c3fb27SDimitry Andric     unsigned NumRegisterParameters) {
341906c3fb27SDimitry Andric   bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
342006c3fb27SDimitry Andric       CGM.getTriple(), CGM.getCodeGenOpts());
342106c3fb27SDimitry Andric   return std::make_unique<WinX86_32TargetCodeGenInfo>(
342206c3fb27SDimitry Andric       CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
342306c3fb27SDimitry Andric       NumRegisterParameters);
342406c3fb27SDimitry Andric }
342506c3fb27SDimitry Andric 
342606c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo>
342706c3fb27SDimitry Andric CodeGen::createX86_64TargetCodeGenInfo(CodeGenModule &CGM,
342806c3fb27SDimitry Andric                                        X86AVXABILevel AVXLevel) {
342906c3fb27SDimitry Andric   return std::make_unique<X86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
343006c3fb27SDimitry Andric }
343106c3fb27SDimitry Andric 
343206c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo>
343306c3fb27SDimitry Andric CodeGen::createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM,
343406c3fb27SDimitry Andric                                           X86AVXABILevel AVXLevel) {
343506c3fb27SDimitry Andric   return std::make_unique<WinX86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
343606c3fb27SDimitry Andric }
3437