xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp (revision 9768746ba83efa02837c5b9c66348db6e900208f)
1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TargetInfo.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGValue.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/CodeGenOptions.h"
24 #include "clang/Basic/DiagnosticFrontend.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/CodeGen/SwiftCallingConv.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/IntrinsicsNVPTX.h"
34 #include "llvm/IR/IntrinsicsS390.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 
40 using namespace clang;
41 using namespace CodeGen;
42 
43 // Helper for coercing an aggregate argument or return value into an integer
44 // array of the same size (including padding) and alignment.  This alternate
45 // coercion happens only for the RenderScript ABI and can be removed after
46 // runtimes that rely on it are no longer supported.
47 //
48 // RenderScript assumes that the size of the argument / return value in the IR
49 // is the same as the size of the corresponding qualified type. This helper
50 // coerces the aggregate type into an array of the same size (including
51 // padding).  This coercion is used in lieu of expansion of struct members or
52 // other canonical coercions that return a coerced-type of larger size.
53 //
54 // Ty          - The argument / return value type
55 // Context     - The associated ASTContext
56 // LLVMContext - The associated LLVMContext
57 static ABIArgInfo coerceToIntArray(QualType Ty,
58                                    ASTContext &Context,
59                                    llvm::LLVMContext &LLVMContext) {
60   // Alignment and Size are measured in bits.
61   const uint64_t Size = Context.getTypeSize(Ty);
62   const uint64_t Alignment = Context.getTypeAlign(Ty);
63   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
64   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
65   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
66 }
67 
68 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
69                                llvm::Value *Array,
70                                llvm::Value *Value,
71                                unsigned FirstIndex,
72                                unsigned LastIndex) {
73   // Alternatively, we could emit this as a loop in the source.
74   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
75     llvm::Value *Cell =
76         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
77     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
78   }
79 }
80 
81 static bool isAggregateTypeForABI(QualType T) {
82   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
83          T->isMemberFunctionPointerType();
84 }
85 
86 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
87                                             bool Realign,
88                                             llvm::Type *Padding) const {
89   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
90                                  Realign, Padding);
91 }
92 
93 ABIArgInfo
94 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
95   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
96                                       /*ByVal*/ false, Realign);
97 }
98 
99 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
100                              QualType Ty) const {
101   return Address::invalid();
102 }
103 
104 static llvm::Type *getVAListElementType(CodeGenFunction &CGF) {
105   return CGF.ConvertTypeForMem(
106       CGF.getContext().getBuiltinVaListType()->getPointeeType());
107 }
108 
109 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
110   if (Ty->isPromotableIntegerType())
111     return true;
112 
113   if (const auto *EIT = Ty->getAs<BitIntType>())
114     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
115       return true;
116 
117   return false;
118 }
119 
120 ABIInfo::~ABIInfo() {}
121 
122 /// Does the given lowering require more than the given number of
123 /// registers when expanded?
124 ///
125 /// This is intended to be the basis of a reasonable basic implementation
126 /// of should{Pass,Return}IndirectlyForSwift.
127 ///
128 /// For most targets, a limit of four total registers is reasonable; this
129 /// limits the amount of code required in order to move around the value
130 /// in case it wasn't produced immediately prior to the call by the caller
131 /// (or wasn't produced in exactly the right registers) or isn't used
132 /// immediately within the callee.  But some targets may need to further
133 /// limit the register count due to an inability to support that many
134 /// return registers.
135 static bool occupiesMoreThan(CodeGenTypes &cgt,
136                              ArrayRef<llvm::Type*> scalarTypes,
137                              unsigned maxAllRegisters) {
138   unsigned intCount = 0, fpCount = 0;
139   for (llvm::Type *type : scalarTypes) {
140     if (type->isPointerTy()) {
141       intCount++;
142     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
143       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
144       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
145     } else {
146       assert(type->isVectorTy() || type->isFloatingPointTy());
147       fpCount++;
148     }
149   }
150 
151   return (intCount + fpCount > maxAllRegisters);
152 }
153 
154 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
155                                              llvm::Type *eltTy,
156                                              unsigned numElts) const {
157   // The default implementation of this assumes that the target guarantees
158   // 128-bit SIMD support but nothing more.
159   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
160 }
161 
162 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
163                                               CGCXXABI &CXXABI) {
164   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
165   if (!RD) {
166     if (!RT->getDecl()->canPassInRegisters())
167       return CGCXXABI::RAA_Indirect;
168     return CGCXXABI::RAA_Default;
169   }
170   return CXXABI.getRecordArgABI(RD);
171 }
172 
173 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
174                                               CGCXXABI &CXXABI) {
175   const RecordType *RT = T->getAs<RecordType>();
176   if (!RT)
177     return CGCXXABI::RAA_Default;
178   return getRecordArgABI(RT, CXXABI);
179 }
180 
181 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
182                                const ABIInfo &Info) {
183   QualType Ty = FI.getReturnType();
184 
185   if (const auto *RT = Ty->getAs<RecordType>())
186     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
187         !RT->getDecl()->canPassInRegisters()) {
188       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
189       return true;
190     }
191 
192   return CXXABI.classifyReturnType(FI);
193 }
194 
195 /// Pass transparent unions as if they were the type of the first element. Sema
196 /// should ensure that all elements of the union have the same "machine type".
197 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
198   if (const RecordType *UT = Ty->getAsUnionType()) {
199     const RecordDecl *UD = UT->getDecl();
200     if (UD->hasAttr<TransparentUnionAttr>()) {
201       assert(!UD->field_empty() && "sema created an empty transparent union");
202       return UD->field_begin()->getType();
203     }
204   }
205   return Ty;
206 }
207 
208 CGCXXABI &ABIInfo::getCXXABI() const {
209   return CGT.getCXXABI();
210 }
211 
212 ASTContext &ABIInfo::getContext() const {
213   return CGT.getContext();
214 }
215 
216 llvm::LLVMContext &ABIInfo::getVMContext() const {
217   return CGT.getLLVMContext();
218 }
219 
220 const llvm::DataLayout &ABIInfo::getDataLayout() const {
221   return CGT.getDataLayout();
222 }
223 
224 const TargetInfo &ABIInfo::getTarget() const {
225   return CGT.getTarget();
226 }
227 
228 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
229   return CGT.getCodeGenOpts();
230 }
231 
232 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
233 
234 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
235   return false;
236 }
237 
238 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
239                                                 uint64_t Members) const {
240   return false;
241 }
242 
243 bool ABIInfo::isZeroLengthBitfieldPermittedInHomogeneousAggregate() const {
244   // For compatibility with GCC, ignore empty bitfields in C++ mode.
245   return getContext().getLangOpts().CPlusPlus;
246 }
247 
248 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
249   raw_ostream &OS = llvm::errs();
250   OS << "(ABIArgInfo Kind=";
251   switch (TheKind) {
252   case Direct:
253     OS << "Direct Type=";
254     if (llvm::Type *Ty = getCoerceToType())
255       Ty->print(OS);
256     else
257       OS << "null";
258     break;
259   case Extend:
260     OS << "Extend";
261     break;
262   case Ignore:
263     OS << "Ignore";
264     break;
265   case InAlloca:
266     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
267     break;
268   case Indirect:
269     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
270        << " ByVal=" << getIndirectByVal()
271        << " Realign=" << getIndirectRealign();
272     break;
273   case IndirectAliased:
274     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
275        << " AadrSpace=" << getIndirectAddrSpace()
276        << " Realign=" << getIndirectRealign();
277     break;
278   case Expand:
279     OS << "Expand";
280     break;
281   case CoerceAndExpand:
282     OS << "CoerceAndExpand Type=";
283     getCoerceAndExpandType()->print(OS);
284     break;
285   }
286   OS << ")\n";
287 }
288 
289 // Dynamically round a pointer up to a multiple of the given alignment.
290 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
291                                                   llvm::Value *Ptr,
292                                                   CharUnits Align) {
293   llvm::Value *PtrAsInt = Ptr;
294   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
295   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
296   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
297         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
298   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
299            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
300   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
301                                         Ptr->getType(),
302                                         Ptr->getName() + ".aligned");
303   return PtrAsInt;
304 }
305 
306 /// Emit va_arg for a platform using the common void* representation,
307 /// where arguments are simply emitted in an array of slots on the stack.
308 ///
309 /// This version implements the core direct-value passing rules.
310 ///
311 /// \param SlotSize - The size and alignment of a stack slot.
312 ///   Each argument will be allocated to a multiple of this number of
313 ///   slots, and all the slots will be aligned to this value.
314 /// \param AllowHigherAlign - The slot alignment is not a cap;
315 ///   an argument type with an alignment greater than the slot size
316 ///   will be emitted on a higher-alignment address, potentially
317 ///   leaving one or more empty slots behind as padding.  If this
318 ///   is false, the returned address might be less-aligned than
319 ///   DirectAlign.
320 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
321                                       Address VAListAddr,
322                                       llvm::Type *DirectTy,
323                                       CharUnits DirectSize,
324                                       CharUnits DirectAlign,
325                                       CharUnits SlotSize,
326                                       bool AllowHigherAlign) {
327   // Cast the element type to i8* if necessary.  Some platforms define
328   // va_list as a struct containing an i8* instead of just an i8*.
329   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
330     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
331 
332   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
333 
334   // If the CC aligns values higher than the slot size, do so if needed.
335   Address Addr = Address::invalid();
336   if (AllowHigherAlign && DirectAlign > SlotSize) {
337     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
338                    CGF.Int8Ty, DirectAlign);
339   } else {
340     Addr = Address(Ptr, CGF.Int8Ty, SlotSize);
341   }
342 
343   // Advance the pointer past the argument, then store that back.
344   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
345   Address NextPtr =
346       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
347   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
348 
349   // If the argument is smaller than a slot, and this is a big-endian
350   // target, the argument will be right-adjusted in its slot.
351   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
352       !DirectTy->isStructTy()) {
353     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
354   }
355 
356   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
357   return Addr;
358 }
359 
360 /// Emit va_arg for a platform using the common void* representation,
361 /// where arguments are simply emitted in an array of slots on the stack.
362 ///
363 /// \param IsIndirect - Values of this type are passed indirectly.
364 /// \param ValueInfo - The size and alignment of this type, generally
365 ///   computed with getContext().getTypeInfoInChars(ValueTy).
366 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
367 ///   Each argument will be allocated to a multiple of this number of
368 ///   slots, and all the slots will be aligned to this value.
369 /// \param AllowHigherAlign - The slot alignment is not a cap;
370 ///   an argument type with an alignment greater than the slot size
371 ///   will be emitted on a higher-alignment address, potentially
372 ///   leaving one or more empty slots behind as padding.
373 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
374                                 QualType ValueTy, bool IsIndirect,
375                                 TypeInfoChars ValueInfo,
376                                 CharUnits SlotSizeAndAlign,
377                                 bool AllowHigherAlign) {
378   // The size and alignment of the value that was passed directly.
379   CharUnits DirectSize, DirectAlign;
380   if (IsIndirect) {
381     DirectSize = CGF.getPointerSize();
382     DirectAlign = CGF.getPointerAlign();
383   } else {
384     DirectSize = ValueInfo.Width;
385     DirectAlign = ValueInfo.Align;
386   }
387 
388   // Cast the address we've calculated to the right type.
389   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
390   if (IsIndirect)
391     DirectTy = DirectTy->getPointerTo(0);
392 
393   Address Addr =
394       emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
395                              SlotSizeAndAlign, AllowHigherAlign);
396 
397   if (IsIndirect) {
398     Addr = Address(CGF.Builder.CreateLoad(Addr), ElementTy, ValueInfo.Align);
399   }
400 
401   return Addr;
402 }
403 
404 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
405                                     QualType Ty, CharUnits SlotSize,
406                                     CharUnits EltSize, const ComplexType *CTy) {
407   Address Addr =
408       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
409                              SlotSize, SlotSize, /*AllowHigher*/ true);
410 
411   Address RealAddr = Addr;
412   Address ImagAddr = RealAddr;
413   if (CGF.CGM.getDataLayout().isBigEndian()) {
414     RealAddr =
415         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
416     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
417                                                       2 * SlotSize - EltSize);
418   } else {
419     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
420   }
421 
422   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
423   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
424   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
425   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
426   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
427 
428   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
429   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
430                          /*init*/ true);
431   return Temp;
432 }
433 
434 static Address emitMergePHI(CodeGenFunction &CGF,
435                             Address Addr1, llvm::BasicBlock *Block1,
436                             Address Addr2, llvm::BasicBlock *Block2,
437                             const llvm::Twine &Name = "") {
438   assert(Addr1.getType() == Addr2.getType());
439   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
440   PHI->addIncoming(Addr1.getPointer(), Block1);
441   PHI->addIncoming(Addr2.getPointer(), Block2);
442   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
443   return Address(PHI, Addr1.getElementType(), Align);
444 }
445 
446 TargetCodeGenInfo::TargetCodeGenInfo(std::unique_ptr<ABIInfo> Info)
447     : Info(std::move(Info)) {}
448 
449 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
450 
451 // If someone can figure out a general rule for this, that would be great.
452 // It's probably just doomed to be platform-dependent, though.
453 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
454   // Verified for:
455   //   x86-64     FreeBSD, Linux, Darwin
456   //   x86-32     FreeBSD, Linux, Darwin
457   //   PowerPC    Linux, Darwin
458   //   ARM        Darwin (*not* EABI)
459   //   AArch64    Linux
460   return 32;
461 }
462 
463 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
464                                      const FunctionNoProtoType *fnType) const {
465   // The following conventions are known to require this to be false:
466   //   x86_stdcall
467   //   MIPS
468   // For everything else, we just prefer false unless we opt out.
469   return false;
470 }
471 
472 void
473 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
474                                              llvm::SmallString<24> &Opt) const {
475   // This assumes the user is passing a library name like "rt" instead of a
476   // filename like "librt.a/so", and that they don't care whether it's static or
477   // dynamic.
478   Opt = "-l";
479   Opt += Lib;
480 }
481 
482 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
483   // OpenCL kernels are called via an explicit runtime API with arguments
484   // set with clSetKernelArg(), not as normal sub-functions.
485   // Return SPIR_KERNEL by default as the kernel calling convention to
486   // ensure the fingerprint is fixed such way that each OpenCL argument
487   // gets one matching argument in the produced kernel function argument
488   // list to enable feasible implementation of clSetKernelArg() with
489   // aggregates etc. In case we would use the default C calling conv here,
490   // clSetKernelArg() might break depending on the target-specific
491   // conventions; different targets might split structs passed as values
492   // to multiple function arguments etc.
493   return llvm::CallingConv::SPIR_KERNEL;
494 }
495 
496 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
497     llvm::PointerType *T, QualType QT) const {
498   return llvm::ConstantPointerNull::get(T);
499 }
500 
501 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
502                                                    const VarDecl *D) const {
503   assert(!CGM.getLangOpts().OpenCL &&
504          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
505          "Address space agnostic languages only");
506   return D ? D->getType().getAddressSpace() : LangAS::Default;
507 }
508 
509 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
510     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
511     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
512   // Since target may map different address spaces in AST to the same address
513   // space, an address space conversion may end up as a bitcast.
514   if (auto *C = dyn_cast<llvm::Constant>(Src))
515     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
516   // Try to preserve the source's name to make IR more readable.
517   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
518       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
519 }
520 
521 llvm::Constant *
522 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
523                                         LangAS SrcAddr, LangAS DestAddr,
524                                         llvm::Type *DestTy) const {
525   // Since target may map different address spaces in AST to the same address
526   // space, an address space conversion may end up as a bitcast.
527   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
528 }
529 
530 llvm::SyncScope::ID
531 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
532                                       SyncScope Scope,
533                                       llvm::AtomicOrdering Ordering,
534                                       llvm::LLVMContext &Ctx) const {
535   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
536 }
537 
538 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
539 
540 /// isEmptyField - Return true iff a the field is "empty", that is it
541 /// is an unnamed bit-field or an (array of) empty record(s).
542 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
543                          bool AllowArrays) {
544   if (FD->isUnnamedBitfield())
545     return true;
546 
547   QualType FT = FD->getType();
548 
549   // Constant arrays of empty records count as empty, strip them off.
550   // Constant arrays of zero length always count as empty.
551   bool WasArray = false;
552   if (AllowArrays)
553     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
554       if (AT->getSize() == 0)
555         return true;
556       FT = AT->getElementType();
557       // The [[no_unique_address]] special case below does not apply to
558       // arrays of C++ empty records, so we need to remember this fact.
559       WasArray = true;
560     }
561 
562   const RecordType *RT = FT->getAs<RecordType>();
563   if (!RT)
564     return false;
565 
566   // C++ record fields are never empty, at least in the Itanium ABI.
567   //
568   // FIXME: We should use a predicate for whether this behavior is true in the
569   // current ABI.
570   //
571   // The exception to the above rule are fields marked with the
572   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
573   // according to the Itanium ABI.  The exception applies only to records,
574   // not arrays of records, so we must also check whether we stripped off an
575   // array type above.
576   if (isa<CXXRecordDecl>(RT->getDecl()) &&
577       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
578     return false;
579 
580   return isEmptyRecord(Context, FT, AllowArrays);
581 }
582 
583 /// isEmptyRecord - Return true iff a structure contains only empty
584 /// fields. Note that a structure with a flexible array member is not
585 /// considered empty.
586 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
587   const RecordType *RT = T->getAs<RecordType>();
588   if (!RT)
589     return false;
590   const RecordDecl *RD = RT->getDecl();
591   if (RD->hasFlexibleArrayMember())
592     return false;
593 
594   // If this is a C++ record, check the bases first.
595   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
596     for (const auto &I : CXXRD->bases())
597       if (!isEmptyRecord(Context, I.getType(), true))
598         return false;
599 
600   for (const auto *I : RD->fields())
601     if (!isEmptyField(Context, I, AllowArrays))
602       return false;
603   return true;
604 }
605 
606 /// isSingleElementStruct - Determine if a structure is a "single
607 /// element struct", i.e. it has exactly one non-empty field or
608 /// exactly one field which is itself a single element
609 /// struct. Structures with flexible array members are never
610 /// considered single element structs.
611 ///
612 /// \return The field declaration for the single non-empty field, if
613 /// it exists.
614 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
615   const RecordType *RT = T->getAs<RecordType>();
616   if (!RT)
617     return nullptr;
618 
619   const RecordDecl *RD = RT->getDecl();
620   if (RD->hasFlexibleArrayMember())
621     return nullptr;
622 
623   const Type *Found = nullptr;
624 
625   // If this is a C++ record, check the bases first.
626   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
627     for (const auto &I : CXXRD->bases()) {
628       // Ignore empty records.
629       if (isEmptyRecord(Context, I.getType(), true))
630         continue;
631 
632       // If we already found an element then this isn't a single-element struct.
633       if (Found)
634         return nullptr;
635 
636       // If this is non-empty and not a single element struct, the composite
637       // cannot be a single element struct.
638       Found = isSingleElementStruct(I.getType(), Context);
639       if (!Found)
640         return nullptr;
641     }
642   }
643 
644   // Check for single element.
645   for (const auto *FD : RD->fields()) {
646     QualType FT = FD->getType();
647 
648     // Ignore empty fields.
649     if (isEmptyField(Context, FD, true))
650       continue;
651 
652     // If we already found an element then this isn't a single-element
653     // struct.
654     if (Found)
655       return nullptr;
656 
657     // Treat single element arrays as the element.
658     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
659       if (AT->getSize().getZExtValue() != 1)
660         break;
661       FT = AT->getElementType();
662     }
663 
664     if (!isAggregateTypeForABI(FT)) {
665       Found = FT.getTypePtr();
666     } else {
667       Found = isSingleElementStruct(FT, Context);
668       if (!Found)
669         return nullptr;
670     }
671   }
672 
673   // We don't consider a struct a single-element struct if it has
674   // padding beyond the element type.
675   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
676     return nullptr;
677 
678   return Found;
679 }
680 
681 namespace {
682 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
683                        const ABIArgInfo &AI) {
684   // This default implementation defers to the llvm backend's va_arg
685   // instruction. It can handle only passing arguments directly
686   // (typically only handled in the backend for primitive types), or
687   // aggregates passed indirectly by pointer (NOTE: if the "byval"
688   // flag has ABI impact in the callee, this implementation cannot
689   // work.)
690 
691   // Only a few cases are covered here at the moment -- those needed
692   // by the default abi.
693   llvm::Value *Val;
694 
695   if (AI.isIndirect()) {
696     assert(!AI.getPaddingType() &&
697            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
698     assert(
699         !AI.getIndirectRealign() &&
700         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
701 
702     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
703     CharUnits TyAlignForABI = TyInfo.Align;
704 
705     llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty);
706     llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy);
707     llvm::Value *Addr =
708         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
709     return Address(Addr, ElementTy, TyAlignForABI);
710   } else {
711     assert((AI.isDirect() || AI.isExtend()) &&
712            "Unexpected ArgInfo Kind in generic VAArg emitter!");
713 
714     assert(!AI.getInReg() &&
715            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
716     assert(!AI.getPaddingType() &&
717            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
718     assert(!AI.getDirectOffset() &&
719            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
720     assert(!AI.getCoerceToType() &&
721            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
722 
723     Address Temp = CGF.CreateMemTemp(Ty, "varet");
724     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
725                                   CGF.ConvertTypeForMem(Ty));
726     CGF.Builder.CreateStore(Val, Temp);
727     return Temp;
728   }
729 }
730 
731 /// DefaultABIInfo - The default implementation for ABI specific
732 /// details. This implementation provides information which results in
733 /// self-consistent and sensible LLVM IR generation, but does not
734 /// conform to any particular ABI.
735 class DefaultABIInfo : public ABIInfo {
736 public:
737   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
738 
739   ABIArgInfo classifyReturnType(QualType RetTy) const;
740   ABIArgInfo classifyArgumentType(QualType RetTy) const;
741 
742   void computeInfo(CGFunctionInfo &FI) const override {
743     if (!getCXXABI().classifyReturnType(FI))
744       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
745     for (auto &I : FI.arguments())
746       I.info = classifyArgumentType(I.type);
747   }
748 
749   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
750                     QualType Ty) const override {
751     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
752   }
753 };
754 
755 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
756 public:
757   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
758       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
759 };
760 
761 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
762   Ty = useFirstFieldIfTransparentUnion(Ty);
763 
764   if (isAggregateTypeForABI(Ty)) {
765     // Records with non-trivial destructors/copy-constructors should not be
766     // passed by value.
767     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
768       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
769 
770     return getNaturalAlignIndirect(Ty);
771   }
772 
773   // Treat an enum type as its underlying type.
774   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
775     Ty = EnumTy->getDecl()->getIntegerType();
776 
777   ASTContext &Context = getContext();
778   if (const auto *EIT = Ty->getAs<BitIntType>())
779     if (EIT->getNumBits() >
780         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
781                                 ? Context.Int128Ty
782                                 : Context.LongLongTy))
783       return getNaturalAlignIndirect(Ty);
784 
785   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
786                                             : ABIArgInfo::getDirect());
787 }
788 
789 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
790   if (RetTy->isVoidType())
791     return ABIArgInfo::getIgnore();
792 
793   if (isAggregateTypeForABI(RetTy))
794     return getNaturalAlignIndirect(RetTy);
795 
796   // Treat an enum type as its underlying type.
797   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
798     RetTy = EnumTy->getDecl()->getIntegerType();
799 
800   if (const auto *EIT = RetTy->getAs<BitIntType>())
801     if (EIT->getNumBits() >
802         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
803                                      ? getContext().Int128Ty
804                                      : getContext().LongLongTy))
805       return getNaturalAlignIndirect(RetTy);
806 
807   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
808                                                : ABIArgInfo::getDirect());
809 }
810 
811 //===----------------------------------------------------------------------===//
812 // WebAssembly ABI Implementation
813 //
814 // This is a very simple ABI that relies a lot on DefaultABIInfo.
815 //===----------------------------------------------------------------------===//
816 
817 class WebAssemblyABIInfo final : public SwiftABIInfo {
818 public:
819   enum ABIKind {
820     MVP = 0,
821     ExperimentalMV = 1,
822   };
823 
824 private:
825   DefaultABIInfo defaultInfo;
826   ABIKind Kind;
827 
828 public:
829   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
830       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
831 
832 private:
833   ABIArgInfo classifyReturnType(QualType RetTy) const;
834   ABIArgInfo classifyArgumentType(QualType Ty) const;
835 
836   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
837   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
838   // overload them.
839   void computeInfo(CGFunctionInfo &FI) const override {
840     if (!getCXXABI().classifyReturnType(FI))
841       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
842     for (auto &Arg : FI.arguments())
843       Arg.info = classifyArgumentType(Arg.type);
844   }
845 
846   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
847                     QualType Ty) const override;
848 
849   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
850                                     bool asReturnValue) const override {
851     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
852   }
853 
854   bool isSwiftErrorInRegister() const override {
855     return false;
856   }
857 };
858 
859 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
860 public:
861   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
862                                         WebAssemblyABIInfo::ABIKind K)
863       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
864 
865   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
866                            CodeGen::CodeGenModule &CGM) const override {
867     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
868     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
869       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
870         llvm::Function *Fn = cast<llvm::Function>(GV);
871         llvm::AttrBuilder B(GV->getContext());
872         B.addAttribute("wasm-import-module", Attr->getImportModule());
873         Fn->addFnAttrs(B);
874       }
875       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
876         llvm::Function *Fn = cast<llvm::Function>(GV);
877         llvm::AttrBuilder B(GV->getContext());
878         B.addAttribute("wasm-import-name", Attr->getImportName());
879         Fn->addFnAttrs(B);
880       }
881       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
882         llvm::Function *Fn = cast<llvm::Function>(GV);
883         llvm::AttrBuilder B(GV->getContext());
884         B.addAttribute("wasm-export-name", Attr->getExportName());
885         Fn->addFnAttrs(B);
886       }
887     }
888 
889     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
890       llvm::Function *Fn = cast<llvm::Function>(GV);
891       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
892         Fn->addFnAttr("no-prototype");
893     }
894   }
895 };
896 
897 /// Classify argument of given type \p Ty.
898 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
899   Ty = useFirstFieldIfTransparentUnion(Ty);
900 
901   if (isAggregateTypeForABI(Ty)) {
902     // Records with non-trivial destructors/copy-constructors should not be
903     // passed by value.
904     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
905       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
906     // Ignore empty structs/unions.
907     if (isEmptyRecord(getContext(), Ty, true))
908       return ABIArgInfo::getIgnore();
909     // Lower single-element structs to just pass a regular value. TODO: We
910     // could do reasonable-size multiple-element structs too, using getExpand(),
911     // though watch out for things like bitfields.
912     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
913       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
914     // For the experimental multivalue ABI, fully expand all other aggregates
915     if (Kind == ABIKind::ExperimentalMV) {
916       const RecordType *RT = Ty->getAs<RecordType>();
917       assert(RT);
918       bool HasBitField = false;
919       for (auto *Field : RT->getDecl()->fields()) {
920         if (Field->isBitField()) {
921           HasBitField = true;
922           break;
923         }
924       }
925       if (!HasBitField)
926         return ABIArgInfo::getExpand();
927     }
928   }
929 
930   // Otherwise just do the default thing.
931   return defaultInfo.classifyArgumentType(Ty);
932 }
933 
934 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
935   if (isAggregateTypeForABI(RetTy)) {
936     // Records with non-trivial destructors/copy-constructors should not be
937     // returned by value.
938     if (!getRecordArgABI(RetTy, getCXXABI())) {
939       // Ignore empty structs/unions.
940       if (isEmptyRecord(getContext(), RetTy, true))
941         return ABIArgInfo::getIgnore();
942       // Lower single-element structs to just return a regular value. TODO: We
943       // could do reasonable-size multiple-element structs too, using
944       // ABIArgInfo::getDirect().
945       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
946         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
947       // For the experimental multivalue ABI, return all other aggregates
948       if (Kind == ABIKind::ExperimentalMV)
949         return ABIArgInfo::getDirect();
950     }
951   }
952 
953   // Otherwise just do the default thing.
954   return defaultInfo.classifyReturnType(RetTy);
955 }
956 
957 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
958                                       QualType Ty) const {
959   bool IsIndirect = isAggregateTypeForABI(Ty) &&
960                     !isEmptyRecord(getContext(), Ty, true) &&
961                     !isSingleElementStruct(Ty, getContext());
962   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
963                           getContext().getTypeInfoInChars(Ty),
964                           CharUnits::fromQuantity(4),
965                           /*AllowHigherAlign=*/true);
966 }
967 
968 //===----------------------------------------------------------------------===//
969 // le32/PNaCl bitcode ABI Implementation
970 //
971 // This is a simplified version of the x86_32 ABI.  Arguments and return values
972 // are always passed on the stack.
973 //===----------------------------------------------------------------------===//
974 
975 class PNaClABIInfo : public ABIInfo {
976  public:
977   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
978 
979   ABIArgInfo classifyReturnType(QualType RetTy) const;
980   ABIArgInfo classifyArgumentType(QualType RetTy) const;
981 
982   void computeInfo(CGFunctionInfo &FI) const override;
983   Address EmitVAArg(CodeGenFunction &CGF,
984                     Address VAListAddr, QualType Ty) const override;
985 };
986 
987 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
988  public:
989    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
990        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
991 };
992 
993 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
994   if (!getCXXABI().classifyReturnType(FI))
995     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
996 
997   for (auto &I : FI.arguments())
998     I.info = classifyArgumentType(I.type);
999 }
1000 
1001 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1002                                 QualType Ty) const {
1003   // The PNaCL ABI is a bit odd, in that varargs don't use normal
1004   // function classification. Structs get passed directly for varargs
1005   // functions, through a rewriting transform in
1006   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
1007   // this target to actually support a va_arg instructions with an
1008   // aggregate type, unlike other targets.
1009   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
1010 }
1011 
1012 /// Classify argument of given type \p Ty.
1013 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1014   if (isAggregateTypeForABI(Ty)) {
1015     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1016       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1017     return getNaturalAlignIndirect(Ty);
1018   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1019     // Treat an enum type as its underlying type.
1020     Ty = EnumTy->getDecl()->getIntegerType();
1021   } else if (Ty->isFloatingType()) {
1022     // Floating-point types don't go inreg.
1023     return ABIArgInfo::getDirect();
1024   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1025     // Treat bit-precise integers as integers if <= 64, otherwise pass
1026     // indirectly.
1027     if (EIT->getNumBits() > 64)
1028       return getNaturalAlignIndirect(Ty);
1029     return ABIArgInfo::getDirect();
1030   }
1031 
1032   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1033                                             : ABIArgInfo::getDirect());
1034 }
1035 
1036 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1037   if (RetTy->isVoidType())
1038     return ABIArgInfo::getIgnore();
1039 
1040   // In the PNaCl ABI we always return records/structures on the stack.
1041   if (isAggregateTypeForABI(RetTy))
1042     return getNaturalAlignIndirect(RetTy);
1043 
1044   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1045   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1046     if (EIT->getNumBits() > 64)
1047       return getNaturalAlignIndirect(RetTy);
1048     return ABIArgInfo::getDirect();
1049   }
1050 
1051   // Treat an enum type as its underlying type.
1052   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1053     RetTy = EnumTy->getDecl()->getIntegerType();
1054 
1055   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1056                                                : ABIArgInfo::getDirect());
1057 }
1058 
1059 /// IsX86_MMXType - Return true if this is an MMX type.
1060 bool IsX86_MMXType(llvm::Type *IRType) {
1061   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1062   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1063     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1064     IRType->getScalarSizeInBits() != 64;
1065 }
1066 
1067 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1068                                           StringRef Constraint,
1069                                           llvm::Type* Ty) {
1070   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1071                      .Cases("y", "&y", "^Ym", true)
1072                      .Default(false);
1073   if (IsMMXCons && Ty->isVectorTy()) {
1074     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1075         64) {
1076       // Invalid MMX constraint
1077       return nullptr;
1078     }
1079 
1080     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1081   }
1082 
1083   // No operation needed
1084   return Ty;
1085 }
1086 
1087 /// Returns true if this type can be passed in SSE registers with the
1088 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1089 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1090   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1091     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1092       if (BT->getKind() == BuiltinType::LongDouble) {
1093         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1094             &llvm::APFloat::x87DoubleExtended())
1095           return false;
1096       }
1097       return true;
1098     }
1099   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1100     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1101     // registers specially.
1102     unsigned VecSize = Context.getTypeSize(VT);
1103     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1104       return true;
1105   }
1106   return false;
1107 }
1108 
1109 /// Returns true if this aggregate is small enough to be passed in SSE registers
1110 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1111 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1112   return NumMembers <= 4;
1113 }
1114 
1115 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1116 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1117   auto AI = ABIArgInfo::getDirect(T);
1118   AI.setInReg(true);
1119   AI.setCanBeFlattened(false);
1120   return AI;
1121 }
1122 
1123 //===----------------------------------------------------------------------===//
1124 // X86-32 ABI Implementation
1125 //===----------------------------------------------------------------------===//
1126 
1127 /// Similar to llvm::CCState, but for Clang.
1128 struct CCState {
1129   CCState(CGFunctionInfo &FI)
1130       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1131 
1132   llvm::SmallBitVector IsPreassigned;
1133   unsigned CC = CallingConv::CC_C;
1134   unsigned FreeRegs = 0;
1135   unsigned FreeSSERegs = 0;
1136 };
1137 
1138 /// X86_32ABIInfo - The X86-32 ABI information.
1139 class X86_32ABIInfo : public SwiftABIInfo {
1140   enum Class {
1141     Integer,
1142     Float
1143   };
1144 
1145   static const unsigned MinABIStackAlignInBytes = 4;
1146 
1147   bool IsDarwinVectorABI;
1148   bool IsRetSmallStructInRegABI;
1149   bool IsWin32StructABI;
1150   bool IsSoftFloatABI;
1151   bool IsMCUABI;
1152   bool IsLinuxABI;
1153   unsigned DefaultNumRegisterParameters;
1154 
1155   static bool isRegisterSize(unsigned Size) {
1156     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1157   }
1158 
1159   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1160     // FIXME: Assumes vectorcall is in use.
1161     return isX86VectorTypeForVectorCall(getContext(), Ty);
1162   }
1163 
1164   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1165                                          uint64_t NumMembers) const override {
1166     // FIXME: Assumes vectorcall is in use.
1167     return isX86VectorCallAggregateSmallEnough(NumMembers);
1168   }
1169 
1170   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1171 
1172   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1173   /// such that the argument will be passed in memory.
1174   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1175 
1176   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1177 
1178   /// Return the alignment to use for the given type on the stack.
1179   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1180 
1181   Class classify(QualType Ty) const;
1182   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1183   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1184 
1185   /// Updates the number of available free registers, returns
1186   /// true if any registers were allocated.
1187   bool updateFreeRegs(QualType Ty, CCState &State) const;
1188 
1189   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1190                                 bool &NeedsPadding) const;
1191   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1192 
1193   bool canExpandIndirectArgument(QualType Ty) const;
1194 
1195   /// Rewrite the function info so that all memory arguments use
1196   /// inalloca.
1197   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1198 
1199   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1200                            CharUnits &StackOffset, ABIArgInfo &Info,
1201                            QualType Type) const;
1202   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1203 
1204 public:
1205 
1206   void computeInfo(CGFunctionInfo &FI) const override;
1207   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1208                     QualType Ty) const override;
1209 
1210   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1211                 bool RetSmallStructInRegABI, bool Win32StructABI,
1212                 unsigned NumRegisterParameters, bool SoftFloatABI)
1213     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1214       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1215       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1216       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1217       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1218                  CGT.getTarget().getTriple().isOSCygMing()),
1219       DefaultNumRegisterParameters(NumRegisterParameters) {}
1220 
1221   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1222                                     bool asReturnValue) const override {
1223     // LLVM's x86-32 lowering currently only assigns up to three
1224     // integer registers and three fp registers.  Oddly, it'll use up to
1225     // four vector registers for vectors, but those can overlap with the
1226     // scalar registers.
1227     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1228   }
1229 
1230   bool isSwiftErrorInRegister() const override {
1231     // x86-32 lowering does not support passing swifterror in a register.
1232     return false;
1233   }
1234 };
1235 
1236 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1237 public:
1238   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1239                           bool RetSmallStructInRegABI, bool Win32StructABI,
1240                           unsigned NumRegisterParameters, bool SoftFloatABI)
1241       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1242             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1243             NumRegisterParameters, SoftFloatABI)) {}
1244 
1245   static bool isStructReturnInRegABI(
1246       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1247 
1248   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1249                            CodeGen::CodeGenModule &CGM) const override;
1250 
1251   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1252     // Darwin uses different dwarf register numbers for EH.
1253     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1254     return 4;
1255   }
1256 
1257   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1258                                llvm::Value *Address) const override;
1259 
1260   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1261                                   StringRef Constraint,
1262                                   llvm::Type* Ty) const override {
1263     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1264   }
1265 
1266   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1267                                 std::string &Constraints,
1268                                 std::vector<llvm::Type *> &ResultRegTypes,
1269                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1270                                 std::vector<LValue> &ResultRegDests,
1271                                 std::string &AsmString,
1272                                 unsigned NumOutputs) const override;
1273 
1274   llvm::Constant *
1275   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1276     unsigned Sig = (0xeb << 0) |  // jmp rel8
1277                    (0x06 << 8) |  //           .+0x08
1278                    ('v' << 16) |
1279                    ('2' << 24);
1280     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1281   }
1282 
1283   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1284     return "movl\t%ebp, %ebp"
1285            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1286   }
1287 };
1288 
1289 }
1290 
1291 /// Rewrite input constraint references after adding some output constraints.
1292 /// In the case where there is one output and one input and we add one output,
1293 /// we need to replace all operand references greater than or equal to 1:
1294 ///     mov $0, $1
1295 ///     mov eax, $1
1296 /// The result will be:
1297 ///     mov $0, $2
1298 ///     mov eax, $2
1299 static void rewriteInputConstraintReferences(unsigned FirstIn,
1300                                              unsigned NumNewOuts,
1301                                              std::string &AsmString) {
1302   std::string Buf;
1303   llvm::raw_string_ostream OS(Buf);
1304   size_t Pos = 0;
1305   while (Pos < AsmString.size()) {
1306     size_t DollarStart = AsmString.find('$', Pos);
1307     if (DollarStart == std::string::npos)
1308       DollarStart = AsmString.size();
1309     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1310     if (DollarEnd == std::string::npos)
1311       DollarEnd = AsmString.size();
1312     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1313     Pos = DollarEnd;
1314     size_t NumDollars = DollarEnd - DollarStart;
1315     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1316       // We have an operand reference.
1317       size_t DigitStart = Pos;
1318       if (AsmString[DigitStart] == '{') {
1319         OS << '{';
1320         ++DigitStart;
1321       }
1322       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1323       if (DigitEnd == std::string::npos)
1324         DigitEnd = AsmString.size();
1325       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1326       unsigned OperandIndex;
1327       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1328         if (OperandIndex >= FirstIn)
1329           OperandIndex += NumNewOuts;
1330         OS << OperandIndex;
1331       } else {
1332         OS << OperandStr;
1333       }
1334       Pos = DigitEnd;
1335     }
1336   }
1337   AsmString = std::move(OS.str());
1338 }
1339 
1340 /// Add output constraints for EAX:EDX because they are return registers.
1341 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1342     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1343     std::vector<llvm::Type *> &ResultRegTypes,
1344     std::vector<llvm::Type *> &ResultTruncRegTypes,
1345     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1346     unsigned NumOutputs) const {
1347   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1348 
1349   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1350   // larger.
1351   if (!Constraints.empty())
1352     Constraints += ',';
1353   if (RetWidth <= 32) {
1354     Constraints += "={eax}";
1355     ResultRegTypes.push_back(CGF.Int32Ty);
1356   } else {
1357     // Use the 'A' constraint for EAX:EDX.
1358     Constraints += "=A";
1359     ResultRegTypes.push_back(CGF.Int64Ty);
1360   }
1361 
1362   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1363   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1364   ResultTruncRegTypes.push_back(CoerceTy);
1365 
1366   // Coerce the integer by bitcasting the return slot pointer.
1367   ReturnSlot.setAddress(
1368       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1369   ResultRegDests.push_back(ReturnSlot);
1370 
1371   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1372 }
1373 
1374 /// shouldReturnTypeInRegister - Determine if the given type should be
1375 /// returned in a register (for the Darwin and MCU ABI).
1376 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1377                                                ASTContext &Context) const {
1378   uint64_t Size = Context.getTypeSize(Ty);
1379 
1380   // For i386, type must be register sized.
1381   // For the MCU ABI, it only needs to be <= 8-byte
1382   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1383    return false;
1384 
1385   if (Ty->isVectorType()) {
1386     // 64- and 128- bit vectors inside structures are not returned in
1387     // registers.
1388     if (Size == 64 || Size == 128)
1389       return false;
1390 
1391     return true;
1392   }
1393 
1394   // If this is a builtin, pointer, enum, complex type, member pointer, or
1395   // member function pointer it is ok.
1396   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1397       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1398       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1399     return true;
1400 
1401   // Arrays are treated like records.
1402   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1403     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1404 
1405   // Otherwise, it must be a record type.
1406   const RecordType *RT = Ty->getAs<RecordType>();
1407   if (!RT) return false;
1408 
1409   // FIXME: Traverse bases here too.
1410 
1411   // Structure types are passed in register if all fields would be
1412   // passed in a register.
1413   for (const auto *FD : RT->getDecl()->fields()) {
1414     // Empty fields are ignored.
1415     if (isEmptyField(Context, FD, true))
1416       continue;
1417 
1418     // Check fields recursively.
1419     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1420       return false;
1421   }
1422   return true;
1423 }
1424 
1425 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1426   // Treat complex types as the element type.
1427   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1428     Ty = CTy->getElementType();
1429 
1430   // Check for a type which we know has a simple scalar argument-passing
1431   // convention without any padding.  (We're specifically looking for 32
1432   // and 64-bit integer and integer-equivalents, float, and double.)
1433   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1434       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1435     return false;
1436 
1437   uint64_t Size = Context.getTypeSize(Ty);
1438   return Size == 32 || Size == 64;
1439 }
1440 
1441 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1442                           uint64_t &Size) {
1443   for (const auto *FD : RD->fields()) {
1444     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1445     // argument is smaller than 32-bits, expanding the struct will create
1446     // alignment padding.
1447     if (!is32Or64BitBasicType(FD->getType(), Context))
1448       return false;
1449 
1450     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1451     // how to expand them yet, and the predicate for telling if a bitfield still
1452     // counts as "basic" is more complicated than what we were doing previously.
1453     if (FD->isBitField())
1454       return false;
1455 
1456     Size += Context.getTypeSize(FD->getType());
1457   }
1458   return true;
1459 }
1460 
1461 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1462                                  uint64_t &Size) {
1463   // Don't do this if there are any non-empty bases.
1464   for (const CXXBaseSpecifier &Base : RD->bases()) {
1465     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1466                               Size))
1467       return false;
1468   }
1469   if (!addFieldSizes(Context, RD, Size))
1470     return false;
1471   return true;
1472 }
1473 
1474 /// Test whether an argument type which is to be passed indirectly (on the
1475 /// stack) would have the equivalent layout if it was expanded into separate
1476 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1477 /// optimizations.
1478 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1479   // We can only expand structure types.
1480   const RecordType *RT = Ty->getAs<RecordType>();
1481   if (!RT)
1482     return false;
1483   const RecordDecl *RD = RT->getDecl();
1484   uint64_t Size = 0;
1485   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1486     if (!IsWin32StructABI) {
1487       // On non-Windows, we have to conservatively match our old bitcode
1488       // prototypes in order to be ABI-compatible at the bitcode level.
1489       if (!CXXRD->isCLike())
1490         return false;
1491     } else {
1492       // Don't do this for dynamic classes.
1493       if (CXXRD->isDynamicClass())
1494         return false;
1495     }
1496     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1497       return false;
1498   } else {
1499     if (!addFieldSizes(getContext(), RD, Size))
1500       return false;
1501   }
1502 
1503   // We can do this if there was no alignment padding.
1504   return Size == getContext().getTypeSize(Ty);
1505 }
1506 
1507 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1508   // If the return value is indirect, then the hidden argument is consuming one
1509   // integer register.
1510   if (State.FreeRegs) {
1511     --State.FreeRegs;
1512     if (!IsMCUABI)
1513       return getNaturalAlignIndirectInReg(RetTy);
1514   }
1515   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1516 }
1517 
1518 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1519                                              CCState &State) const {
1520   if (RetTy->isVoidType())
1521     return ABIArgInfo::getIgnore();
1522 
1523   const Type *Base = nullptr;
1524   uint64_t NumElts = 0;
1525   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1526        State.CC == llvm::CallingConv::X86_RegCall) &&
1527       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1528     // The LLVM struct type for such an aggregate should lower properly.
1529     return ABIArgInfo::getDirect();
1530   }
1531 
1532   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1533     // On Darwin, some vectors are returned in registers.
1534     if (IsDarwinVectorABI) {
1535       uint64_t Size = getContext().getTypeSize(RetTy);
1536 
1537       // 128-bit vectors are a special case; they are returned in
1538       // registers and we need to make sure to pick a type the LLVM
1539       // backend will like.
1540       if (Size == 128)
1541         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1542             llvm::Type::getInt64Ty(getVMContext()), 2));
1543 
1544       // Always return in register if it fits in a general purpose
1545       // register, or if it is 64 bits and has a single element.
1546       if ((Size == 8 || Size == 16 || Size == 32) ||
1547           (Size == 64 && VT->getNumElements() == 1))
1548         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1549                                                             Size));
1550 
1551       return getIndirectReturnResult(RetTy, State);
1552     }
1553 
1554     return ABIArgInfo::getDirect();
1555   }
1556 
1557   if (isAggregateTypeForABI(RetTy)) {
1558     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1559       // Structures with flexible arrays are always indirect.
1560       if (RT->getDecl()->hasFlexibleArrayMember())
1561         return getIndirectReturnResult(RetTy, State);
1562     }
1563 
1564     // If specified, structs and unions are always indirect.
1565     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1566       return getIndirectReturnResult(RetTy, State);
1567 
1568     // Ignore empty structs/unions.
1569     if (isEmptyRecord(getContext(), RetTy, true))
1570       return ABIArgInfo::getIgnore();
1571 
1572     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1573     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1574       QualType ET = getContext().getCanonicalType(CT->getElementType());
1575       if (ET->isFloat16Type())
1576         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1577             llvm::Type::getHalfTy(getVMContext()), 2));
1578     }
1579 
1580     // Small structures which are register sized are generally returned
1581     // in a register.
1582     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1583       uint64_t Size = getContext().getTypeSize(RetTy);
1584 
1585       // As a special-case, if the struct is a "single-element" struct, and
1586       // the field is of type "float" or "double", return it in a
1587       // floating-point register. (MSVC does not apply this special case.)
1588       // We apply a similar transformation for pointer types to improve the
1589       // quality of the generated IR.
1590       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1591         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1592             || SeltTy->hasPointerRepresentation())
1593           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1594 
1595       // FIXME: We should be able to narrow this integer in cases with dead
1596       // padding.
1597       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1598     }
1599 
1600     return getIndirectReturnResult(RetTy, State);
1601   }
1602 
1603   // Treat an enum type as its underlying type.
1604   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1605     RetTy = EnumTy->getDecl()->getIntegerType();
1606 
1607   if (const auto *EIT = RetTy->getAs<BitIntType>())
1608     if (EIT->getNumBits() > 64)
1609       return getIndirectReturnResult(RetTy, State);
1610 
1611   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1612                                                : ABIArgInfo::getDirect());
1613 }
1614 
1615 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1616   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1617 }
1618 
1619 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1620   const RecordType *RT = Ty->getAs<RecordType>();
1621   if (!RT)
1622     return false;
1623   const RecordDecl *RD = RT->getDecl();
1624 
1625   // If this is a C++ record, check the bases first.
1626   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1627     for (const auto &I : CXXRD->bases())
1628       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1629         return false;
1630 
1631   for (const auto *i : RD->fields()) {
1632     QualType FT = i->getType();
1633 
1634     if (isSIMDVectorType(Context, FT))
1635       return true;
1636 
1637     if (isRecordWithSIMDVectorType(Context, FT))
1638       return true;
1639   }
1640 
1641   return false;
1642 }
1643 
1644 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1645                                                  unsigned Align) const {
1646   // Otherwise, if the alignment is less than or equal to the minimum ABI
1647   // alignment, just use the default; the backend will handle this.
1648   if (Align <= MinABIStackAlignInBytes)
1649     return 0; // Use default alignment.
1650 
1651   if (IsLinuxABI) {
1652     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1653     // want to spend any effort dealing with the ramifications of ABI breaks.
1654     //
1655     // If the vector type is __m128/__m256/__m512, return the default alignment.
1656     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1657       return Align;
1658   }
1659   // On non-Darwin, the stack type alignment is always 4.
1660   if (!IsDarwinVectorABI) {
1661     // Set explicit alignment, since we may need to realign the top.
1662     return MinABIStackAlignInBytes;
1663   }
1664 
1665   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1666   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1667                       isRecordWithSIMDVectorType(getContext(), Ty)))
1668     return 16;
1669 
1670   return MinABIStackAlignInBytes;
1671 }
1672 
1673 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1674                                             CCState &State) const {
1675   if (!ByVal) {
1676     if (State.FreeRegs) {
1677       --State.FreeRegs; // Non-byval indirects just use one pointer.
1678       if (!IsMCUABI)
1679         return getNaturalAlignIndirectInReg(Ty);
1680     }
1681     return getNaturalAlignIndirect(Ty, false);
1682   }
1683 
1684   // Compute the byval alignment.
1685   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1686   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1687   if (StackAlign == 0)
1688     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1689 
1690   // If the stack alignment is less than the type alignment, realign the
1691   // argument.
1692   bool Realign = TypeAlign > StackAlign;
1693   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1694                                  /*ByVal=*/true, Realign);
1695 }
1696 
1697 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1698   const Type *T = isSingleElementStruct(Ty, getContext());
1699   if (!T)
1700     T = Ty.getTypePtr();
1701 
1702   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1703     BuiltinType::Kind K = BT->getKind();
1704     if (K == BuiltinType::Float || K == BuiltinType::Double)
1705       return Float;
1706   }
1707   return Integer;
1708 }
1709 
1710 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1711   if (!IsSoftFloatABI) {
1712     Class C = classify(Ty);
1713     if (C == Float)
1714       return false;
1715   }
1716 
1717   unsigned Size = getContext().getTypeSize(Ty);
1718   unsigned SizeInRegs = (Size + 31) / 32;
1719 
1720   if (SizeInRegs == 0)
1721     return false;
1722 
1723   if (!IsMCUABI) {
1724     if (SizeInRegs > State.FreeRegs) {
1725       State.FreeRegs = 0;
1726       return false;
1727     }
1728   } else {
1729     // The MCU psABI allows passing parameters in-reg even if there are
1730     // earlier parameters that are passed on the stack. Also,
1731     // it does not allow passing >8-byte structs in-register,
1732     // even if there are 3 free registers available.
1733     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1734       return false;
1735   }
1736 
1737   State.FreeRegs -= SizeInRegs;
1738   return true;
1739 }
1740 
1741 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1742                                              bool &InReg,
1743                                              bool &NeedsPadding) const {
1744   // On Windows, aggregates other than HFAs are never passed in registers, and
1745   // they do not consume register slots. Homogenous floating-point aggregates
1746   // (HFAs) have already been dealt with at this point.
1747   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1748     return false;
1749 
1750   NeedsPadding = false;
1751   InReg = !IsMCUABI;
1752 
1753   if (!updateFreeRegs(Ty, State))
1754     return false;
1755 
1756   if (IsMCUABI)
1757     return true;
1758 
1759   if (State.CC == llvm::CallingConv::X86_FastCall ||
1760       State.CC == llvm::CallingConv::X86_VectorCall ||
1761       State.CC == llvm::CallingConv::X86_RegCall) {
1762     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1763       NeedsPadding = true;
1764 
1765     return false;
1766   }
1767 
1768   return true;
1769 }
1770 
1771 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1772   if (!updateFreeRegs(Ty, State))
1773     return false;
1774 
1775   if (IsMCUABI)
1776     return false;
1777 
1778   if (State.CC == llvm::CallingConv::X86_FastCall ||
1779       State.CC == llvm::CallingConv::X86_VectorCall ||
1780       State.CC == llvm::CallingConv::X86_RegCall) {
1781     if (getContext().getTypeSize(Ty) > 32)
1782       return false;
1783 
1784     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1785         Ty->isReferenceType());
1786   }
1787 
1788   return true;
1789 }
1790 
1791 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1792   // Vectorcall x86 works subtly different than in x64, so the format is
1793   // a bit different than the x64 version.  First, all vector types (not HVAs)
1794   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1795   // This differs from the x64 implementation, where the first 6 by INDEX get
1796   // registers.
1797   // In the second pass over the arguments, HVAs are passed in the remaining
1798   // vector registers if possible, or indirectly by address. The address will be
1799   // passed in ECX/EDX if available. Any other arguments are passed according to
1800   // the usual fastcall rules.
1801   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1802   for (int I = 0, E = Args.size(); I < E; ++I) {
1803     const Type *Base = nullptr;
1804     uint64_t NumElts = 0;
1805     const QualType &Ty = Args[I].type;
1806     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1807         isHomogeneousAggregate(Ty, Base, NumElts)) {
1808       if (State.FreeSSERegs >= NumElts) {
1809         State.FreeSSERegs -= NumElts;
1810         Args[I].info = ABIArgInfo::getDirectInReg();
1811         State.IsPreassigned.set(I);
1812       }
1813     }
1814   }
1815 }
1816 
1817 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1818                                                CCState &State) const {
1819   // FIXME: Set alignment on indirect arguments.
1820   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1821   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1822   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1823 
1824   Ty = useFirstFieldIfTransparentUnion(Ty);
1825   TypeInfo TI = getContext().getTypeInfo(Ty);
1826 
1827   // Check with the C++ ABI first.
1828   const RecordType *RT = Ty->getAs<RecordType>();
1829   if (RT) {
1830     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1831     if (RAA == CGCXXABI::RAA_Indirect) {
1832       return getIndirectResult(Ty, false, State);
1833     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1834       // The field index doesn't matter, we'll fix it up later.
1835       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1836     }
1837   }
1838 
1839   // Regcall uses the concept of a homogenous vector aggregate, similar
1840   // to other targets.
1841   const Type *Base = nullptr;
1842   uint64_t NumElts = 0;
1843   if ((IsRegCall || IsVectorCall) &&
1844       isHomogeneousAggregate(Ty, Base, NumElts)) {
1845     if (State.FreeSSERegs >= NumElts) {
1846       State.FreeSSERegs -= NumElts;
1847 
1848       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1849       // does.
1850       if (IsVectorCall)
1851         return getDirectX86Hva();
1852 
1853       if (Ty->isBuiltinType() || Ty->isVectorType())
1854         return ABIArgInfo::getDirect();
1855       return ABIArgInfo::getExpand();
1856     }
1857     return getIndirectResult(Ty, /*ByVal=*/false, State);
1858   }
1859 
1860   if (isAggregateTypeForABI(Ty)) {
1861     // Structures with flexible arrays are always indirect.
1862     // FIXME: This should not be byval!
1863     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1864       return getIndirectResult(Ty, true, State);
1865 
1866     // Ignore empty structs/unions on non-Windows.
1867     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1868       return ABIArgInfo::getIgnore();
1869 
1870     llvm::LLVMContext &LLVMContext = getVMContext();
1871     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1872     bool NeedsPadding = false;
1873     bool InReg;
1874     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1875       unsigned SizeInRegs = (TI.Width + 31) / 32;
1876       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1877       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1878       if (InReg)
1879         return ABIArgInfo::getDirectInReg(Result);
1880       else
1881         return ABIArgInfo::getDirect(Result);
1882     }
1883     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1884 
1885     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1886     // added in MSVC 2015.
1887     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1888       return getIndirectResult(Ty, /*ByVal=*/false, State);
1889 
1890     // Expand small (<= 128-bit) record types when we know that the stack layout
1891     // of those arguments will match the struct. This is important because the
1892     // LLVM backend isn't smart enough to remove byval, which inhibits many
1893     // optimizations.
1894     // Don't do this for the MCU if there are still free integer registers
1895     // (see X86_64 ABI for full explanation).
1896     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1897         canExpandIndirectArgument(Ty))
1898       return ABIArgInfo::getExpandWithPadding(
1899           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1900 
1901     return getIndirectResult(Ty, true, State);
1902   }
1903 
1904   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1905     // On Windows, vectors are passed directly if registers are available, or
1906     // indirectly if not. This avoids the need to align argument memory. Pass
1907     // user-defined vector types larger than 512 bits indirectly for simplicity.
1908     if (IsWin32StructABI) {
1909       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1910         --State.FreeSSERegs;
1911         return ABIArgInfo::getDirectInReg();
1912       }
1913       return getIndirectResult(Ty, /*ByVal=*/false, State);
1914     }
1915 
1916     // On Darwin, some vectors are passed in memory, we handle this by passing
1917     // it as an i8/i16/i32/i64.
1918     if (IsDarwinVectorABI) {
1919       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1920           (TI.Width == 64 && VT->getNumElements() == 1))
1921         return ABIArgInfo::getDirect(
1922             llvm::IntegerType::get(getVMContext(), TI.Width));
1923     }
1924 
1925     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1926       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1927 
1928     return ABIArgInfo::getDirect();
1929   }
1930 
1931 
1932   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1933     Ty = EnumTy->getDecl()->getIntegerType();
1934 
1935   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1936 
1937   if (isPromotableIntegerTypeForABI(Ty)) {
1938     if (InReg)
1939       return ABIArgInfo::getExtendInReg(Ty);
1940     return ABIArgInfo::getExtend(Ty);
1941   }
1942 
1943   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1944     if (EIT->getNumBits() <= 64) {
1945       if (InReg)
1946         return ABIArgInfo::getDirectInReg();
1947       return ABIArgInfo::getDirect();
1948     }
1949     return getIndirectResult(Ty, /*ByVal=*/false, State);
1950   }
1951 
1952   if (InReg)
1953     return ABIArgInfo::getDirectInReg();
1954   return ABIArgInfo::getDirect();
1955 }
1956 
1957 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1958   CCState State(FI);
1959   if (IsMCUABI)
1960     State.FreeRegs = 3;
1961   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1962     State.FreeRegs = 2;
1963     State.FreeSSERegs = 3;
1964   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1965     State.FreeRegs = 2;
1966     State.FreeSSERegs = 6;
1967   } else if (FI.getHasRegParm())
1968     State.FreeRegs = FI.getRegParm();
1969   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1970     State.FreeRegs = 5;
1971     State.FreeSSERegs = 8;
1972   } else if (IsWin32StructABI) {
1973     // Since MSVC 2015, the first three SSE vectors have been passed in
1974     // registers. The rest are passed indirectly.
1975     State.FreeRegs = DefaultNumRegisterParameters;
1976     State.FreeSSERegs = 3;
1977   } else
1978     State.FreeRegs = DefaultNumRegisterParameters;
1979 
1980   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1981     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1982   } else if (FI.getReturnInfo().isIndirect()) {
1983     // The C++ ABI is not aware of register usage, so we have to check if the
1984     // return value was sret and put it in a register ourselves if appropriate.
1985     if (State.FreeRegs) {
1986       --State.FreeRegs;  // The sret parameter consumes a register.
1987       if (!IsMCUABI)
1988         FI.getReturnInfo().setInReg(true);
1989     }
1990   }
1991 
1992   // The chain argument effectively gives us another free register.
1993   if (FI.isChainCall())
1994     ++State.FreeRegs;
1995 
1996   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1997   // arguments to XMM registers as available.
1998   if (State.CC == llvm::CallingConv::X86_VectorCall)
1999     runVectorCallFirstPass(FI, State);
2000 
2001   bool UsedInAlloca = false;
2002   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
2003   for (int I = 0, E = Args.size(); I < E; ++I) {
2004     // Skip arguments that have already been assigned.
2005     if (State.IsPreassigned.test(I))
2006       continue;
2007 
2008     Args[I].info = classifyArgumentType(Args[I].type, State);
2009     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
2010   }
2011 
2012   // If we needed to use inalloca for any argument, do a second pass and rewrite
2013   // all the memory arguments to use inalloca.
2014   if (UsedInAlloca)
2015     rewriteWithInAlloca(FI);
2016 }
2017 
2018 void
2019 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2020                                    CharUnits &StackOffset, ABIArgInfo &Info,
2021                                    QualType Type) const {
2022   // Arguments are always 4-byte-aligned.
2023   CharUnits WordSize = CharUnits::fromQuantity(4);
2024   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2025 
2026   // sret pointers and indirect things will require an extra pointer
2027   // indirection, unless they are byval. Most things are byval, and will not
2028   // require this indirection.
2029   bool IsIndirect = false;
2030   if (Info.isIndirect() && !Info.getIndirectByVal())
2031     IsIndirect = true;
2032   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2033   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2034   if (IsIndirect)
2035     LLTy = LLTy->getPointerTo(0);
2036   FrameFields.push_back(LLTy);
2037   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2038 
2039   // Insert padding bytes to respect alignment.
2040   CharUnits FieldEnd = StackOffset;
2041   StackOffset = FieldEnd.alignTo(WordSize);
2042   if (StackOffset != FieldEnd) {
2043     CharUnits NumBytes = StackOffset - FieldEnd;
2044     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2045     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2046     FrameFields.push_back(Ty);
2047   }
2048 }
2049 
2050 static bool isArgInAlloca(const ABIArgInfo &Info) {
2051   // Leave ignored and inreg arguments alone.
2052   switch (Info.getKind()) {
2053   case ABIArgInfo::InAlloca:
2054     return true;
2055   case ABIArgInfo::Ignore:
2056   case ABIArgInfo::IndirectAliased:
2057     return false;
2058   case ABIArgInfo::Indirect:
2059   case ABIArgInfo::Direct:
2060   case ABIArgInfo::Extend:
2061     return !Info.getInReg();
2062   case ABIArgInfo::Expand:
2063   case ABIArgInfo::CoerceAndExpand:
2064     // These are aggregate types which are never passed in registers when
2065     // inalloca is involved.
2066     return true;
2067   }
2068   llvm_unreachable("invalid enum");
2069 }
2070 
2071 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2072   assert(IsWin32StructABI && "inalloca only supported on win32");
2073 
2074   // Build a packed struct type for all of the arguments in memory.
2075   SmallVector<llvm::Type *, 6> FrameFields;
2076 
2077   // The stack alignment is always 4.
2078   CharUnits StackAlign = CharUnits::fromQuantity(4);
2079 
2080   CharUnits StackOffset;
2081   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2082 
2083   // Put 'this' into the struct before 'sret', if necessary.
2084   bool IsThisCall =
2085       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2086   ABIArgInfo &Ret = FI.getReturnInfo();
2087   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2088       isArgInAlloca(I->info)) {
2089     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2090     ++I;
2091   }
2092 
2093   // Put the sret parameter into the inalloca struct if it's in memory.
2094   if (Ret.isIndirect() && !Ret.getInReg()) {
2095     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2096     // On Windows, the hidden sret parameter is always returned in eax.
2097     Ret.setInAllocaSRet(IsWin32StructABI);
2098   }
2099 
2100   // Skip the 'this' parameter in ecx.
2101   if (IsThisCall)
2102     ++I;
2103 
2104   // Put arguments passed in memory into the struct.
2105   for (; I != E; ++I) {
2106     if (isArgInAlloca(I->info))
2107       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2108   }
2109 
2110   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2111                                         /*isPacked=*/true),
2112                   StackAlign);
2113 }
2114 
2115 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2116                                  Address VAListAddr, QualType Ty) const {
2117 
2118   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2119 
2120   // x86-32 changes the alignment of certain arguments on the stack.
2121   //
2122   // Just messing with TypeInfo like this works because we never pass
2123   // anything indirectly.
2124   TypeInfo.Align = CharUnits::fromQuantity(
2125                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2126 
2127   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2128                           TypeInfo, CharUnits::fromQuantity(4),
2129                           /*AllowHigherAlign*/ true);
2130 }
2131 
2132 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2133     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2134   assert(Triple.getArch() == llvm::Triple::x86);
2135 
2136   switch (Opts.getStructReturnConvention()) {
2137   case CodeGenOptions::SRCK_Default:
2138     break;
2139   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2140     return false;
2141   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2142     return true;
2143   }
2144 
2145   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2146     return true;
2147 
2148   switch (Triple.getOS()) {
2149   case llvm::Triple::DragonFly:
2150   case llvm::Triple::FreeBSD:
2151   case llvm::Triple::OpenBSD:
2152   case llvm::Triple::Win32:
2153     return true;
2154   default:
2155     return false;
2156   }
2157 }
2158 
2159 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2160                                  CodeGen::CodeGenModule &CGM) {
2161   if (!FD->hasAttr<AnyX86InterruptAttr>())
2162     return;
2163 
2164   llvm::Function *Fn = cast<llvm::Function>(GV);
2165   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2166   if (FD->getNumParams() == 0)
2167     return;
2168 
2169   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2170   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2171   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2172     Fn->getContext(), ByValTy);
2173   Fn->addParamAttr(0, NewAttr);
2174 }
2175 
2176 void X86_32TargetCodeGenInfo::setTargetAttributes(
2177     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2178   if (GV->isDeclaration())
2179     return;
2180   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2181     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2182       llvm::Function *Fn = cast<llvm::Function>(GV);
2183       Fn->addFnAttr("stackrealign");
2184     }
2185 
2186     addX86InterruptAttrs(FD, GV, CGM);
2187   }
2188 }
2189 
2190 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2191                                                CodeGen::CodeGenFunction &CGF,
2192                                                llvm::Value *Address) const {
2193   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2194 
2195   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2196 
2197   // 0-7 are the eight integer registers;  the order is different
2198   //   on Darwin (for EH), but the range is the same.
2199   // 8 is %eip.
2200   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2201 
2202   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2203     // 12-16 are st(0..4).  Not sure why we stop at 4.
2204     // These have size 16, which is sizeof(long double) on
2205     // platforms with 8-byte alignment for that type.
2206     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2207     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2208 
2209   } else {
2210     // 9 is %eflags, which doesn't get a size on Darwin for some
2211     // reason.
2212     Builder.CreateAlignedStore(
2213         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2214                                CharUnits::One());
2215 
2216     // 11-16 are st(0..5).  Not sure why we stop at 5.
2217     // These have size 12, which is sizeof(long double) on
2218     // platforms with 4-byte alignment for that type.
2219     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2220     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2221   }
2222 
2223   return false;
2224 }
2225 
2226 //===----------------------------------------------------------------------===//
2227 // X86-64 ABI Implementation
2228 //===----------------------------------------------------------------------===//
2229 
2230 
2231 namespace {
2232 /// The AVX ABI level for X86 targets.
2233 enum class X86AVXABILevel {
2234   None,
2235   AVX,
2236   AVX512
2237 };
2238 
2239 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2240 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2241   switch (AVXLevel) {
2242   case X86AVXABILevel::AVX512:
2243     return 512;
2244   case X86AVXABILevel::AVX:
2245     return 256;
2246   case X86AVXABILevel::None:
2247     return 128;
2248   }
2249   llvm_unreachable("Unknown AVXLevel");
2250 }
2251 
2252 /// X86_64ABIInfo - The X86_64 ABI information.
2253 class X86_64ABIInfo : public SwiftABIInfo {
2254   enum Class {
2255     Integer = 0,
2256     SSE,
2257     SSEUp,
2258     X87,
2259     X87Up,
2260     ComplexX87,
2261     NoClass,
2262     Memory
2263   };
2264 
2265   /// merge - Implement the X86_64 ABI merging algorithm.
2266   ///
2267   /// Merge an accumulating classification \arg Accum with a field
2268   /// classification \arg Field.
2269   ///
2270   /// \param Accum - The accumulating classification. This should
2271   /// always be either NoClass or the result of a previous merge
2272   /// call. In addition, this should never be Memory (the caller
2273   /// should just return Memory for the aggregate).
2274   static Class merge(Class Accum, Class Field);
2275 
2276   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2277   ///
2278   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2279   /// final MEMORY or SSE classes when necessary.
2280   ///
2281   /// \param AggregateSize - The size of the current aggregate in
2282   /// the classification process.
2283   ///
2284   /// \param Lo - The classification for the parts of the type
2285   /// residing in the low word of the containing object.
2286   ///
2287   /// \param Hi - The classification for the parts of the type
2288   /// residing in the higher words of the containing object.
2289   ///
2290   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2291 
2292   /// classify - Determine the x86_64 register classes in which the
2293   /// given type T should be passed.
2294   ///
2295   /// \param Lo - The classification for the parts of the type
2296   /// residing in the low word of the containing object.
2297   ///
2298   /// \param Hi - The classification for the parts of the type
2299   /// residing in the high word of the containing object.
2300   ///
2301   /// \param OffsetBase - The bit offset of this type in the
2302   /// containing object.  Some parameters are classified different
2303   /// depending on whether they straddle an eightbyte boundary.
2304   ///
2305   /// \param isNamedArg - Whether the argument in question is a "named"
2306   /// argument, as used in AMD64-ABI 3.5.7.
2307   ///
2308   /// \param IsRegCall - Whether the calling conversion is regcall.
2309   ///
2310   /// If a word is unused its result will be NoClass; if a type should
2311   /// be passed in Memory then at least the classification of \arg Lo
2312   /// will be Memory.
2313   ///
2314   /// The \arg Lo class will be NoClass iff the argument is ignored.
2315   ///
2316   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2317   /// also be ComplexX87.
2318   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2319                 bool isNamedArg, bool IsRegCall = false) const;
2320 
2321   llvm::Type *GetByteVectorType(QualType Ty) const;
2322   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2323                                  unsigned IROffset, QualType SourceTy,
2324                                  unsigned SourceOffset) const;
2325   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2326                                      unsigned IROffset, QualType SourceTy,
2327                                      unsigned SourceOffset) const;
2328 
2329   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2330   /// such that the argument will be returned in memory.
2331   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2332 
2333   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2334   /// such that the argument will be passed in memory.
2335   ///
2336   /// \param freeIntRegs - The number of free integer registers remaining
2337   /// available.
2338   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2339 
2340   ABIArgInfo classifyReturnType(QualType RetTy) const;
2341 
2342   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2343                                   unsigned &neededInt, unsigned &neededSSE,
2344                                   bool isNamedArg,
2345                                   bool IsRegCall = false) const;
2346 
2347   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2348                                        unsigned &NeededSSE,
2349                                        unsigned &MaxVectorWidth) const;
2350 
2351   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2352                                            unsigned &NeededSSE,
2353                                            unsigned &MaxVectorWidth) const;
2354 
2355   bool IsIllegalVectorType(QualType Ty) const;
2356 
2357   /// The 0.98 ABI revision clarified a lot of ambiguities,
2358   /// unfortunately in ways that were not always consistent with
2359   /// certain previous compilers.  In particular, platforms which
2360   /// required strict binary compatibility with older versions of GCC
2361   /// may need to exempt themselves.
2362   bool honorsRevision0_98() const {
2363     return !getTarget().getTriple().isOSDarwin();
2364   }
2365 
2366   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2367   /// classify it as INTEGER (for compatibility with older clang compilers).
2368   bool classifyIntegerMMXAsSSE() const {
2369     // Clang <= 3.8 did not do this.
2370     if (getContext().getLangOpts().getClangABICompat() <=
2371         LangOptions::ClangABI::Ver3_8)
2372       return false;
2373 
2374     const llvm::Triple &Triple = getTarget().getTriple();
2375     if (Triple.isOSDarwin() || Triple.isPS())
2376       return false;
2377     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2378       return false;
2379     return true;
2380   }
2381 
2382   // GCC classifies vectors of __int128 as memory.
2383   bool passInt128VectorsInMem() const {
2384     // Clang <= 9.0 did not do this.
2385     if (getContext().getLangOpts().getClangABICompat() <=
2386         LangOptions::ClangABI::Ver9)
2387       return false;
2388 
2389     const llvm::Triple &T = getTarget().getTriple();
2390     return T.isOSLinux() || T.isOSNetBSD();
2391   }
2392 
2393   X86AVXABILevel AVXLevel;
2394   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2395   // 64-bit hardware.
2396   bool Has64BitPointers;
2397 
2398 public:
2399   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2400       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2401       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2402   }
2403 
2404   bool isPassedUsingAVXType(QualType type) const {
2405     unsigned neededInt, neededSSE;
2406     // The freeIntRegs argument doesn't matter here.
2407     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2408                                            /*isNamedArg*/true);
2409     if (info.isDirect()) {
2410       llvm::Type *ty = info.getCoerceToType();
2411       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2412         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2413     }
2414     return false;
2415   }
2416 
2417   void computeInfo(CGFunctionInfo &FI) const override;
2418 
2419   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2420                     QualType Ty) const override;
2421   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2422                       QualType Ty) const override;
2423 
2424   bool has64BitPointers() const {
2425     return Has64BitPointers;
2426   }
2427 
2428   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2429                                     bool asReturnValue) const override {
2430     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2431   }
2432   bool isSwiftErrorInRegister() const override {
2433     return true;
2434   }
2435 };
2436 
2437 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2438 class WinX86_64ABIInfo : public SwiftABIInfo {
2439 public:
2440   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2441       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2442         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2443 
2444   void computeInfo(CGFunctionInfo &FI) const override;
2445 
2446   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2447                     QualType Ty) const override;
2448 
2449   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2450     // FIXME: Assumes vectorcall is in use.
2451     return isX86VectorTypeForVectorCall(getContext(), Ty);
2452   }
2453 
2454   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2455                                          uint64_t NumMembers) const override {
2456     // FIXME: Assumes vectorcall is in use.
2457     return isX86VectorCallAggregateSmallEnough(NumMembers);
2458   }
2459 
2460   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2461                                     bool asReturnValue) const override {
2462     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2463   }
2464 
2465   bool isSwiftErrorInRegister() const override {
2466     return true;
2467   }
2468 
2469 private:
2470   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2471                       bool IsVectorCall, bool IsRegCall) const;
2472   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2473                                            const ABIArgInfo &current) const;
2474 
2475   X86AVXABILevel AVXLevel;
2476 
2477   bool IsMingw64;
2478 };
2479 
2480 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2481 public:
2482   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2483       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2484 
2485   const X86_64ABIInfo &getABIInfo() const {
2486     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2487   }
2488 
2489   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2490   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2491   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2492 
2493   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2494     return 7;
2495   }
2496 
2497   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2498                                llvm::Value *Address) const override {
2499     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2500 
2501     // 0-15 are the 16 integer registers.
2502     // 16 is %rip.
2503     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2504     return false;
2505   }
2506 
2507   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2508                                   StringRef Constraint,
2509                                   llvm::Type* Ty) const override {
2510     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2511   }
2512 
2513   bool isNoProtoCallVariadic(const CallArgList &args,
2514                              const FunctionNoProtoType *fnType) const override {
2515     // The default CC on x86-64 sets %al to the number of SSA
2516     // registers used, and GCC sets this when calling an unprototyped
2517     // function, so we override the default behavior.  However, don't do
2518     // that when AVX types are involved: the ABI explicitly states it is
2519     // undefined, and it doesn't work in practice because of how the ABI
2520     // defines varargs anyway.
2521     if (fnType->getCallConv() == CC_C) {
2522       bool HasAVXType = false;
2523       for (CallArgList::const_iterator
2524              it = args.begin(), ie = args.end(); it != ie; ++it) {
2525         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2526           HasAVXType = true;
2527           break;
2528         }
2529       }
2530 
2531       if (!HasAVXType)
2532         return true;
2533     }
2534 
2535     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2536   }
2537 
2538   llvm::Constant *
2539   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2540     unsigned Sig = (0xeb << 0) | // jmp rel8
2541                    (0x06 << 8) | //           .+0x08
2542                    ('v' << 16) |
2543                    ('2' << 24);
2544     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2545   }
2546 
2547   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2548                            CodeGen::CodeGenModule &CGM) const override {
2549     if (GV->isDeclaration())
2550       return;
2551     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2552       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2553         llvm::Function *Fn = cast<llvm::Function>(GV);
2554         Fn->addFnAttr("stackrealign");
2555       }
2556 
2557       addX86InterruptAttrs(FD, GV, CGM);
2558     }
2559   }
2560 
2561   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2562                             const FunctionDecl *Caller,
2563                             const FunctionDecl *Callee,
2564                             const CallArgList &Args) const override;
2565 };
2566 
2567 static void initFeatureMaps(const ASTContext &Ctx,
2568                             llvm::StringMap<bool> &CallerMap,
2569                             const FunctionDecl *Caller,
2570                             llvm::StringMap<bool> &CalleeMap,
2571                             const FunctionDecl *Callee) {
2572   if (CalleeMap.empty() && CallerMap.empty()) {
2573     // The caller is potentially nullptr in the case where the call isn't in a
2574     // function.  In this case, the getFunctionFeatureMap ensures we just get
2575     // the TU level setting (since it cannot be modified by 'target'..
2576     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2577     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2578   }
2579 }
2580 
2581 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2582                                  SourceLocation CallLoc,
2583                                  const llvm::StringMap<bool> &CallerMap,
2584                                  const llvm::StringMap<bool> &CalleeMap,
2585                                  QualType Ty, StringRef Feature,
2586                                  bool IsArgument) {
2587   bool CallerHasFeat = CallerMap.lookup(Feature);
2588   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2589   if (!CallerHasFeat && !CalleeHasFeat)
2590     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2591            << IsArgument << Ty << Feature;
2592 
2593   // Mixing calling conventions here is very clearly an error.
2594   if (!CallerHasFeat || !CalleeHasFeat)
2595     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2596            << IsArgument << Ty << Feature;
2597 
2598   // Else, both caller and callee have the required feature, so there is no need
2599   // to diagnose.
2600   return false;
2601 }
2602 
2603 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2604                           SourceLocation CallLoc,
2605                           const llvm::StringMap<bool> &CallerMap,
2606                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2607                           bool IsArgument) {
2608   uint64_t Size = Ctx.getTypeSize(Ty);
2609   if (Size > 256)
2610     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2611                                 "avx512f", IsArgument);
2612 
2613   if (Size > 128)
2614     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2615                                 IsArgument);
2616 
2617   return false;
2618 }
2619 
2620 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2621     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2622     const FunctionDecl *Callee, const CallArgList &Args) const {
2623   llvm::StringMap<bool> CallerMap;
2624   llvm::StringMap<bool> CalleeMap;
2625   unsigned ArgIndex = 0;
2626 
2627   // We need to loop through the actual call arguments rather than the the
2628   // function's parameters, in case this variadic.
2629   for (const CallArg &Arg : Args) {
2630     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2631     // additionally changes how vectors >256 in size are passed. Like GCC, we
2632     // warn when a function is called with an argument where this will change.
2633     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2634     // the caller and callee features are mismatched.
2635     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2636     // change its ABI with attribute-target after this call.
2637     if (Arg.getType()->isVectorType() &&
2638         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2639       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2640       QualType Ty = Arg.getType();
2641       // The CallArg seems to have desugared the type already, so for clearer
2642       // diagnostics, replace it with the type in the FunctionDecl if possible.
2643       if (ArgIndex < Callee->getNumParams())
2644         Ty = Callee->getParamDecl(ArgIndex)->getType();
2645 
2646       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2647                         CalleeMap, Ty, /*IsArgument*/ true))
2648         return;
2649     }
2650     ++ArgIndex;
2651   }
2652 
2653   // Check return always, as we don't have a good way of knowing in codegen
2654   // whether this value is used, tail-called, etc.
2655   if (Callee->getReturnType()->isVectorType() &&
2656       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2657     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2658     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2659                   CalleeMap, Callee->getReturnType(),
2660                   /*IsArgument*/ false);
2661   }
2662 }
2663 
2664 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2665   // If the argument does not end in .lib, automatically add the suffix.
2666   // If the argument contains a space, enclose it in quotes.
2667   // This matches the behavior of MSVC.
2668   bool Quote = Lib.contains(' ');
2669   std::string ArgStr = Quote ? "\"" : "";
2670   ArgStr += Lib;
2671   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2672     ArgStr += ".lib";
2673   ArgStr += Quote ? "\"" : "";
2674   return ArgStr;
2675 }
2676 
2677 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2678 public:
2679   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2680         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2681         unsigned NumRegisterParameters)
2682     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2683         Win32StructABI, NumRegisterParameters, false) {}
2684 
2685   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2686                            CodeGen::CodeGenModule &CGM) const override;
2687 
2688   void getDependentLibraryOption(llvm::StringRef Lib,
2689                                  llvm::SmallString<24> &Opt) const override {
2690     Opt = "/DEFAULTLIB:";
2691     Opt += qualifyWindowsLibrary(Lib);
2692   }
2693 
2694   void getDetectMismatchOption(llvm::StringRef Name,
2695                                llvm::StringRef Value,
2696                                llvm::SmallString<32> &Opt) const override {
2697     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2698   }
2699 };
2700 
2701 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2702                                           CodeGen::CodeGenModule &CGM) {
2703   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2704 
2705     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2706       Fn->addFnAttr("stack-probe-size",
2707                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2708     if (CGM.getCodeGenOpts().NoStackArgProbe)
2709       Fn->addFnAttr("no-stack-arg-probe");
2710   }
2711 }
2712 
2713 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2714     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2715   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2716   if (GV->isDeclaration())
2717     return;
2718   addStackProbeTargetAttributes(D, GV, CGM);
2719 }
2720 
2721 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2722 public:
2723   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2724                              X86AVXABILevel AVXLevel)
2725       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2726 
2727   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2728                            CodeGen::CodeGenModule &CGM) const override;
2729 
2730   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2731     return 7;
2732   }
2733 
2734   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2735                                llvm::Value *Address) const override {
2736     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2737 
2738     // 0-15 are the 16 integer registers.
2739     // 16 is %rip.
2740     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2741     return false;
2742   }
2743 
2744   void getDependentLibraryOption(llvm::StringRef Lib,
2745                                  llvm::SmallString<24> &Opt) const override {
2746     Opt = "/DEFAULTLIB:";
2747     Opt += qualifyWindowsLibrary(Lib);
2748   }
2749 
2750   void getDetectMismatchOption(llvm::StringRef Name,
2751                                llvm::StringRef Value,
2752                                llvm::SmallString<32> &Opt) const override {
2753     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2754   }
2755 };
2756 
2757 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2758     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2759   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2760   if (GV->isDeclaration())
2761     return;
2762   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2763     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2764       llvm::Function *Fn = cast<llvm::Function>(GV);
2765       Fn->addFnAttr("stackrealign");
2766     }
2767 
2768     addX86InterruptAttrs(FD, GV, CGM);
2769   }
2770 
2771   addStackProbeTargetAttributes(D, GV, CGM);
2772 }
2773 }
2774 
2775 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2776                               Class &Hi) const {
2777   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2778   //
2779   // (a) If one of the classes is Memory, the whole argument is passed in
2780   //     memory.
2781   //
2782   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2783   //     memory.
2784   //
2785   // (c) If the size of the aggregate exceeds two eightbytes and the first
2786   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2787   //     argument is passed in memory. NOTE: This is necessary to keep the
2788   //     ABI working for processors that don't support the __m256 type.
2789   //
2790   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2791   //
2792   // Some of these are enforced by the merging logic.  Others can arise
2793   // only with unions; for example:
2794   //   union { _Complex double; unsigned; }
2795   //
2796   // Note that clauses (b) and (c) were added in 0.98.
2797   //
2798   if (Hi == Memory)
2799     Lo = Memory;
2800   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2801     Lo = Memory;
2802   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2803     Lo = Memory;
2804   if (Hi == SSEUp && Lo != SSE)
2805     Hi = SSE;
2806 }
2807 
2808 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2809   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2810   // classified recursively so that always two fields are
2811   // considered. The resulting class is calculated according to
2812   // the classes of the fields in the eightbyte:
2813   //
2814   // (a) If both classes are equal, this is the resulting class.
2815   //
2816   // (b) If one of the classes is NO_CLASS, the resulting class is
2817   // the other class.
2818   //
2819   // (c) If one of the classes is MEMORY, the result is the MEMORY
2820   // class.
2821   //
2822   // (d) If one of the classes is INTEGER, the result is the
2823   // INTEGER.
2824   //
2825   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2826   // MEMORY is used as class.
2827   //
2828   // (f) Otherwise class SSE is used.
2829 
2830   // Accum should never be memory (we should have returned) or
2831   // ComplexX87 (because this cannot be passed in a structure).
2832   assert((Accum != Memory && Accum != ComplexX87) &&
2833          "Invalid accumulated classification during merge.");
2834   if (Accum == Field || Field == NoClass)
2835     return Accum;
2836   if (Field == Memory)
2837     return Memory;
2838   if (Accum == NoClass)
2839     return Field;
2840   if (Accum == Integer || Field == Integer)
2841     return Integer;
2842   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2843       Accum == X87 || Accum == X87Up)
2844     return Memory;
2845   return SSE;
2846 }
2847 
2848 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
2849                              Class &Hi, bool isNamedArg, bool IsRegCall) const {
2850   // FIXME: This code can be simplified by introducing a simple value class for
2851   // Class pairs with appropriate constructor methods for the various
2852   // situations.
2853 
2854   // FIXME: Some of the split computations are wrong; unaligned vectors
2855   // shouldn't be passed in registers for example, so there is no chance they
2856   // can straddle an eightbyte. Verify & simplify.
2857 
2858   Lo = Hi = NoClass;
2859 
2860   Class &Current = OffsetBase < 64 ? Lo : Hi;
2861   Current = Memory;
2862 
2863   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2864     BuiltinType::Kind k = BT->getKind();
2865 
2866     if (k == BuiltinType::Void) {
2867       Current = NoClass;
2868     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2869       Lo = Integer;
2870       Hi = Integer;
2871     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2872       Current = Integer;
2873     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2874                k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
2875       Current = SSE;
2876     } else if (k == BuiltinType::LongDouble) {
2877       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2878       if (LDF == &llvm::APFloat::IEEEquad()) {
2879         Lo = SSE;
2880         Hi = SSEUp;
2881       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2882         Lo = X87;
2883         Hi = X87Up;
2884       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2885         Current = SSE;
2886       } else
2887         llvm_unreachable("unexpected long double representation!");
2888     }
2889     // FIXME: _Decimal32 and _Decimal64 are SSE.
2890     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2891     return;
2892   }
2893 
2894   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2895     // Classify the underlying integer type.
2896     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2897     return;
2898   }
2899 
2900   if (Ty->hasPointerRepresentation()) {
2901     Current = Integer;
2902     return;
2903   }
2904 
2905   if (Ty->isMemberPointerType()) {
2906     if (Ty->isMemberFunctionPointerType()) {
2907       if (Has64BitPointers) {
2908         // If Has64BitPointers, this is an {i64, i64}, so classify both
2909         // Lo and Hi now.
2910         Lo = Hi = Integer;
2911       } else {
2912         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2913         // straddles an eightbyte boundary, Hi should be classified as well.
2914         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2915         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2916         if (EB_FuncPtr != EB_ThisAdj) {
2917           Lo = Hi = Integer;
2918         } else {
2919           Current = Integer;
2920         }
2921       }
2922     } else {
2923       Current = Integer;
2924     }
2925     return;
2926   }
2927 
2928   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2929     uint64_t Size = getContext().getTypeSize(VT);
2930     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2931       // gcc passes the following as integer:
2932       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2933       // 2 bytes - <2 x char>, <1 x short>
2934       // 1 byte  - <1 x char>
2935       Current = Integer;
2936 
2937       // If this type crosses an eightbyte boundary, it should be
2938       // split.
2939       uint64_t EB_Lo = (OffsetBase) / 64;
2940       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2941       if (EB_Lo != EB_Hi)
2942         Hi = Lo;
2943     } else if (Size == 64) {
2944       QualType ElementType = VT->getElementType();
2945 
2946       // gcc passes <1 x double> in memory. :(
2947       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2948         return;
2949 
2950       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2951       // pass them as integer.  For platforms where clang is the de facto
2952       // platform compiler, we must continue to use integer.
2953       if (!classifyIntegerMMXAsSSE() &&
2954           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2955            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2956            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2957            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2958         Current = Integer;
2959       else
2960         Current = SSE;
2961 
2962       // If this type crosses an eightbyte boundary, it should be
2963       // split.
2964       if (OffsetBase && OffsetBase != 64)
2965         Hi = Lo;
2966     } else if (Size == 128 ||
2967                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2968       QualType ElementType = VT->getElementType();
2969 
2970       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2971       if (passInt128VectorsInMem() && Size != 128 &&
2972           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2973            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2974         return;
2975 
2976       // Arguments of 256-bits are split into four eightbyte chunks. The
2977       // least significant one belongs to class SSE and all the others to class
2978       // SSEUP. The original Lo and Hi design considers that types can't be
2979       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2980       // This design isn't correct for 256-bits, but since there're no cases
2981       // where the upper parts would need to be inspected, avoid adding
2982       // complexity and just consider Hi to match the 64-256 part.
2983       //
2984       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2985       // registers if they are "named", i.e. not part of the "..." of a
2986       // variadic function.
2987       //
2988       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2989       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2990       Lo = SSE;
2991       Hi = SSEUp;
2992     }
2993     return;
2994   }
2995 
2996   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2997     QualType ET = getContext().getCanonicalType(CT->getElementType());
2998 
2999     uint64_t Size = getContext().getTypeSize(Ty);
3000     if (ET->isIntegralOrEnumerationType()) {
3001       if (Size <= 64)
3002         Current = Integer;
3003       else if (Size <= 128)
3004         Lo = Hi = Integer;
3005     } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
3006                ET->isBFloat16Type()) {
3007       Current = SSE;
3008     } else if (ET == getContext().DoubleTy) {
3009       Lo = Hi = SSE;
3010     } else if (ET == getContext().LongDoubleTy) {
3011       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3012       if (LDF == &llvm::APFloat::IEEEquad())
3013         Current = Memory;
3014       else if (LDF == &llvm::APFloat::x87DoubleExtended())
3015         Current = ComplexX87;
3016       else if (LDF == &llvm::APFloat::IEEEdouble())
3017         Lo = Hi = SSE;
3018       else
3019         llvm_unreachable("unexpected long double representation!");
3020     }
3021 
3022     // If this complex type crosses an eightbyte boundary then it
3023     // should be split.
3024     uint64_t EB_Real = (OffsetBase) / 64;
3025     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3026     if (Hi == NoClass && EB_Real != EB_Imag)
3027       Hi = Lo;
3028 
3029     return;
3030   }
3031 
3032   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3033     if (EITy->getNumBits() <= 64)
3034       Current = Integer;
3035     else if (EITy->getNumBits() <= 128)
3036       Lo = Hi = Integer;
3037     // Larger values need to get passed in memory.
3038     return;
3039   }
3040 
3041   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3042     // Arrays are treated like structures.
3043 
3044     uint64_t Size = getContext().getTypeSize(Ty);
3045 
3046     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3047     // than eight eightbytes, ..., it has class MEMORY.
3048     // regcall ABI doesn't have limitation to an object. The only limitation
3049     // is the free registers, which will be checked in computeInfo.
3050     if (!IsRegCall && Size > 512)
3051       return;
3052 
3053     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3054     // fields, it has class MEMORY.
3055     //
3056     // Only need to check alignment of array base.
3057     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3058       return;
3059 
3060     // Otherwise implement simplified merge. We could be smarter about
3061     // this, but it isn't worth it and would be harder to verify.
3062     Current = NoClass;
3063     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3064     uint64_t ArraySize = AT->getSize().getZExtValue();
3065 
3066     // The only case a 256-bit wide vector could be used is when the array
3067     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3068     // to work for sizes wider than 128, early check and fallback to memory.
3069     //
3070     if (Size > 128 &&
3071         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3072       return;
3073 
3074     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3075       Class FieldLo, FieldHi;
3076       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3077       Lo = merge(Lo, FieldLo);
3078       Hi = merge(Hi, FieldHi);
3079       if (Lo == Memory || Hi == Memory)
3080         break;
3081     }
3082 
3083     postMerge(Size, Lo, Hi);
3084     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3085     return;
3086   }
3087 
3088   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3089     uint64_t Size = getContext().getTypeSize(Ty);
3090 
3091     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3092     // than eight eightbytes, ..., it has class MEMORY.
3093     if (Size > 512)
3094       return;
3095 
3096     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3097     // copy constructor or a non-trivial destructor, it is passed by invisible
3098     // reference.
3099     if (getRecordArgABI(RT, getCXXABI()))
3100       return;
3101 
3102     const RecordDecl *RD = RT->getDecl();
3103 
3104     // Assume variable sized types are passed in memory.
3105     if (RD->hasFlexibleArrayMember())
3106       return;
3107 
3108     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3109 
3110     // Reset Lo class, this will be recomputed.
3111     Current = NoClass;
3112 
3113     // If this is a C++ record, classify the bases first.
3114     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3115       for (const auto &I : CXXRD->bases()) {
3116         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3117                "Unexpected base class!");
3118         const auto *Base =
3119             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3120 
3121         // Classify this field.
3122         //
3123         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3124         // single eightbyte, each is classified separately. Each eightbyte gets
3125         // initialized to class NO_CLASS.
3126         Class FieldLo, FieldHi;
3127         uint64_t Offset =
3128           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3129         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3130         Lo = merge(Lo, FieldLo);
3131         Hi = merge(Hi, FieldHi);
3132         if (Lo == Memory || Hi == Memory) {
3133           postMerge(Size, Lo, Hi);
3134           return;
3135         }
3136       }
3137     }
3138 
3139     // Classify the fields one at a time, merging the results.
3140     unsigned idx = 0;
3141     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3142                                 LangOptions::ClangABI::Ver11 ||
3143                             getContext().getTargetInfo().getTriple().isPS();
3144     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3145 
3146     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3147            i != e; ++i, ++idx) {
3148       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3149       bool BitField = i->isBitField();
3150 
3151       // Ignore padding bit-fields.
3152       if (BitField && i->isUnnamedBitfield())
3153         continue;
3154 
3155       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3156       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3157       //
3158       // The only case a 256-bit or a 512-bit wide vector could be used is when
3159       // the struct contains a single 256-bit or 512-bit element. Early check
3160       // and fallback to memory.
3161       //
3162       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3163       // than 128.
3164       if (Size > 128 &&
3165           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3166            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3167         Lo = Memory;
3168         postMerge(Size, Lo, Hi);
3169         return;
3170       }
3171       // Note, skip this test for bit-fields, see below.
3172       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3173         Lo = Memory;
3174         postMerge(Size, Lo, Hi);
3175         return;
3176       }
3177 
3178       // Classify this field.
3179       //
3180       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3181       // exceeds a single eightbyte, each is classified
3182       // separately. Each eightbyte gets initialized to class
3183       // NO_CLASS.
3184       Class FieldLo, FieldHi;
3185 
3186       // Bit-fields require special handling, they do not force the
3187       // structure to be passed in memory even if unaligned, and
3188       // therefore they can straddle an eightbyte.
3189       if (BitField) {
3190         assert(!i->isUnnamedBitfield());
3191         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3192         uint64_t Size = i->getBitWidthValue(getContext());
3193 
3194         uint64_t EB_Lo = Offset / 64;
3195         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3196 
3197         if (EB_Lo) {
3198           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3199           FieldLo = NoClass;
3200           FieldHi = Integer;
3201         } else {
3202           FieldLo = Integer;
3203           FieldHi = EB_Hi ? Integer : NoClass;
3204         }
3205       } else
3206         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3207       Lo = merge(Lo, FieldLo);
3208       Hi = merge(Hi, FieldHi);
3209       if (Lo == Memory || Hi == Memory)
3210         break;
3211     }
3212 
3213     postMerge(Size, Lo, Hi);
3214   }
3215 }
3216 
3217 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3218   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3219   // place naturally.
3220   if (!isAggregateTypeForABI(Ty)) {
3221     // Treat an enum type as its underlying type.
3222     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3223       Ty = EnumTy->getDecl()->getIntegerType();
3224 
3225     if (Ty->isBitIntType())
3226       return getNaturalAlignIndirect(Ty);
3227 
3228     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3229                                               : ABIArgInfo::getDirect());
3230   }
3231 
3232   return getNaturalAlignIndirect(Ty);
3233 }
3234 
3235 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3236   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3237     uint64_t Size = getContext().getTypeSize(VecTy);
3238     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3239     if (Size <= 64 || Size > LargestVector)
3240       return true;
3241     QualType EltTy = VecTy->getElementType();
3242     if (passInt128VectorsInMem() &&
3243         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3244          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3245       return true;
3246   }
3247 
3248   return false;
3249 }
3250 
3251 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3252                                             unsigned freeIntRegs) const {
3253   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3254   // place naturally.
3255   //
3256   // This assumption is optimistic, as there could be free registers available
3257   // when we need to pass this argument in memory, and LLVM could try to pass
3258   // the argument in the free register. This does not seem to happen currently,
3259   // but this code would be much safer if we could mark the argument with
3260   // 'onstack'. See PR12193.
3261   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3262       !Ty->isBitIntType()) {
3263     // Treat an enum type as its underlying type.
3264     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3265       Ty = EnumTy->getDecl()->getIntegerType();
3266 
3267     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3268                                               : ABIArgInfo::getDirect());
3269   }
3270 
3271   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3272     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3273 
3274   // Compute the byval alignment. We specify the alignment of the byval in all
3275   // cases so that the mid-level optimizer knows the alignment of the byval.
3276   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3277 
3278   // Attempt to avoid passing indirect results using byval when possible. This
3279   // is important for good codegen.
3280   //
3281   // We do this by coercing the value into a scalar type which the backend can
3282   // handle naturally (i.e., without using byval).
3283   //
3284   // For simplicity, we currently only do this when we have exhausted all of the
3285   // free integer registers. Doing this when there are free integer registers
3286   // would require more care, as we would have to ensure that the coerced value
3287   // did not claim the unused register. That would require either reording the
3288   // arguments to the function (so that any subsequent inreg values came first),
3289   // or only doing this optimization when there were no following arguments that
3290   // might be inreg.
3291   //
3292   // We currently expect it to be rare (particularly in well written code) for
3293   // arguments to be passed on the stack when there are still free integer
3294   // registers available (this would typically imply large structs being passed
3295   // by value), so this seems like a fair tradeoff for now.
3296   //
3297   // We can revisit this if the backend grows support for 'onstack' parameter
3298   // attributes. See PR12193.
3299   if (freeIntRegs == 0) {
3300     uint64_t Size = getContext().getTypeSize(Ty);
3301 
3302     // If this type fits in an eightbyte, coerce it into the matching integral
3303     // type, which will end up on the stack (with alignment 8).
3304     if (Align == 8 && Size <= 64)
3305       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3306                                                           Size));
3307   }
3308 
3309   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3310 }
3311 
3312 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3313 /// register. Pick an LLVM IR type that will be passed as a vector register.
3314 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3315   // Wrapper structs/arrays that only contain vectors are passed just like
3316   // vectors; strip them off if present.
3317   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3318     Ty = QualType(InnerTy, 0);
3319 
3320   llvm::Type *IRType = CGT.ConvertType(Ty);
3321   if (isa<llvm::VectorType>(IRType)) {
3322     // Don't pass vXi128 vectors in their native type, the backend can't
3323     // legalize them.
3324     if (passInt128VectorsInMem() &&
3325         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3326       // Use a vXi64 vector.
3327       uint64_t Size = getContext().getTypeSize(Ty);
3328       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3329                                         Size / 64);
3330     }
3331 
3332     return IRType;
3333   }
3334 
3335   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3336     return IRType;
3337 
3338   // We couldn't find the preferred IR vector type for 'Ty'.
3339   uint64_t Size = getContext().getTypeSize(Ty);
3340   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3341 
3342 
3343   // Return a LLVM IR vector type based on the size of 'Ty'.
3344   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3345                                     Size / 64);
3346 }
3347 
3348 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3349 /// is known to either be off the end of the specified type or being in
3350 /// alignment padding.  The user type specified is known to be at most 128 bits
3351 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3352 /// classification that put one of the two halves in the INTEGER class.
3353 ///
3354 /// It is conservatively correct to return false.
3355 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3356                                   unsigned EndBit, ASTContext &Context) {
3357   // If the bytes being queried are off the end of the type, there is no user
3358   // data hiding here.  This handles analysis of builtins, vectors and other
3359   // types that don't contain interesting padding.
3360   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3361   if (TySize <= StartBit)
3362     return true;
3363 
3364   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3365     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3366     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3367 
3368     // Check each element to see if the element overlaps with the queried range.
3369     for (unsigned i = 0; i != NumElts; ++i) {
3370       // If the element is after the span we care about, then we're done..
3371       unsigned EltOffset = i*EltSize;
3372       if (EltOffset >= EndBit) break;
3373 
3374       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3375       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3376                                  EndBit-EltOffset, Context))
3377         return false;
3378     }
3379     // If it overlaps no elements, then it is safe to process as padding.
3380     return true;
3381   }
3382 
3383   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3384     const RecordDecl *RD = RT->getDecl();
3385     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3386 
3387     // If this is a C++ record, check the bases first.
3388     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3389       for (const auto &I : CXXRD->bases()) {
3390         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3391                "Unexpected base class!");
3392         const auto *Base =
3393             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3394 
3395         // If the base is after the span we care about, ignore it.
3396         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3397         if (BaseOffset >= EndBit) continue;
3398 
3399         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3400         if (!BitsContainNoUserData(I.getType(), BaseStart,
3401                                    EndBit-BaseOffset, Context))
3402           return false;
3403       }
3404     }
3405 
3406     // Verify that no field has data that overlaps the region of interest.  Yes
3407     // this could be sped up a lot by being smarter about queried fields,
3408     // however we're only looking at structs up to 16 bytes, so we don't care
3409     // much.
3410     unsigned idx = 0;
3411     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3412          i != e; ++i, ++idx) {
3413       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3414 
3415       // If we found a field after the region we care about, then we're done.
3416       if (FieldOffset >= EndBit) break;
3417 
3418       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3419       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3420                                  Context))
3421         return false;
3422     }
3423 
3424     // If nothing in this record overlapped the area of interest, then we're
3425     // clean.
3426     return true;
3427   }
3428 
3429   return false;
3430 }
3431 
3432 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3433 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3434                                      const llvm::DataLayout &TD) {
3435   if (IROffset == 0 && IRType->isFloatingPointTy())
3436     return IRType;
3437 
3438   // If this is a struct, recurse into the field at the specified offset.
3439   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3440     if (!STy->getNumContainedTypes())
3441       return nullptr;
3442 
3443     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3444     unsigned Elt = SL->getElementContainingOffset(IROffset);
3445     IROffset -= SL->getElementOffset(Elt);
3446     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3447   }
3448 
3449   // If this is an array, recurse into the field at the specified offset.
3450   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3451     llvm::Type *EltTy = ATy->getElementType();
3452     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3453     IROffset -= IROffset / EltSize * EltSize;
3454     return getFPTypeAtOffset(EltTy, IROffset, TD);
3455   }
3456 
3457   return nullptr;
3458 }
3459 
3460 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3461 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3462 llvm::Type *X86_64ABIInfo::
3463 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3464                    QualType SourceTy, unsigned SourceOffset) const {
3465   const llvm::DataLayout &TD = getDataLayout();
3466   unsigned SourceSize =
3467       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3468   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3469   if (!T0 || T0->isDoubleTy())
3470     return llvm::Type::getDoubleTy(getVMContext());
3471 
3472   // Get the adjacent FP type.
3473   llvm::Type *T1 = nullptr;
3474   unsigned T0Size = TD.getTypeAllocSize(T0);
3475   if (SourceSize > T0Size)
3476       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3477   if (T1 == nullptr) {
3478     // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
3479     // to its alignment.
3480     if (T0->is16bitFPTy() && SourceSize > 4)
3481       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3482     // If we can't get a second FP type, return a simple half or float.
3483     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3484     // {float, i8} too.
3485     if (T1 == nullptr)
3486       return T0;
3487   }
3488 
3489   if (T0->isFloatTy() && T1->isFloatTy())
3490     return llvm::FixedVectorType::get(T0, 2);
3491 
3492   if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
3493     llvm::Type *T2 = nullptr;
3494     if (SourceSize > 4)
3495       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3496     if (T2 == nullptr)
3497       return llvm::FixedVectorType::get(T0, 2);
3498     return llvm::FixedVectorType::get(T0, 4);
3499   }
3500 
3501   if (T0->is16bitFPTy() || T1->is16bitFPTy())
3502     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3503 
3504   return llvm::Type::getDoubleTy(getVMContext());
3505 }
3506 
3507 
3508 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3509 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3510 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3511 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3512 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3513 /// etc).
3514 ///
3515 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3516 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3517 /// the 8-byte value references.  PrefType may be null.
3518 ///
3519 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3520 /// an offset into this that we're processing (which is always either 0 or 8).
3521 ///
3522 llvm::Type *X86_64ABIInfo::
3523 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3524                        QualType SourceTy, unsigned SourceOffset) const {
3525   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3526   // returning an 8-byte unit starting with it.  See if we can safely use it.
3527   if (IROffset == 0) {
3528     // Pointers and int64's always fill the 8-byte unit.
3529     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3530         IRType->isIntegerTy(64))
3531       return IRType;
3532 
3533     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3534     // goodness in the source type is just tail padding.  This is allowed to
3535     // kick in for struct {double,int} on the int, but not on
3536     // struct{double,int,int} because we wouldn't return the second int.  We
3537     // have to do this analysis on the source type because we can't depend on
3538     // unions being lowered a specific way etc.
3539     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3540         IRType->isIntegerTy(32) ||
3541         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3542       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3543           cast<llvm::IntegerType>(IRType)->getBitWidth();
3544 
3545       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3546                                 SourceOffset*8+64, getContext()))
3547         return IRType;
3548     }
3549   }
3550 
3551   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3552     // If this is a struct, recurse into the field at the specified offset.
3553     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3554     if (IROffset < SL->getSizeInBytes()) {
3555       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3556       IROffset -= SL->getElementOffset(FieldIdx);
3557 
3558       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3559                                     SourceTy, SourceOffset);
3560     }
3561   }
3562 
3563   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3564     llvm::Type *EltTy = ATy->getElementType();
3565     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3566     unsigned EltOffset = IROffset/EltSize*EltSize;
3567     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3568                                   SourceOffset);
3569   }
3570 
3571   // Okay, we don't have any better idea of what to pass, so we pass this in an
3572   // integer register that isn't too big to fit the rest of the struct.
3573   unsigned TySizeInBytes =
3574     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3575 
3576   assert(TySizeInBytes != SourceOffset && "Empty field?");
3577 
3578   // It is always safe to classify this as an integer type up to i64 that
3579   // isn't larger than the structure.
3580   return llvm::IntegerType::get(getVMContext(),
3581                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3582 }
3583 
3584 
3585 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3586 /// be used as elements of a two register pair to pass or return, return a
3587 /// first class aggregate to represent them.  For example, if the low part of
3588 /// a by-value argument should be passed as i32* and the high part as float,
3589 /// return {i32*, float}.
3590 static llvm::Type *
3591 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3592                            const llvm::DataLayout &TD) {
3593   // In order to correctly satisfy the ABI, we need to the high part to start
3594   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3595   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3596   // the second element at offset 8.  Check for this:
3597   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3598   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3599   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3600   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3601 
3602   // To handle this, we have to increase the size of the low part so that the
3603   // second element will start at an 8 byte offset.  We can't increase the size
3604   // of the second element because it might make us access off the end of the
3605   // struct.
3606   if (HiStart != 8) {
3607     // There are usually two sorts of types the ABI generation code can produce
3608     // for the low part of a pair that aren't 8 bytes in size: half, float or
3609     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3610     // NaCl).
3611     // Promote these to a larger type.
3612     if (Lo->isHalfTy() || Lo->isFloatTy())
3613       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3614     else {
3615       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3616              && "Invalid/unknown lo type");
3617       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3618     }
3619   }
3620 
3621   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3622 
3623   // Verify that the second element is at an 8-byte offset.
3624   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3625          "Invalid x86-64 argument pair!");
3626   return Result;
3627 }
3628 
3629 ABIArgInfo X86_64ABIInfo::
3630 classifyReturnType(QualType RetTy) const {
3631   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3632   // classification algorithm.
3633   X86_64ABIInfo::Class Lo, Hi;
3634   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3635 
3636   // Check some invariants.
3637   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3638   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3639 
3640   llvm::Type *ResType = nullptr;
3641   switch (Lo) {
3642   case NoClass:
3643     if (Hi == NoClass)
3644       return ABIArgInfo::getIgnore();
3645     // If the low part is just padding, it takes no register, leave ResType
3646     // null.
3647     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3648            "Unknown missing lo part");
3649     break;
3650 
3651   case SSEUp:
3652   case X87Up:
3653     llvm_unreachable("Invalid classification for lo word.");
3654 
3655     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3656     // hidden argument.
3657   case Memory:
3658     return getIndirectReturnResult(RetTy);
3659 
3660     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3661     // available register of the sequence %rax, %rdx is used.
3662   case Integer:
3663     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3664 
3665     // If we have a sign or zero extended integer, make sure to return Extend
3666     // so that the parameter gets the right LLVM IR attributes.
3667     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3668       // Treat an enum type as its underlying type.
3669       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3670         RetTy = EnumTy->getDecl()->getIntegerType();
3671 
3672       if (RetTy->isIntegralOrEnumerationType() &&
3673           isPromotableIntegerTypeForABI(RetTy))
3674         return ABIArgInfo::getExtend(RetTy);
3675     }
3676     break;
3677 
3678     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3679     // available SSE register of the sequence %xmm0, %xmm1 is used.
3680   case SSE:
3681     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3682     break;
3683 
3684     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3685     // returned on the X87 stack in %st0 as 80-bit x87 number.
3686   case X87:
3687     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3688     break;
3689 
3690     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3691     // part of the value is returned in %st0 and the imaginary part in
3692     // %st1.
3693   case ComplexX87:
3694     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3695     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3696                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3697     break;
3698   }
3699 
3700   llvm::Type *HighPart = nullptr;
3701   switch (Hi) {
3702     // Memory was handled previously and X87 should
3703     // never occur as a hi class.
3704   case Memory:
3705   case X87:
3706     llvm_unreachable("Invalid classification for hi word.");
3707 
3708   case ComplexX87: // Previously handled.
3709   case NoClass:
3710     break;
3711 
3712   case Integer:
3713     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3714     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3715       return ABIArgInfo::getDirect(HighPart, 8);
3716     break;
3717   case SSE:
3718     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3719     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3720       return ABIArgInfo::getDirect(HighPart, 8);
3721     break;
3722 
3723     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3724     // is passed in the next available eightbyte chunk if the last used
3725     // vector register.
3726     //
3727     // SSEUP should always be preceded by SSE, just widen.
3728   case SSEUp:
3729     assert(Lo == SSE && "Unexpected SSEUp classification.");
3730     ResType = GetByteVectorType(RetTy);
3731     break;
3732 
3733     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3734     // returned together with the previous X87 value in %st0.
3735   case X87Up:
3736     // If X87Up is preceded by X87, we don't need to do
3737     // anything. However, in some cases with unions it may not be
3738     // preceded by X87. In such situations we follow gcc and pass the
3739     // extra bits in an SSE reg.
3740     if (Lo != X87) {
3741       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3742       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3743         return ABIArgInfo::getDirect(HighPart, 8);
3744     }
3745     break;
3746   }
3747 
3748   // If a high part was specified, merge it together with the low part.  It is
3749   // known to pass in the high eightbyte of the result.  We do this by forming a
3750   // first class struct aggregate with the high and low part: {low, high}
3751   if (HighPart)
3752     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3753 
3754   return ABIArgInfo::getDirect(ResType);
3755 }
3756 
3757 ABIArgInfo
3758 X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
3759                                     unsigned &neededInt, unsigned &neededSSE,
3760                                     bool isNamedArg, bool IsRegCall) const {
3761   Ty = useFirstFieldIfTransparentUnion(Ty);
3762 
3763   X86_64ABIInfo::Class Lo, Hi;
3764   classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
3765 
3766   // Check some invariants.
3767   // FIXME: Enforce these by construction.
3768   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3769   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3770 
3771   neededInt = 0;
3772   neededSSE = 0;
3773   llvm::Type *ResType = nullptr;
3774   switch (Lo) {
3775   case NoClass:
3776     if (Hi == NoClass)
3777       return ABIArgInfo::getIgnore();
3778     // If the low part is just padding, it takes no register, leave ResType
3779     // null.
3780     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3781            "Unknown missing lo part");
3782     break;
3783 
3784     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3785     // on the stack.
3786   case Memory:
3787 
3788     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3789     // COMPLEX_X87, it is passed in memory.
3790   case X87:
3791   case ComplexX87:
3792     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3793       ++neededInt;
3794     return getIndirectResult(Ty, freeIntRegs);
3795 
3796   case SSEUp:
3797   case X87Up:
3798     llvm_unreachable("Invalid classification for lo word.");
3799 
3800     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3801     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3802     // and %r9 is used.
3803   case Integer:
3804     ++neededInt;
3805 
3806     // Pick an 8-byte type based on the preferred type.
3807     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3808 
3809     // If we have a sign or zero extended integer, make sure to return Extend
3810     // so that the parameter gets the right LLVM IR attributes.
3811     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3812       // Treat an enum type as its underlying type.
3813       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3814         Ty = EnumTy->getDecl()->getIntegerType();
3815 
3816       if (Ty->isIntegralOrEnumerationType() &&
3817           isPromotableIntegerTypeForABI(Ty))
3818         return ABIArgInfo::getExtend(Ty);
3819     }
3820 
3821     break;
3822 
3823     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3824     // available SSE register is used, the registers are taken in the
3825     // order from %xmm0 to %xmm7.
3826   case SSE: {
3827     llvm::Type *IRType = CGT.ConvertType(Ty);
3828     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3829     ++neededSSE;
3830     break;
3831   }
3832   }
3833 
3834   llvm::Type *HighPart = nullptr;
3835   switch (Hi) {
3836     // Memory was handled previously, ComplexX87 and X87 should
3837     // never occur as hi classes, and X87Up must be preceded by X87,
3838     // which is passed in memory.
3839   case Memory:
3840   case X87:
3841   case ComplexX87:
3842     llvm_unreachable("Invalid classification for hi word.");
3843 
3844   case NoClass: break;
3845 
3846   case Integer:
3847     ++neededInt;
3848     // Pick an 8-byte type based on the preferred type.
3849     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3850 
3851     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3852       return ABIArgInfo::getDirect(HighPart, 8);
3853     break;
3854 
3855     // X87Up generally doesn't occur here (long double is passed in
3856     // memory), except in situations involving unions.
3857   case X87Up:
3858   case SSE:
3859     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3860 
3861     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3862       return ABIArgInfo::getDirect(HighPart, 8);
3863 
3864     ++neededSSE;
3865     break;
3866 
3867     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3868     // eightbyte is passed in the upper half of the last used SSE
3869     // register.  This only happens when 128-bit vectors are passed.
3870   case SSEUp:
3871     assert(Lo == SSE && "Unexpected SSEUp classification");
3872     ResType = GetByteVectorType(Ty);
3873     break;
3874   }
3875 
3876   // If a high part was specified, merge it together with the low part.  It is
3877   // known to pass in the high eightbyte of the result.  We do this by forming a
3878   // first class struct aggregate with the high and low part: {low, high}
3879   if (HighPart)
3880     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3881 
3882   return ABIArgInfo::getDirect(ResType);
3883 }
3884 
3885 ABIArgInfo
3886 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3887                                              unsigned &NeededSSE,
3888                                              unsigned &MaxVectorWidth) const {
3889   auto RT = Ty->getAs<RecordType>();
3890   assert(RT && "classifyRegCallStructType only valid with struct types");
3891 
3892   if (RT->getDecl()->hasFlexibleArrayMember())
3893     return getIndirectReturnResult(Ty);
3894 
3895   // Sum up bases
3896   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3897     if (CXXRD->isDynamicClass()) {
3898       NeededInt = NeededSSE = 0;
3899       return getIndirectReturnResult(Ty);
3900     }
3901 
3902     for (const auto &I : CXXRD->bases())
3903       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
3904                                         MaxVectorWidth)
3905               .isIndirect()) {
3906         NeededInt = NeededSSE = 0;
3907         return getIndirectReturnResult(Ty);
3908       }
3909   }
3910 
3911   // Sum up members
3912   for (const auto *FD : RT->getDecl()->fields()) {
3913     QualType MTy = FD->getType();
3914     if (MTy->isRecordType() && !MTy->isUnionType()) {
3915       if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
3916                                         MaxVectorWidth)
3917               .isIndirect()) {
3918         NeededInt = NeededSSE = 0;
3919         return getIndirectReturnResult(Ty);
3920       }
3921     } else {
3922       unsigned LocalNeededInt, LocalNeededSSE;
3923       if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
3924                                true, true)
3925               .isIndirect()) {
3926         NeededInt = NeededSSE = 0;
3927         return getIndirectReturnResult(Ty);
3928       }
3929       if (const auto *AT = getContext().getAsConstantArrayType(MTy))
3930         MTy = AT->getElementType();
3931       if (const auto *VT = MTy->getAs<VectorType>())
3932         if (getContext().getTypeSize(VT) > MaxVectorWidth)
3933           MaxVectorWidth = getContext().getTypeSize(VT);
3934       NeededInt += LocalNeededInt;
3935       NeededSSE += LocalNeededSSE;
3936     }
3937   }
3938 
3939   return ABIArgInfo::getDirect();
3940 }
3941 
3942 ABIArgInfo
3943 X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
3944                                          unsigned &NeededSSE,
3945                                          unsigned &MaxVectorWidth) const {
3946 
3947   NeededInt = 0;
3948   NeededSSE = 0;
3949   MaxVectorWidth = 0;
3950 
3951   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
3952                                        MaxVectorWidth);
3953 }
3954 
3955 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3956 
3957   const unsigned CallingConv = FI.getCallingConvention();
3958   // It is possible to force Win64 calling convention on any x86_64 target by
3959   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3960   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3961   if (CallingConv == llvm::CallingConv::Win64) {
3962     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3963     Win64ABIInfo.computeInfo(FI);
3964     return;
3965   }
3966 
3967   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3968 
3969   // Keep track of the number of assigned registers.
3970   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3971   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3972   unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
3973 
3974   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3975     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3976         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3977       FI.getReturnInfo() = classifyRegCallStructType(
3978           FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
3979       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3980         FreeIntRegs -= NeededInt;
3981         FreeSSERegs -= NeededSSE;
3982       } else {
3983         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3984       }
3985     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3986                getContext().getCanonicalType(FI.getReturnType()
3987                                                  ->getAs<ComplexType>()
3988                                                  ->getElementType()) ==
3989                    getContext().LongDoubleTy)
3990       // Complex Long Double Type is passed in Memory when Regcall
3991       // calling convention is used.
3992       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3993     else
3994       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3995   }
3996 
3997   // If the return value is indirect, then the hidden argument is consuming one
3998   // integer register.
3999   if (FI.getReturnInfo().isIndirect())
4000     --FreeIntRegs;
4001   else if (NeededSSE && MaxVectorWidth > 0)
4002     FI.setMaxVectorWidth(MaxVectorWidth);
4003 
4004   // The chain argument effectively gives us another free register.
4005   if (FI.isChainCall())
4006     ++FreeIntRegs;
4007 
4008   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
4009   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
4010   // get assigned (in left-to-right order) for passing as follows...
4011   unsigned ArgNo = 0;
4012   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4013        it != ie; ++it, ++ArgNo) {
4014     bool IsNamedArg = ArgNo < NumRequiredArgs;
4015 
4016     if (IsRegCall && it->type->isStructureOrClassType())
4017       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
4018                                            MaxVectorWidth);
4019     else
4020       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
4021                                       NeededSSE, IsNamedArg);
4022 
4023     // AMD64-ABI 3.2.3p3: If there are no registers available for any
4024     // eightbyte of an argument, the whole argument is passed on the
4025     // stack. If registers have already been assigned for some
4026     // eightbytes of such an argument, the assignments get reverted.
4027     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
4028       FreeIntRegs -= NeededInt;
4029       FreeSSERegs -= NeededSSE;
4030       if (MaxVectorWidth > FI.getMaxVectorWidth())
4031         FI.setMaxVectorWidth(MaxVectorWidth);
4032     } else {
4033       it->info = getIndirectResult(it->type, FreeIntRegs);
4034     }
4035   }
4036 }
4037 
4038 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4039                                          Address VAListAddr, QualType Ty) {
4040   Address overflow_arg_area_p =
4041       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4042   llvm::Value *overflow_arg_area =
4043     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4044 
4045   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4046   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4047   // It isn't stated explicitly in the standard, but in practice we use
4048   // alignment greater than 16 where necessary.
4049   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4050   if (Align > CharUnits::fromQuantity(8)) {
4051     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4052                                                       Align);
4053   }
4054 
4055   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4056   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4057   llvm::Value *Res =
4058     CGF.Builder.CreateBitCast(overflow_arg_area,
4059                               llvm::PointerType::getUnqual(LTy));
4060 
4061   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4062   // l->overflow_arg_area + sizeof(type).
4063   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4064   // an 8 byte boundary.
4065 
4066   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4067   llvm::Value *Offset =
4068       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4069   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4070                                             Offset, "overflow_arg_area.next");
4071   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4072 
4073   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4074   return Address(Res, LTy, Align);
4075 }
4076 
4077 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4078                                  QualType Ty) const {
4079   // Assume that va_list type is correct; should be pointer to LLVM type:
4080   // struct {
4081   //   i32 gp_offset;
4082   //   i32 fp_offset;
4083   //   i8* overflow_arg_area;
4084   //   i8* reg_save_area;
4085   // };
4086   unsigned neededInt, neededSSE;
4087 
4088   Ty = getContext().getCanonicalType(Ty);
4089   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4090                                        /*isNamedArg*/false);
4091 
4092   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4093   // in the registers. If not go to step 7.
4094   if (!neededInt && !neededSSE)
4095     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4096 
4097   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4098   // general purpose registers needed to pass type and num_fp to hold
4099   // the number of floating point registers needed.
4100 
4101   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4102   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4103   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4104   //
4105   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4106   // register save space).
4107 
4108   llvm::Value *InRegs = nullptr;
4109   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4110   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4111   if (neededInt) {
4112     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4113     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4114     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4115     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4116   }
4117 
4118   if (neededSSE) {
4119     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4120     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4121     llvm::Value *FitsInFP =
4122       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4123     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4124     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4125   }
4126 
4127   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4128   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4129   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4130   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4131 
4132   // Emit code to load the value if it was passed in registers.
4133 
4134   CGF.EmitBlock(InRegBlock);
4135 
4136   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4137   // an offset of l->gp_offset and/or l->fp_offset. This may require
4138   // copying to a temporary location in case the parameter is passed
4139   // in different register classes or requires an alignment greater
4140   // than 8 for general purpose registers and 16 for XMM registers.
4141   //
4142   // FIXME: This really results in shameful code when we end up needing to
4143   // collect arguments from different places; often what should result in a
4144   // simple assembling of a structure from scattered addresses has many more
4145   // loads than necessary. Can we clean this up?
4146   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4147   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4148       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4149 
4150   Address RegAddr = Address::invalid();
4151   if (neededInt && neededSSE) {
4152     // FIXME: Cleanup.
4153     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4154     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4155     Address Tmp = CGF.CreateMemTemp(Ty);
4156     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4157     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4158     llvm::Type *TyLo = ST->getElementType(0);
4159     llvm::Type *TyHi = ST->getElementType(1);
4160     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4161            "Unexpected ABI info for mixed regs");
4162     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4163     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4164     llvm::Value *GPAddr =
4165         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4166     llvm::Value *FPAddr =
4167         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4168     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4169     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4170 
4171     // Copy the first element.
4172     // FIXME: Our choice of alignment here and below is probably pessimistic.
4173     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4174         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4175         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4176     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4177 
4178     // Copy the second element.
4179     V = CGF.Builder.CreateAlignedLoad(
4180         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4181         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4182     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4183 
4184     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4185   } else if (neededInt) {
4186     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4187                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4188     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4189 
4190     // Copy to a temporary if necessary to ensure the appropriate alignment.
4191     auto TInfo = getContext().getTypeInfoInChars(Ty);
4192     uint64_t TySize = TInfo.Width.getQuantity();
4193     CharUnits TyAlign = TInfo.Align;
4194 
4195     // Copy into a temporary if the type is more aligned than the
4196     // register save area.
4197     if (TyAlign.getQuantity() > 8) {
4198       Address Tmp = CGF.CreateMemTemp(Ty);
4199       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4200       RegAddr = Tmp;
4201     }
4202 
4203   } else if (neededSSE == 1) {
4204     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4205                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4206     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4207   } else {
4208     assert(neededSSE == 2 && "Invalid number of needed registers!");
4209     // SSE registers are spaced 16 bytes apart in the register save
4210     // area, we need to collect the two eightbytes together.
4211     // The ABI isn't explicit about this, but it seems reasonable
4212     // to assume that the slots are 16-byte aligned, since the stack is
4213     // naturally 16-byte aligned and the prologue is expected to store
4214     // all the SSE registers to the RSA.
4215     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4216                                                       fp_offset),
4217                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4218     Address RegAddrHi =
4219       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4220                                              CharUnits::fromQuantity(16));
4221     llvm::Type *ST = AI.canHaveCoerceToType()
4222                          ? AI.getCoerceToType()
4223                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4224     llvm::Value *V;
4225     Address Tmp = CGF.CreateMemTemp(Ty);
4226     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4227     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4228         RegAddrLo, ST->getStructElementType(0)));
4229     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4230     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4231         RegAddrHi, ST->getStructElementType(1)));
4232     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4233 
4234     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4235   }
4236 
4237   // AMD64-ABI 3.5.7p5: Step 5. Set:
4238   // l->gp_offset = l->gp_offset + num_gp * 8
4239   // l->fp_offset = l->fp_offset + num_fp * 16.
4240   if (neededInt) {
4241     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4242     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4243                             gp_offset_p);
4244   }
4245   if (neededSSE) {
4246     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4247     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4248                             fp_offset_p);
4249   }
4250   CGF.EmitBranch(ContBlock);
4251 
4252   // Emit code to load the value if it was passed in memory.
4253 
4254   CGF.EmitBlock(InMemBlock);
4255   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4256 
4257   // Return the appropriate result.
4258 
4259   CGF.EmitBlock(ContBlock);
4260   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4261                                  "vaarg.addr");
4262   return ResAddr;
4263 }
4264 
4265 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4266                                    QualType Ty) const {
4267   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4268   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4269   uint64_t Width = getContext().getTypeSize(Ty);
4270   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4271 
4272   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4273                           CGF.getContext().getTypeInfoInChars(Ty),
4274                           CharUnits::fromQuantity(8),
4275                           /*allowHigherAlign*/ false);
4276 }
4277 
4278 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4279     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4280   const Type *Base = nullptr;
4281   uint64_t NumElts = 0;
4282 
4283   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4284       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4285     FreeSSERegs -= NumElts;
4286     return getDirectX86Hva();
4287   }
4288   return current;
4289 }
4290 
4291 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4292                                       bool IsReturnType, bool IsVectorCall,
4293                                       bool IsRegCall) const {
4294 
4295   if (Ty->isVoidType())
4296     return ABIArgInfo::getIgnore();
4297 
4298   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4299     Ty = EnumTy->getDecl()->getIntegerType();
4300 
4301   TypeInfo Info = getContext().getTypeInfo(Ty);
4302   uint64_t Width = Info.Width;
4303   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4304 
4305   const RecordType *RT = Ty->getAs<RecordType>();
4306   if (RT) {
4307     if (!IsReturnType) {
4308       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4309         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4310     }
4311 
4312     if (RT->getDecl()->hasFlexibleArrayMember())
4313       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4314 
4315   }
4316 
4317   const Type *Base = nullptr;
4318   uint64_t NumElts = 0;
4319   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4320   // other targets.
4321   if ((IsVectorCall || IsRegCall) &&
4322       isHomogeneousAggregate(Ty, Base, NumElts)) {
4323     if (IsRegCall) {
4324       if (FreeSSERegs >= NumElts) {
4325         FreeSSERegs -= NumElts;
4326         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4327           return ABIArgInfo::getDirect();
4328         return ABIArgInfo::getExpand();
4329       }
4330       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4331     } else if (IsVectorCall) {
4332       if (FreeSSERegs >= NumElts &&
4333           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4334         FreeSSERegs -= NumElts;
4335         return ABIArgInfo::getDirect();
4336       } else if (IsReturnType) {
4337         return ABIArgInfo::getExpand();
4338       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4339         // HVAs are delayed and reclassified in the 2nd step.
4340         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4341       }
4342     }
4343   }
4344 
4345   if (Ty->isMemberPointerType()) {
4346     // If the member pointer is represented by an LLVM int or ptr, pass it
4347     // directly.
4348     llvm::Type *LLTy = CGT.ConvertType(Ty);
4349     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4350       return ABIArgInfo::getDirect();
4351   }
4352 
4353   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4354     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4355     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4356     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4357       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4358 
4359     // Otherwise, coerce it to a small integer.
4360     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4361   }
4362 
4363   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4364     switch (BT->getKind()) {
4365     case BuiltinType::Bool:
4366       // Bool type is always extended to the ABI, other builtin types are not
4367       // extended.
4368       return ABIArgInfo::getExtend(Ty);
4369 
4370     case BuiltinType::LongDouble:
4371       // Mingw64 GCC uses the old 80 bit extended precision floating point
4372       // unit. It passes them indirectly through memory.
4373       if (IsMingw64) {
4374         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4375         if (LDF == &llvm::APFloat::x87DoubleExtended())
4376           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4377       }
4378       break;
4379 
4380     case BuiltinType::Int128:
4381     case BuiltinType::UInt128:
4382       // If it's a parameter type, the normal ABI rule is that arguments larger
4383       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4384       // even though it isn't particularly efficient.
4385       if (!IsReturnType)
4386         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4387 
4388       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4389       // Clang matches them for compatibility.
4390       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4391           llvm::Type::getInt64Ty(getVMContext()), 2));
4392 
4393     default:
4394       break;
4395     }
4396   }
4397 
4398   if (Ty->isBitIntType()) {
4399     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4400     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4401     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4402     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4403     // the power of 2.
4404     if (Width <= 64)
4405       return ABIArgInfo::getDirect();
4406     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4407   }
4408 
4409   return ABIArgInfo::getDirect();
4410 }
4411 
4412 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4413   const unsigned CC = FI.getCallingConvention();
4414   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4415   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4416 
4417   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4418   // classification rules.
4419   if (CC == llvm::CallingConv::X86_64_SysV) {
4420     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4421     SysVABIInfo.computeInfo(FI);
4422     return;
4423   }
4424 
4425   unsigned FreeSSERegs = 0;
4426   if (IsVectorCall) {
4427     // We can use up to 4 SSE return registers with vectorcall.
4428     FreeSSERegs = 4;
4429   } else if (IsRegCall) {
4430     // RegCall gives us 16 SSE registers.
4431     FreeSSERegs = 16;
4432   }
4433 
4434   if (!getCXXABI().classifyReturnType(FI))
4435     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4436                                   IsVectorCall, IsRegCall);
4437 
4438   if (IsVectorCall) {
4439     // We can use up to 6 SSE register parameters with vectorcall.
4440     FreeSSERegs = 6;
4441   } else if (IsRegCall) {
4442     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4443     FreeSSERegs = 16;
4444   }
4445 
4446   unsigned ArgNum = 0;
4447   unsigned ZeroSSERegs = 0;
4448   for (auto &I : FI.arguments()) {
4449     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4450     // XMM/YMM registers. After the sixth argument, pretend no vector
4451     // registers are left.
4452     unsigned *MaybeFreeSSERegs =
4453         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4454     I.info =
4455         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4456     ++ArgNum;
4457   }
4458 
4459   if (IsVectorCall) {
4460     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4461     // second pass.
4462     for (auto &I : FI.arguments())
4463       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4464   }
4465 }
4466 
4467 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4468                                     QualType Ty) const {
4469   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4470   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4471   uint64_t Width = getContext().getTypeSize(Ty);
4472   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4473 
4474   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4475                           CGF.getContext().getTypeInfoInChars(Ty),
4476                           CharUnits::fromQuantity(8),
4477                           /*allowHigherAlign*/ false);
4478 }
4479 
4480 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4481                                         llvm::Value *Address, bool Is64Bit,
4482                                         bool IsAIX) {
4483   // This is calculated from the LLVM and GCC tables and verified
4484   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4485 
4486   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4487 
4488   llvm::IntegerType *i8 = CGF.Int8Ty;
4489   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4490   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4491   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4492 
4493   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4494   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4495 
4496   // 32-63: fp0-31, the 8-byte floating-point registers
4497   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4498 
4499   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4500   // 64: mq
4501   // 65: lr
4502   // 66: ctr
4503   // 67: ap
4504   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4505 
4506   // 68-76 are various 4-byte special-purpose registers:
4507   // 68-75 cr0-7
4508   // 76: xer
4509   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4510 
4511   // 77-108: v0-31, the 16-byte vector registers
4512   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4513 
4514   // 109: vrsave
4515   // 110: vscr
4516   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4517 
4518   // AIX does not utilize the rest of the registers.
4519   if (IsAIX)
4520     return false;
4521 
4522   // 111: spe_acc
4523   // 112: spefscr
4524   // 113: sfp
4525   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4526 
4527   if (!Is64Bit)
4528     return false;
4529 
4530   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4531   // or above CPU.
4532   // 64-bit only registers:
4533   // 114: tfhar
4534   // 115: tfiar
4535   // 116: texasr
4536   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4537 
4538   return false;
4539 }
4540 
4541 // AIX
4542 namespace {
4543 /// AIXABIInfo - The AIX XCOFF ABI information.
4544 class AIXABIInfo : public ABIInfo {
4545   const bool Is64Bit;
4546   const unsigned PtrByteSize;
4547   CharUnits getParamTypeAlignment(QualType Ty) const;
4548 
4549 public:
4550   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4551       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4552 
4553   bool isPromotableTypeForABI(QualType Ty) const;
4554 
4555   ABIArgInfo classifyReturnType(QualType RetTy) const;
4556   ABIArgInfo classifyArgumentType(QualType Ty) const;
4557 
4558   void computeInfo(CGFunctionInfo &FI) const override {
4559     if (!getCXXABI().classifyReturnType(FI))
4560       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4561 
4562     for (auto &I : FI.arguments())
4563       I.info = classifyArgumentType(I.type);
4564   }
4565 
4566   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4567                     QualType Ty) const override;
4568 };
4569 
4570 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4571   const bool Is64Bit;
4572 
4573 public:
4574   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4575       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4576         Is64Bit(Is64Bit) {}
4577   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4578     return 1; // r1 is the dedicated stack pointer
4579   }
4580 
4581   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4582                                llvm::Value *Address) const override;
4583 };
4584 } // namespace
4585 
4586 // Return true if the ABI requires Ty to be passed sign- or zero-
4587 // extended to 32/64 bits.
4588 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4589   // Treat an enum type as its underlying type.
4590   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4591     Ty = EnumTy->getDecl()->getIntegerType();
4592 
4593   // Promotable integer types are required to be promoted by the ABI.
4594   if (Ty->isPromotableIntegerType())
4595     return true;
4596 
4597   if (!Is64Bit)
4598     return false;
4599 
4600   // For 64 bit mode, in addition to the usual promotable integer types, we also
4601   // need to extend all 32-bit types, since the ABI requires promotion to 64
4602   // bits.
4603   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4604     switch (BT->getKind()) {
4605     case BuiltinType::Int:
4606     case BuiltinType::UInt:
4607       return true;
4608     default:
4609       break;
4610     }
4611 
4612   return false;
4613 }
4614 
4615 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4616   if (RetTy->isAnyComplexType())
4617     return ABIArgInfo::getDirect();
4618 
4619   if (RetTy->isVectorType())
4620     return ABIArgInfo::getDirect();
4621 
4622   if (RetTy->isVoidType())
4623     return ABIArgInfo::getIgnore();
4624 
4625   if (isAggregateTypeForABI(RetTy))
4626     return getNaturalAlignIndirect(RetTy);
4627 
4628   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4629                                         : ABIArgInfo::getDirect());
4630 }
4631 
4632 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4633   Ty = useFirstFieldIfTransparentUnion(Ty);
4634 
4635   if (Ty->isAnyComplexType())
4636     return ABIArgInfo::getDirect();
4637 
4638   if (Ty->isVectorType())
4639     return ABIArgInfo::getDirect();
4640 
4641   if (isAggregateTypeForABI(Ty)) {
4642     // Records with non-trivial destructors/copy-constructors should not be
4643     // passed by value.
4644     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4645       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4646 
4647     CharUnits CCAlign = getParamTypeAlignment(Ty);
4648     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4649 
4650     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4651                                    /*Realign*/ TyAlign > CCAlign);
4652   }
4653 
4654   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4655                                      : ABIArgInfo::getDirect());
4656 }
4657 
4658 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4659   // Complex types are passed just like their elements.
4660   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4661     Ty = CTy->getElementType();
4662 
4663   if (Ty->isVectorType())
4664     return CharUnits::fromQuantity(16);
4665 
4666   // If the structure contains a vector type, the alignment is 16.
4667   if (isRecordWithSIMDVectorType(getContext(), Ty))
4668     return CharUnits::fromQuantity(16);
4669 
4670   return CharUnits::fromQuantity(PtrByteSize);
4671 }
4672 
4673 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4674                               QualType Ty) const {
4675 
4676   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4677   TypeInfo.Align = getParamTypeAlignment(Ty);
4678 
4679   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4680 
4681   // If we have a complex type and the base type is smaller than the register
4682   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4683   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4684   // Clang expects us to produce a pointer to a structure with the two parts
4685   // packed tightly. So generate loads of the real and imaginary parts relative
4686   // to the va_list pointer, and store them to a temporary structure. We do the
4687   // same as the PPC64ABI here.
4688   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4689     CharUnits EltSize = TypeInfo.Width / 2;
4690     if (EltSize < SlotSize)
4691       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4692   }
4693 
4694   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4695                           SlotSize, /*AllowHigher*/ true);
4696 }
4697 
4698 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4699     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4700   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4701 }
4702 
4703 // PowerPC-32
4704 namespace {
4705 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4706 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4707   bool IsSoftFloatABI;
4708   bool IsRetSmallStructInRegABI;
4709 
4710   CharUnits getParamTypeAlignment(QualType Ty) const;
4711 
4712 public:
4713   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4714                      bool RetSmallStructInRegABI)
4715       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4716         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4717 
4718   ABIArgInfo classifyReturnType(QualType RetTy) const;
4719 
4720   void computeInfo(CGFunctionInfo &FI) const override {
4721     if (!getCXXABI().classifyReturnType(FI))
4722       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4723     for (auto &I : FI.arguments())
4724       I.info = classifyArgumentType(I.type);
4725   }
4726 
4727   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4728                     QualType Ty) const override;
4729 };
4730 
4731 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4732 public:
4733   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4734                          bool RetSmallStructInRegABI)
4735       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4736             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4737 
4738   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4739                                      const CodeGenOptions &Opts);
4740 
4741   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4742     // This is recovered from gcc output.
4743     return 1; // r1 is the dedicated stack pointer
4744   }
4745 
4746   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4747                                llvm::Value *Address) const override;
4748 };
4749 }
4750 
4751 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4752   // Complex types are passed just like their elements.
4753   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4754     Ty = CTy->getElementType();
4755 
4756   if (Ty->isVectorType())
4757     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4758                                                                        : 4);
4759 
4760   // For single-element float/vector structs, we consider the whole type
4761   // to have the same alignment requirements as its single element.
4762   const Type *AlignTy = nullptr;
4763   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4764     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4765     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4766         (BT && BT->isFloatingPoint()))
4767       AlignTy = EltType;
4768   }
4769 
4770   if (AlignTy)
4771     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4772   return CharUnits::fromQuantity(4);
4773 }
4774 
4775 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4776   uint64_t Size;
4777 
4778   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4779   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4780       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4781     // System V ABI (1995), page 3-22, specified:
4782     // > A structure or union whose size is less than or equal to 8 bytes
4783     // > shall be returned in r3 and r4, as if it were first stored in the
4784     // > 8-byte aligned memory area and then the low addressed word were
4785     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4786     // > the last member of the structure or union are not defined.
4787     //
4788     // GCC for big-endian PPC32 inserts the pad before the first member,
4789     // not "beyond the last member" of the struct.  To stay compatible
4790     // with GCC, we coerce the struct to an integer of the same size.
4791     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4792     if (Size == 0)
4793       return ABIArgInfo::getIgnore();
4794     else {
4795       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4796       return ABIArgInfo::getDirect(CoerceTy);
4797     }
4798   }
4799 
4800   return DefaultABIInfo::classifyReturnType(RetTy);
4801 }
4802 
4803 // TODO: this implementation is now likely redundant with
4804 // DefaultABIInfo::EmitVAArg.
4805 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4806                                       QualType Ty) const {
4807   if (getTarget().getTriple().isOSDarwin()) {
4808     auto TI = getContext().getTypeInfoInChars(Ty);
4809     TI.Align = getParamTypeAlignment(Ty);
4810 
4811     CharUnits SlotSize = CharUnits::fromQuantity(4);
4812     return emitVoidPtrVAArg(CGF, VAList, Ty,
4813                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4814                             /*AllowHigherAlign=*/true);
4815   }
4816 
4817   const unsigned OverflowLimit = 8;
4818   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4819     // TODO: Implement this. For now ignore.
4820     (void)CTy;
4821     return Address::invalid(); // FIXME?
4822   }
4823 
4824   // struct __va_list_tag {
4825   //   unsigned char gpr;
4826   //   unsigned char fpr;
4827   //   unsigned short reserved;
4828   //   void *overflow_arg_area;
4829   //   void *reg_save_area;
4830   // };
4831 
4832   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4833   bool isInt = !Ty->isFloatingType();
4834   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4835 
4836   // All aggregates are passed indirectly?  That doesn't seem consistent
4837   // with the argument-lowering code.
4838   bool isIndirect = isAggregateTypeForABI(Ty);
4839 
4840   CGBuilderTy &Builder = CGF.Builder;
4841 
4842   // The calling convention either uses 1-2 GPRs or 1 FPR.
4843   Address NumRegsAddr = Address::invalid();
4844   if (isInt || IsSoftFloatABI) {
4845     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4846   } else {
4847     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4848   }
4849 
4850   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4851 
4852   // "Align" the register count when TY is i64.
4853   if (isI64 || (isF64 && IsSoftFloatABI)) {
4854     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4855     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4856   }
4857 
4858   llvm::Value *CC =
4859       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4860 
4861   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4862   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4863   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4864 
4865   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4866 
4867   llvm::Type *DirectTy = CGF.ConvertType(Ty), *ElementTy = DirectTy;
4868   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4869 
4870   // Case 1: consume registers.
4871   Address RegAddr = Address::invalid();
4872   {
4873     CGF.EmitBlock(UsingRegs);
4874 
4875     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4876     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CGF.Int8Ty,
4877                       CharUnits::fromQuantity(8));
4878     assert(RegAddr.getElementType() == CGF.Int8Ty);
4879 
4880     // Floating-point registers start after the general-purpose registers.
4881     if (!(isInt || IsSoftFloatABI)) {
4882       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4883                                                    CharUnits::fromQuantity(32));
4884     }
4885 
4886     // Get the address of the saved value by scaling the number of
4887     // registers we've used by the number of
4888     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4889     llvm::Value *RegOffset =
4890         Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4891     RegAddr = Address(
4892         Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
4893         CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4894     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4895 
4896     // Increase the used-register count.
4897     NumRegs =
4898       Builder.CreateAdd(NumRegs,
4899                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4900     Builder.CreateStore(NumRegs, NumRegsAddr);
4901 
4902     CGF.EmitBranch(Cont);
4903   }
4904 
4905   // Case 2: consume space in the overflow area.
4906   Address MemAddr = Address::invalid();
4907   {
4908     CGF.EmitBlock(UsingOverflow);
4909 
4910     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4911 
4912     // Everything in the overflow area is rounded up to a size of at least 4.
4913     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4914 
4915     CharUnits Size;
4916     if (!isIndirect) {
4917       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4918       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4919     } else {
4920       Size = CGF.getPointerSize();
4921     }
4922 
4923     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4924     Address OverflowArea =
4925         Address(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), CGF.Int8Ty,
4926                 OverflowAreaAlign);
4927     // Round up address of argument to alignment
4928     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4929     if (Align > OverflowAreaAlign) {
4930       llvm::Value *Ptr = OverflowArea.getPointer();
4931       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4932                              OverflowArea.getElementType(), Align);
4933     }
4934 
4935     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4936 
4937     // Increase the overflow area.
4938     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4939     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4940     CGF.EmitBranch(Cont);
4941   }
4942 
4943   CGF.EmitBlock(Cont);
4944 
4945   // Merge the cases with a phi.
4946   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4947                                 "vaarg.addr");
4948 
4949   // Load the pointer if the argument was passed indirectly.
4950   if (isIndirect) {
4951     Result = Address(Builder.CreateLoad(Result, "aggr"), ElementTy,
4952                      getContext().getTypeAlignInChars(Ty));
4953   }
4954 
4955   return Result;
4956 }
4957 
4958 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4959     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4960   assert(Triple.isPPC32());
4961 
4962   switch (Opts.getStructReturnConvention()) {
4963   case CodeGenOptions::SRCK_Default:
4964     break;
4965   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4966     return false;
4967   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4968     return true;
4969   }
4970 
4971   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4972     return true;
4973 
4974   return false;
4975 }
4976 
4977 bool
4978 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4979                                                 llvm::Value *Address) const {
4980   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4981                                      /*IsAIX*/ false);
4982 }
4983 
4984 // PowerPC-64
4985 
4986 namespace {
4987 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4988 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4989 public:
4990   enum ABIKind {
4991     ELFv1 = 0,
4992     ELFv2
4993   };
4994 
4995 private:
4996   static const unsigned GPRBits = 64;
4997   ABIKind Kind;
4998   bool IsSoftFloatABI;
4999 
5000 public:
5001   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
5002                      bool SoftFloatABI)
5003       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
5004 
5005   bool isPromotableTypeForABI(QualType Ty) const;
5006   CharUnits getParamTypeAlignment(QualType Ty) const;
5007 
5008   ABIArgInfo classifyReturnType(QualType RetTy) const;
5009   ABIArgInfo classifyArgumentType(QualType Ty) const;
5010 
5011   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5012   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5013                                          uint64_t Members) const override;
5014 
5015   // TODO: We can add more logic to computeInfo to improve performance.
5016   // Example: For aggregate arguments that fit in a register, we could
5017   // use getDirectInReg (as is done below for structs containing a single
5018   // floating-point value) to avoid pushing them to memory on function
5019   // entry.  This would require changing the logic in PPCISelLowering
5020   // when lowering the parameters in the caller and args in the callee.
5021   void computeInfo(CGFunctionInfo &FI) const override {
5022     if (!getCXXABI().classifyReturnType(FI))
5023       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5024     for (auto &I : FI.arguments()) {
5025       // We rely on the default argument classification for the most part.
5026       // One exception:  An aggregate containing a single floating-point
5027       // or vector item must be passed in a register if one is available.
5028       const Type *T = isSingleElementStruct(I.type, getContext());
5029       if (T) {
5030         const BuiltinType *BT = T->getAs<BuiltinType>();
5031         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
5032             (BT && BT->isFloatingPoint())) {
5033           QualType QT(T, 0);
5034           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
5035           continue;
5036         }
5037       }
5038       I.info = classifyArgumentType(I.type);
5039     }
5040   }
5041 
5042   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5043                     QualType Ty) const override;
5044 
5045   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5046                                     bool asReturnValue) const override {
5047     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5048   }
5049 
5050   bool isSwiftErrorInRegister() const override {
5051     return false;
5052   }
5053 };
5054 
5055 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5056 
5057 public:
5058   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5059                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5060                                bool SoftFloatABI)
5061       : TargetCodeGenInfo(
5062             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5063 
5064   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5065     // This is recovered from gcc output.
5066     return 1; // r1 is the dedicated stack pointer
5067   }
5068 
5069   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5070                                llvm::Value *Address) const override;
5071 };
5072 
5073 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5074 public:
5075   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5076 
5077   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5078     // This is recovered from gcc output.
5079     return 1; // r1 is the dedicated stack pointer
5080   }
5081 
5082   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5083                                llvm::Value *Address) const override;
5084 };
5085 
5086 }
5087 
5088 // Return true if the ABI requires Ty to be passed sign- or zero-
5089 // extended to 64 bits.
5090 bool
5091 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5092   // Treat an enum type as its underlying type.
5093   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5094     Ty = EnumTy->getDecl()->getIntegerType();
5095 
5096   // Promotable integer types are required to be promoted by the ABI.
5097   if (isPromotableIntegerTypeForABI(Ty))
5098     return true;
5099 
5100   // In addition to the usual promotable integer types, we also need to
5101   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5102   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5103     switch (BT->getKind()) {
5104     case BuiltinType::Int:
5105     case BuiltinType::UInt:
5106       return true;
5107     default:
5108       break;
5109     }
5110 
5111   if (const auto *EIT = Ty->getAs<BitIntType>())
5112     if (EIT->getNumBits() < 64)
5113       return true;
5114 
5115   return false;
5116 }
5117 
5118 /// isAlignedParamType - Determine whether a type requires 16-byte or
5119 /// higher alignment in the parameter area.  Always returns at least 8.
5120 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5121   // Complex types are passed just like their elements.
5122   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5123     Ty = CTy->getElementType();
5124 
5125   auto FloatUsesVector = [this](QualType Ty){
5126     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5127                                            Ty) == &llvm::APFloat::IEEEquad();
5128   };
5129 
5130   // Only vector types of size 16 bytes need alignment (larger types are
5131   // passed via reference, smaller types are not aligned).
5132   if (Ty->isVectorType()) {
5133     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5134   } else if (FloatUsesVector(Ty)) {
5135     // According to ABI document section 'Optional Save Areas': If extended
5136     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5137     // format are supported, map them to a single quadword, quadword aligned.
5138     return CharUnits::fromQuantity(16);
5139   }
5140 
5141   // For single-element float/vector structs, we consider the whole type
5142   // to have the same alignment requirements as its single element.
5143   const Type *AlignAsType = nullptr;
5144   const Type *EltType = isSingleElementStruct(Ty, getContext());
5145   if (EltType) {
5146     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5147     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5148         (BT && BT->isFloatingPoint()))
5149       AlignAsType = EltType;
5150   }
5151 
5152   // Likewise for ELFv2 homogeneous aggregates.
5153   const Type *Base = nullptr;
5154   uint64_t Members = 0;
5155   if (!AlignAsType && Kind == ELFv2 &&
5156       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5157     AlignAsType = Base;
5158 
5159   // With special case aggregates, only vector base types need alignment.
5160   if (AlignAsType) {
5161     bool UsesVector = AlignAsType->isVectorType() ||
5162                       FloatUsesVector(QualType(AlignAsType, 0));
5163     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5164   }
5165 
5166   // Otherwise, we only need alignment for any aggregate type that
5167   // has an alignment requirement of >= 16 bytes.
5168   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5169     return CharUnits::fromQuantity(16);
5170   }
5171 
5172   return CharUnits::fromQuantity(8);
5173 }
5174 
5175 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5176 /// aggregate.  Base is set to the base element type, and Members is set
5177 /// to the number of base elements.
5178 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5179                                      uint64_t &Members) const {
5180   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5181     uint64_t NElements = AT->getSize().getZExtValue();
5182     if (NElements == 0)
5183       return false;
5184     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5185       return false;
5186     Members *= NElements;
5187   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5188     const RecordDecl *RD = RT->getDecl();
5189     if (RD->hasFlexibleArrayMember())
5190       return false;
5191 
5192     Members = 0;
5193 
5194     // If this is a C++ record, check the properties of the record such as
5195     // bases and ABI specific restrictions
5196     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5197       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5198         return false;
5199 
5200       for (const auto &I : CXXRD->bases()) {
5201         // Ignore empty records.
5202         if (isEmptyRecord(getContext(), I.getType(), true))
5203           continue;
5204 
5205         uint64_t FldMembers;
5206         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5207           return false;
5208 
5209         Members += FldMembers;
5210       }
5211     }
5212 
5213     for (const auto *FD : RD->fields()) {
5214       // Ignore (non-zero arrays of) empty records.
5215       QualType FT = FD->getType();
5216       while (const ConstantArrayType *AT =
5217              getContext().getAsConstantArrayType(FT)) {
5218         if (AT->getSize().getZExtValue() == 0)
5219           return false;
5220         FT = AT->getElementType();
5221       }
5222       if (isEmptyRecord(getContext(), FT, true))
5223         continue;
5224 
5225       if (isZeroLengthBitfieldPermittedInHomogeneousAggregate() &&
5226           FD->isZeroLengthBitField(getContext()))
5227         continue;
5228 
5229       uint64_t FldMembers;
5230       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5231         return false;
5232 
5233       Members = (RD->isUnion() ?
5234                  std::max(Members, FldMembers) : Members + FldMembers);
5235     }
5236 
5237     if (!Base)
5238       return false;
5239 
5240     // Ensure there is no padding.
5241     if (getContext().getTypeSize(Base) * Members !=
5242         getContext().getTypeSize(Ty))
5243       return false;
5244   } else {
5245     Members = 1;
5246     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5247       Members = 2;
5248       Ty = CT->getElementType();
5249     }
5250 
5251     // Most ABIs only support float, double, and some vector type widths.
5252     if (!isHomogeneousAggregateBaseType(Ty))
5253       return false;
5254 
5255     // The base type must be the same for all members.  Types that
5256     // agree in both total size and mode (float vs. vector) are
5257     // treated as being equivalent here.
5258     const Type *TyPtr = Ty.getTypePtr();
5259     if (!Base) {
5260       Base = TyPtr;
5261       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5262       // so make sure to widen it explicitly.
5263       if (const VectorType *VT = Base->getAs<VectorType>()) {
5264         QualType EltTy = VT->getElementType();
5265         unsigned NumElements =
5266             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5267         Base = getContext()
5268                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5269                    .getTypePtr();
5270       }
5271     }
5272 
5273     if (Base->isVectorType() != TyPtr->isVectorType() ||
5274         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5275       return false;
5276   }
5277   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5278 }
5279 
5280 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5281   // Homogeneous aggregates for ELFv2 must have base types of float,
5282   // double, long double, or 128-bit vectors.
5283   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5284     if (BT->getKind() == BuiltinType::Float ||
5285         BT->getKind() == BuiltinType::Double ||
5286         BT->getKind() == BuiltinType::LongDouble ||
5287         BT->getKind() == BuiltinType::Ibm128 ||
5288         (getContext().getTargetInfo().hasFloat128Type() &&
5289          (BT->getKind() == BuiltinType::Float128))) {
5290       if (IsSoftFloatABI)
5291         return false;
5292       return true;
5293     }
5294   }
5295   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5296     if (getContext().getTypeSize(VT) == 128)
5297       return true;
5298   }
5299   return false;
5300 }
5301 
5302 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5303     const Type *Base, uint64_t Members) const {
5304   // Vector and fp128 types require one register, other floating point types
5305   // require one or two registers depending on their size.
5306   uint32_t NumRegs =
5307       ((getContext().getTargetInfo().hasFloat128Type() &&
5308           Base->isFloat128Type()) ||
5309         Base->isVectorType()) ? 1
5310                               : (getContext().getTypeSize(Base) + 63) / 64;
5311 
5312   // Homogeneous Aggregates may occupy at most 8 registers.
5313   return Members * NumRegs <= 8;
5314 }
5315 
5316 ABIArgInfo
5317 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5318   Ty = useFirstFieldIfTransparentUnion(Ty);
5319 
5320   if (Ty->isAnyComplexType())
5321     return ABIArgInfo::getDirect();
5322 
5323   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5324   // or via reference (larger than 16 bytes).
5325   if (Ty->isVectorType()) {
5326     uint64_t Size = getContext().getTypeSize(Ty);
5327     if (Size > 128)
5328       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5329     else if (Size < 128) {
5330       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5331       return ABIArgInfo::getDirect(CoerceTy);
5332     }
5333   }
5334 
5335   if (const auto *EIT = Ty->getAs<BitIntType>())
5336     if (EIT->getNumBits() > 128)
5337       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5338 
5339   if (isAggregateTypeForABI(Ty)) {
5340     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5341       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5342 
5343     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5344     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5345 
5346     // ELFv2 homogeneous aggregates are passed as array types.
5347     const Type *Base = nullptr;
5348     uint64_t Members = 0;
5349     if (Kind == ELFv2 &&
5350         isHomogeneousAggregate(Ty, Base, Members)) {
5351       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5352       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5353       return ABIArgInfo::getDirect(CoerceTy);
5354     }
5355 
5356     // If an aggregate may end up fully in registers, we do not
5357     // use the ByVal method, but pass the aggregate as array.
5358     // This is usually beneficial since we avoid forcing the
5359     // back-end to store the argument to memory.
5360     uint64_t Bits = getContext().getTypeSize(Ty);
5361     if (Bits > 0 && Bits <= 8 * GPRBits) {
5362       llvm::Type *CoerceTy;
5363 
5364       // Types up to 8 bytes are passed as integer type (which will be
5365       // properly aligned in the argument save area doubleword).
5366       if (Bits <= GPRBits)
5367         CoerceTy =
5368             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5369       // Larger types are passed as arrays, with the base type selected
5370       // according to the required alignment in the save area.
5371       else {
5372         uint64_t RegBits = ABIAlign * 8;
5373         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5374         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5375         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5376       }
5377 
5378       return ABIArgInfo::getDirect(CoerceTy);
5379     }
5380 
5381     // All other aggregates are passed ByVal.
5382     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5383                                    /*ByVal=*/true,
5384                                    /*Realign=*/TyAlign > ABIAlign);
5385   }
5386 
5387   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5388                                      : ABIArgInfo::getDirect());
5389 }
5390 
5391 ABIArgInfo
5392 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5393   if (RetTy->isVoidType())
5394     return ABIArgInfo::getIgnore();
5395 
5396   if (RetTy->isAnyComplexType())
5397     return ABIArgInfo::getDirect();
5398 
5399   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5400   // or via reference (larger than 16 bytes).
5401   if (RetTy->isVectorType()) {
5402     uint64_t Size = getContext().getTypeSize(RetTy);
5403     if (Size > 128)
5404       return getNaturalAlignIndirect(RetTy);
5405     else if (Size < 128) {
5406       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5407       return ABIArgInfo::getDirect(CoerceTy);
5408     }
5409   }
5410 
5411   if (const auto *EIT = RetTy->getAs<BitIntType>())
5412     if (EIT->getNumBits() > 128)
5413       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5414 
5415   if (isAggregateTypeForABI(RetTy)) {
5416     // ELFv2 homogeneous aggregates are returned as array types.
5417     const Type *Base = nullptr;
5418     uint64_t Members = 0;
5419     if (Kind == ELFv2 &&
5420         isHomogeneousAggregate(RetTy, Base, Members)) {
5421       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5422       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5423       return ABIArgInfo::getDirect(CoerceTy);
5424     }
5425 
5426     // ELFv2 small aggregates are returned in up to two registers.
5427     uint64_t Bits = getContext().getTypeSize(RetTy);
5428     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5429       if (Bits == 0)
5430         return ABIArgInfo::getIgnore();
5431 
5432       llvm::Type *CoerceTy;
5433       if (Bits > GPRBits) {
5434         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5435         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5436       } else
5437         CoerceTy =
5438             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5439       return ABIArgInfo::getDirect(CoerceTy);
5440     }
5441 
5442     // All other aggregates are returned indirectly.
5443     return getNaturalAlignIndirect(RetTy);
5444   }
5445 
5446   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5447                                         : ABIArgInfo::getDirect());
5448 }
5449 
5450 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5451 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5452                                       QualType Ty) const {
5453   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5454   TypeInfo.Align = getParamTypeAlignment(Ty);
5455 
5456   CharUnits SlotSize = CharUnits::fromQuantity(8);
5457 
5458   // If we have a complex type and the base type is smaller than 8 bytes,
5459   // the ABI calls for the real and imaginary parts to be right-adjusted
5460   // in separate doublewords.  However, Clang expects us to produce a
5461   // pointer to a structure with the two parts packed tightly.  So generate
5462   // loads of the real and imaginary parts relative to the va_list pointer,
5463   // and store them to a temporary structure.
5464   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5465     CharUnits EltSize = TypeInfo.Width / 2;
5466     if (EltSize < SlotSize)
5467       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5468   }
5469 
5470   // Otherwise, just use the general rule.
5471   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5472                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5473 }
5474 
5475 bool
5476 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5477   CodeGen::CodeGenFunction &CGF,
5478   llvm::Value *Address) const {
5479   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5480                                      /*IsAIX*/ false);
5481 }
5482 
5483 bool
5484 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5485                                                 llvm::Value *Address) const {
5486   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5487                                      /*IsAIX*/ false);
5488 }
5489 
5490 //===----------------------------------------------------------------------===//
5491 // AArch64 ABI Implementation
5492 //===----------------------------------------------------------------------===//
5493 
5494 namespace {
5495 
5496 class AArch64ABIInfo : public SwiftABIInfo {
5497 public:
5498   enum ABIKind {
5499     AAPCS = 0,
5500     DarwinPCS,
5501     Win64
5502   };
5503 
5504 private:
5505   ABIKind Kind;
5506 
5507 public:
5508   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5509     : SwiftABIInfo(CGT), Kind(Kind) {}
5510 
5511 private:
5512   ABIKind getABIKind() const { return Kind; }
5513   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5514 
5515   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5516   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5517                                   unsigned CallingConvention) const;
5518   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5519   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5520   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5521                                          uint64_t Members) const override;
5522   bool isZeroLengthBitfieldPermittedInHomogeneousAggregate() const override;
5523 
5524   bool isIllegalVectorType(QualType Ty) const;
5525 
5526   void computeInfo(CGFunctionInfo &FI) const override {
5527     if (!::classifyReturnType(getCXXABI(), FI, *this))
5528       FI.getReturnInfo() =
5529           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5530 
5531     for (auto &it : FI.arguments())
5532       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5533                                      FI.getCallingConvention());
5534   }
5535 
5536   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5537                           CodeGenFunction &CGF) const;
5538 
5539   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5540                          CodeGenFunction &CGF) const;
5541 
5542   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5543                     QualType Ty) const override {
5544     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5545     if (isa<llvm::ScalableVectorType>(BaseTy))
5546       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5547                                "currently not supported");
5548 
5549     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5550                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5551                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5552   }
5553 
5554   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5555                       QualType Ty) const override;
5556 
5557   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5558                                     bool asReturnValue) const override {
5559     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5560   }
5561   bool isSwiftErrorInRegister() const override {
5562     return true;
5563   }
5564 
5565   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5566                                  unsigned elts) const override;
5567 
5568   bool allowBFloatArgsAndRet() const override {
5569     return getTarget().hasBFloat16Type();
5570   }
5571 };
5572 
5573 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5574 public:
5575   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5576       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5577 
5578   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5579     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5580   }
5581 
5582   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5583     return 31;
5584   }
5585 
5586   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5587 
5588   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5589                            CodeGen::CodeGenModule &CGM) const override {
5590     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5591     if (!FD)
5592       return;
5593 
5594     const auto *TA = FD->getAttr<TargetAttr>();
5595     if (TA == nullptr)
5596       return;
5597 
5598     ParsedTargetAttr Attr = TA->parse();
5599     if (Attr.BranchProtection.empty())
5600       return;
5601 
5602     TargetInfo::BranchProtectionInfo BPI;
5603     StringRef Error;
5604     (void)CGM.getTarget().validateBranchProtection(
5605         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5606     assert(Error.empty());
5607 
5608     auto *Fn = cast<llvm::Function>(GV);
5609     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5610     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5611 
5612     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5613       Fn->addFnAttr("sign-return-address-key",
5614                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5615                         ? "a_key"
5616                         : "b_key");
5617     }
5618 
5619     Fn->addFnAttr("branch-target-enforcement",
5620                   BPI.BranchTargetEnforcement ? "true" : "false");
5621   }
5622 
5623   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5624                                 llvm::Type *Ty) const override {
5625     if (CGF.getTarget().hasFeature("ls64")) {
5626       auto *ST = dyn_cast<llvm::StructType>(Ty);
5627       if (ST && ST->getNumElements() == 1) {
5628         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5629         if (AT && AT->getNumElements() == 8 &&
5630             AT->getElementType()->isIntegerTy(64))
5631           return true;
5632       }
5633     }
5634     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5635   }
5636 };
5637 
5638 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5639 public:
5640   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5641       : AArch64TargetCodeGenInfo(CGT, K) {}
5642 
5643   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5644                            CodeGen::CodeGenModule &CGM) const override;
5645 
5646   void getDependentLibraryOption(llvm::StringRef Lib,
5647                                  llvm::SmallString<24> &Opt) const override {
5648     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5649   }
5650 
5651   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5652                                llvm::SmallString<32> &Opt) const override {
5653     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5654   }
5655 };
5656 
5657 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5658     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5659   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5660   if (GV->isDeclaration())
5661     return;
5662   addStackProbeTargetAttributes(D, GV, CGM);
5663 }
5664 }
5665 
5666 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5667   assert(Ty->isVectorType() && "expected vector type!");
5668 
5669   const auto *VT = Ty->castAs<VectorType>();
5670   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5671     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5672     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5673                BuiltinType::UChar &&
5674            "unexpected builtin type for SVE predicate!");
5675     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5676         llvm::Type::getInt1Ty(getVMContext()), 16));
5677   }
5678 
5679   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5680     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5681 
5682     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5683     llvm::ScalableVectorType *ResType = nullptr;
5684     switch (BT->getKind()) {
5685     default:
5686       llvm_unreachable("unexpected builtin type for SVE vector!");
5687     case BuiltinType::SChar:
5688     case BuiltinType::UChar:
5689       ResType = llvm::ScalableVectorType::get(
5690           llvm::Type::getInt8Ty(getVMContext()), 16);
5691       break;
5692     case BuiltinType::Short:
5693     case BuiltinType::UShort:
5694       ResType = llvm::ScalableVectorType::get(
5695           llvm::Type::getInt16Ty(getVMContext()), 8);
5696       break;
5697     case BuiltinType::Int:
5698     case BuiltinType::UInt:
5699       ResType = llvm::ScalableVectorType::get(
5700           llvm::Type::getInt32Ty(getVMContext()), 4);
5701       break;
5702     case BuiltinType::Long:
5703     case BuiltinType::ULong:
5704       ResType = llvm::ScalableVectorType::get(
5705           llvm::Type::getInt64Ty(getVMContext()), 2);
5706       break;
5707     case BuiltinType::Half:
5708       ResType = llvm::ScalableVectorType::get(
5709           llvm::Type::getHalfTy(getVMContext()), 8);
5710       break;
5711     case BuiltinType::Float:
5712       ResType = llvm::ScalableVectorType::get(
5713           llvm::Type::getFloatTy(getVMContext()), 4);
5714       break;
5715     case BuiltinType::Double:
5716       ResType = llvm::ScalableVectorType::get(
5717           llvm::Type::getDoubleTy(getVMContext()), 2);
5718       break;
5719     case BuiltinType::BFloat16:
5720       ResType = llvm::ScalableVectorType::get(
5721           llvm::Type::getBFloatTy(getVMContext()), 8);
5722       break;
5723     }
5724     return ABIArgInfo::getDirect(ResType);
5725   }
5726 
5727   uint64_t Size = getContext().getTypeSize(Ty);
5728   // Android promotes <2 x i8> to i16, not i32
5729   if (isAndroid() && (Size <= 16)) {
5730     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5731     return ABIArgInfo::getDirect(ResType);
5732   }
5733   if (Size <= 32) {
5734     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5735     return ABIArgInfo::getDirect(ResType);
5736   }
5737   if (Size == 64) {
5738     auto *ResType =
5739         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5740     return ABIArgInfo::getDirect(ResType);
5741   }
5742   if (Size == 128) {
5743     auto *ResType =
5744         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5745     return ABIArgInfo::getDirect(ResType);
5746   }
5747   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5748 }
5749 
5750 ABIArgInfo
5751 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5752                                      unsigned CallingConvention) const {
5753   Ty = useFirstFieldIfTransparentUnion(Ty);
5754 
5755   // Handle illegal vector types here.
5756   if (isIllegalVectorType(Ty))
5757     return coerceIllegalVector(Ty);
5758 
5759   if (!isAggregateTypeForABI(Ty)) {
5760     // Treat an enum type as its underlying type.
5761     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5762       Ty = EnumTy->getDecl()->getIntegerType();
5763 
5764     if (const auto *EIT = Ty->getAs<BitIntType>())
5765       if (EIT->getNumBits() > 128)
5766         return getNaturalAlignIndirect(Ty);
5767 
5768     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5769                 ? ABIArgInfo::getExtend(Ty)
5770                 : ABIArgInfo::getDirect());
5771   }
5772 
5773   // Structures with either a non-trivial destructor or a non-trivial
5774   // copy constructor are always indirect.
5775   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5776     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5777                                      CGCXXABI::RAA_DirectInMemory);
5778   }
5779 
5780   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5781   // elsewhere for GNU compatibility.
5782   uint64_t Size = getContext().getTypeSize(Ty);
5783   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5784   if (IsEmpty || Size == 0) {
5785     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5786       return ABIArgInfo::getIgnore();
5787 
5788     // GNU C mode. The only argument that gets ignored is an empty one with size
5789     // 0.
5790     if (IsEmpty && Size == 0)
5791       return ABIArgInfo::getIgnore();
5792     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5793   }
5794 
5795   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5796   const Type *Base = nullptr;
5797   uint64_t Members = 0;
5798   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5799   bool IsWinVariadic = IsWin64 && IsVariadic;
5800   // In variadic functions on Windows, all composite types are treated alike,
5801   // no special handling of HFAs/HVAs.
5802   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5803     if (Kind != AArch64ABIInfo::AAPCS)
5804       return ABIArgInfo::getDirect(
5805           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5806 
5807     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5808     // default otherwise.
5809     unsigned Align =
5810         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5811     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5812     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5813     return ABIArgInfo::getDirect(
5814         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5815         nullptr, true, Align);
5816   }
5817 
5818   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5819   if (Size <= 128) {
5820     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5821     // same size and alignment.
5822     if (getTarget().isRenderScriptTarget()) {
5823       return coerceToIntArray(Ty, getContext(), getVMContext());
5824     }
5825     unsigned Alignment;
5826     if (Kind == AArch64ABIInfo::AAPCS) {
5827       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5828       Alignment = Alignment < 128 ? 64 : 128;
5829     } else {
5830       Alignment = std::max(getContext().getTypeAlign(Ty),
5831                            (unsigned)getTarget().getPointerWidth(0));
5832     }
5833     Size = llvm::alignTo(Size, Alignment);
5834 
5835     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5836     // For aggregates with 16-byte alignment, we use i128.
5837     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5838     return ABIArgInfo::getDirect(
5839         Size == Alignment ? BaseTy
5840                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5841   }
5842 
5843   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5844 }
5845 
5846 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5847                                               bool IsVariadic) const {
5848   if (RetTy->isVoidType())
5849     return ABIArgInfo::getIgnore();
5850 
5851   if (const auto *VT = RetTy->getAs<VectorType>()) {
5852     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5853         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5854       return coerceIllegalVector(RetTy);
5855   }
5856 
5857   // Large vector types should be returned via memory.
5858   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5859     return getNaturalAlignIndirect(RetTy);
5860 
5861   if (!isAggregateTypeForABI(RetTy)) {
5862     // Treat an enum type as its underlying type.
5863     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5864       RetTy = EnumTy->getDecl()->getIntegerType();
5865 
5866     if (const auto *EIT = RetTy->getAs<BitIntType>())
5867       if (EIT->getNumBits() > 128)
5868         return getNaturalAlignIndirect(RetTy);
5869 
5870     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5871                 ? ABIArgInfo::getExtend(RetTy)
5872                 : ABIArgInfo::getDirect());
5873   }
5874 
5875   uint64_t Size = getContext().getTypeSize(RetTy);
5876   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5877     return ABIArgInfo::getIgnore();
5878 
5879   const Type *Base = nullptr;
5880   uint64_t Members = 0;
5881   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5882       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5883         IsVariadic))
5884     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5885     return ABIArgInfo::getDirect();
5886 
5887   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5888   if (Size <= 128) {
5889     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5890     // same size and alignment.
5891     if (getTarget().isRenderScriptTarget()) {
5892       return coerceToIntArray(RetTy, getContext(), getVMContext());
5893     }
5894 
5895     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5896       // Composite types are returned in lower bits of a 64-bit register for LE,
5897       // and in higher bits for BE. However, integer types are always returned
5898       // in lower bits for both LE and BE, and they are not rounded up to
5899       // 64-bits. We can skip rounding up of composite types for LE, but not for
5900       // BE, otherwise composite types will be indistinguishable from integer
5901       // types.
5902       return ABIArgInfo::getDirect(
5903           llvm::IntegerType::get(getVMContext(), Size));
5904     }
5905 
5906     unsigned Alignment = getContext().getTypeAlign(RetTy);
5907     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5908 
5909     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5910     // For aggregates with 16-byte alignment, we use i128.
5911     if (Alignment < 128 && Size == 128) {
5912       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5913       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5914     }
5915     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5916   }
5917 
5918   return getNaturalAlignIndirect(RetTy);
5919 }
5920 
5921 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5922 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5923   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5924     // Check whether VT is a fixed-length SVE vector. These types are
5925     // represented as scalable vectors in function args/return and must be
5926     // coerced from fixed vectors.
5927     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5928         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5929       return true;
5930 
5931     // Check whether VT is legal.
5932     unsigned NumElements = VT->getNumElements();
5933     uint64_t Size = getContext().getTypeSize(VT);
5934     // NumElements should be power of 2.
5935     if (!llvm::isPowerOf2_32(NumElements))
5936       return true;
5937 
5938     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5939     // vectors for some reason.
5940     llvm::Triple Triple = getTarget().getTriple();
5941     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5942         Triple.isOSBinFormatMachO())
5943       return Size <= 32;
5944 
5945     return Size != 64 && (Size != 128 || NumElements == 1);
5946   }
5947   return false;
5948 }
5949 
5950 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5951                                                llvm::Type *eltTy,
5952                                                unsigned elts) const {
5953   if (!llvm::isPowerOf2_32(elts))
5954     return false;
5955   if (totalSize.getQuantity() != 8 &&
5956       (totalSize.getQuantity() != 16 || elts == 1))
5957     return false;
5958   return true;
5959 }
5960 
5961 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5962   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5963   // point type or a short-vector type. This is the same as the 32-bit ABI,
5964   // but with the difference that any floating-point type is allowed,
5965   // including __fp16.
5966   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5967     if (BT->isFloatingPoint())
5968       return true;
5969   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5970     unsigned VecSize = getContext().getTypeSize(VT);
5971     if (VecSize == 64 || VecSize == 128)
5972       return true;
5973   }
5974   return false;
5975 }
5976 
5977 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5978                                                        uint64_t Members) const {
5979   return Members <= 4;
5980 }
5981 
5982 bool AArch64ABIInfo::isZeroLengthBitfieldPermittedInHomogeneousAggregate()
5983     const {
5984   // AAPCS64 says that the rule for whether something is a homogeneous
5985   // aggregate is applied to the output of the data layout decision. So
5986   // anything that doesn't affect the data layout also does not affect
5987   // homogeneity. In particular, zero-length bitfields don't stop a struct
5988   // being homogeneous.
5989   return true;
5990 }
5991 
5992 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5993                                        CodeGenFunction &CGF) const {
5994   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5995                                        CGF.CurFnInfo->getCallingConvention());
5996   bool IsIndirect = AI.isIndirect();
5997 
5998   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5999   if (IsIndirect)
6000     BaseTy = llvm::PointerType::getUnqual(BaseTy);
6001   else if (AI.getCoerceToType())
6002     BaseTy = AI.getCoerceToType();
6003 
6004   unsigned NumRegs = 1;
6005   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
6006     BaseTy = ArrTy->getElementType();
6007     NumRegs = ArrTy->getNumElements();
6008   }
6009   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
6010 
6011   // The AArch64 va_list type and handling is specified in the Procedure Call
6012   // Standard, section B.4:
6013   //
6014   // struct {
6015   //   void *__stack;
6016   //   void *__gr_top;
6017   //   void *__vr_top;
6018   //   int __gr_offs;
6019   //   int __vr_offs;
6020   // };
6021 
6022   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
6023   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6024   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
6025   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6026 
6027   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6028   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
6029 
6030   Address reg_offs_p = Address::invalid();
6031   llvm::Value *reg_offs = nullptr;
6032   int reg_top_index;
6033   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
6034   if (!IsFPR) {
6035     // 3 is the field number of __gr_offs
6036     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
6037     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
6038     reg_top_index = 1; // field number for __gr_top
6039     RegSize = llvm::alignTo(RegSize, 8);
6040   } else {
6041     // 4 is the field number of __vr_offs.
6042     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
6043     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
6044     reg_top_index = 2; // field number for __vr_top
6045     RegSize = 16 * NumRegs;
6046   }
6047 
6048   //=======================================
6049   // Find out where argument was passed
6050   //=======================================
6051 
6052   // If reg_offs >= 0 we're already using the stack for this type of
6053   // argument. We don't want to keep updating reg_offs (in case it overflows,
6054   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6055   // whatever they get).
6056   llvm::Value *UsingStack = nullptr;
6057   UsingStack = CGF.Builder.CreateICmpSGE(
6058       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6059 
6060   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6061 
6062   // Otherwise, at least some kind of argument could go in these registers, the
6063   // question is whether this particular type is too big.
6064   CGF.EmitBlock(MaybeRegBlock);
6065 
6066   // Integer arguments may need to correct register alignment (for example a
6067   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6068   // align __gr_offs to calculate the potential address.
6069   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6070     int Align = TyAlign.getQuantity();
6071 
6072     reg_offs = CGF.Builder.CreateAdd(
6073         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6074         "align_regoffs");
6075     reg_offs = CGF.Builder.CreateAnd(
6076         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6077         "aligned_regoffs");
6078   }
6079 
6080   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6081   // The fact that this is done unconditionally reflects the fact that
6082   // allocating an argument to the stack also uses up all the remaining
6083   // registers of the appropriate kind.
6084   llvm::Value *NewOffset = nullptr;
6085   NewOffset = CGF.Builder.CreateAdd(
6086       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6087   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6088 
6089   // Now we're in a position to decide whether this argument really was in
6090   // registers or not.
6091   llvm::Value *InRegs = nullptr;
6092   InRegs = CGF.Builder.CreateICmpSLE(
6093       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6094 
6095   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6096 
6097   //=======================================
6098   // Argument was in registers
6099   //=======================================
6100 
6101   // Now we emit the code for if the argument was originally passed in
6102   // registers. First start the appropriate block:
6103   CGF.EmitBlock(InRegBlock);
6104 
6105   llvm::Value *reg_top = nullptr;
6106   Address reg_top_p =
6107       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6108   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6109   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6110                    CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
6111   Address RegAddr = Address::invalid();
6112   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy;
6113 
6114   if (IsIndirect) {
6115     // If it's been passed indirectly (actually a struct), whatever we find from
6116     // stored registers or on the stack will actually be a struct **.
6117     MemTy = llvm::PointerType::getUnqual(MemTy);
6118   }
6119 
6120   const Type *Base = nullptr;
6121   uint64_t NumMembers = 0;
6122   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6123   if (IsHFA && NumMembers > 1) {
6124     // Homogeneous aggregates passed in registers will have their elements split
6125     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6126     // qN+1, ...). We reload and store into a temporary local variable
6127     // contiguously.
6128     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6129     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6130     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6131     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6132     Address Tmp = CGF.CreateTempAlloca(HFATy,
6133                                        std::max(TyAlign, BaseTyInfo.Align));
6134 
6135     // On big-endian platforms, the value will be right-aligned in its slot.
6136     int Offset = 0;
6137     if (CGF.CGM.getDataLayout().isBigEndian() &&
6138         BaseTyInfo.Width.getQuantity() < 16)
6139       Offset = 16 - BaseTyInfo.Width.getQuantity();
6140 
6141     for (unsigned i = 0; i < NumMembers; ++i) {
6142       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6143       Address LoadAddr =
6144         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6145       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6146 
6147       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6148 
6149       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6150       CGF.Builder.CreateStore(Elem, StoreAddr);
6151     }
6152 
6153     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6154   } else {
6155     // Otherwise the object is contiguous in memory.
6156 
6157     // It might be right-aligned in its slot.
6158     CharUnits SlotSize = BaseAddr.getAlignment();
6159     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6160         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6161         TySize < SlotSize) {
6162       CharUnits Offset = SlotSize - TySize;
6163       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6164     }
6165 
6166     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6167   }
6168 
6169   CGF.EmitBranch(ContBlock);
6170 
6171   //=======================================
6172   // Argument was on the stack
6173   //=======================================
6174   CGF.EmitBlock(OnStackBlock);
6175 
6176   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6177   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6178 
6179   // Again, stack arguments may need realignment. In this case both integer and
6180   // floating-point ones might be affected.
6181   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6182     int Align = TyAlign.getQuantity();
6183 
6184     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6185 
6186     OnStackPtr = CGF.Builder.CreateAdd(
6187         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6188         "align_stack");
6189     OnStackPtr = CGF.Builder.CreateAnd(
6190         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6191         "align_stack");
6192 
6193     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6194   }
6195   Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty,
6196                                 std::max(CharUnits::fromQuantity(8), TyAlign));
6197 
6198   // All stack slots are multiples of 8 bytes.
6199   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6200   CharUnits StackSize;
6201   if (IsIndirect)
6202     StackSize = StackSlotSize;
6203   else
6204     StackSize = TySize.alignTo(StackSlotSize);
6205 
6206   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6207   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6208       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6209 
6210   // Write the new value of __stack for the next call to va_arg
6211   CGF.Builder.CreateStore(NewStack, stack_p);
6212 
6213   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6214       TySize < StackSlotSize) {
6215     CharUnits Offset = StackSlotSize - TySize;
6216     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6217   }
6218 
6219   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6220 
6221   CGF.EmitBranch(ContBlock);
6222 
6223   //=======================================
6224   // Tidy up
6225   //=======================================
6226   CGF.EmitBlock(ContBlock);
6227 
6228   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
6229                                  OnStackBlock, "vaargs.addr");
6230 
6231   if (IsIndirect)
6232     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy,
6233                    TyAlign);
6234 
6235   return ResAddr;
6236 }
6237 
6238 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6239                                         CodeGenFunction &CGF) const {
6240   // The backend's lowering doesn't support va_arg for aggregates or
6241   // illegal vector types.  Lower VAArg here for these cases and use
6242   // the LLVM va_arg instruction for everything else.
6243   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6244     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6245 
6246   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6247   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6248 
6249   // Empty records are ignored for parameter passing purposes.
6250   if (isEmptyRecord(getContext(), Ty, true)) {
6251     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"),
6252                            getVAListElementType(CGF), SlotSize);
6253     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6254     return Addr;
6255   }
6256 
6257   // The size of the actual thing passed, which might end up just
6258   // being a pointer for indirect types.
6259   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6260 
6261   // Arguments bigger than 16 bytes which aren't homogeneous
6262   // aggregates should be passed indirectly.
6263   bool IsIndirect = false;
6264   if (TyInfo.Width.getQuantity() > 16) {
6265     const Type *Base = nullptr;
6266     uint64_t Members = 0;
6267     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6268   }
6269 
6270   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6271                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6272 }
6273 
6274 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6275                                     QualType Ty) const {
6276   bool IsIndirect = false;
6277 
6278   // Composites larger than 16 bytes are passed by reference.
6279   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6280     IsIndirect = true;
6281 
6282   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6283                           CGF.getContext().getTypeInfoInChars(Ty),
6284                           CharUnits::fromQuantity(8),
6285                           /*allowHigherAlign*/ false);
6286 }
6287 
6288 //===----------------------------------------------------------------------===//
6289 // ARM ABI Implementation
6290 //===----------------------------------------------------------------------===//
6291 
6292 namespace {
6293 
6294 class ARMABIInfo : public SwiftABIInfo {
6295 public:
6296   enum ABIKind {
6297     APCS = 0,
6298     AAPCS = 1,
6299     AAPCS_VFP = 2,
6300     AAPCS16_VFP = 3,
6301   };
6302 
6303 private:
6304   ABIKind Kind;
6305   bool IsFloatABISoftFP;
6306 
6307 public:
6308   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6309       : SwiftABIInfo(CGT), Kind(_Kind) {
6310     setCCs();
6311     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6312         CGT.getCodeGenOpts().FloatABI == ""; // default
6313   }
6314 
6315   bool isEABI() const {
6316     switch (getTarget().getTriple().getEnvironment()) {
6317     case llvm::Triple::Android:
6318     case llvm::Triple::EABI:
6319     case llvm::Triple::EABIHF:
6320     case llvm::Triple::GNUEABI:
6321     case llvm::Triple::GNUEABIHF:
6322     case llvm::Triple::MuslEABI:
6323     case llvm::Triple::MuslEABIHF:
6324       return true;
6325     default:
6326       return false;
6327     }
6328   }
6329 
6330   bool isEABIHF() const {
6331     switch (getTarget().getTriple().getEnvironment()) {
6332     case llvm::Triple::EABIHF:
6333     case llvm::Triple::GNUEABIHF:
6334     case llvm::Triple::MuslEABIHF:
6335       return true;
6336     default:
6337       return false;
6338     }
6339   }
6340 
6341   ABIKind getABIKind() const { return Kind; }
6342 
6343   bool allowBFloatArgsAndRet() const override {
6344     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6345   }
6346 
6347 private:
6348   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6349                                 unsigned functionCallConv) const;
6350   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6351                                   unsigned functionCallConv) const;
6352   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6353                                           uint64_t Members) const;
6354   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6355   bool isIllegalVectorType(QualType Ty) const;
6356   bool containsAnyFP16Vectors(QualType Ty) const;
6357 
6358   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6359   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6360                                          uint64_t Members) const override;
6361   bool isZeroLengthBitfieldPermittedInHomogeneousAggregate() const override;
6362 
6363   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6364 
6365   void computeInfo(CGFunctionInfo &FI) const override;
6366 
6367   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6368                     QualType Ty) const override;
6369 
6370   llvm::CallingConv::ID getLLVMDefaultCC() const;
6371   llvm::CallingConv::ID getABIDefaultCC() const;
6372   void setCCs();
6373 
6374   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6375                                     bool asReturnValue) const override {
6376     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6377   }
6378   bool isSwiftErrorInRegister() const override {
6379     return true;
6380   }
6381   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6382                                  unsigned elts) const override;
6383 };
6384 
6385 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6386 public:
6387   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6388       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6389 
6390   const ARMABIInfo &getABIInfo() const {
6391     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6392   }
6393 
6394   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6395     return 13;
6396   }
6397 
6398   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6399     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6400   }
6401 
6402   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6403                                llvm::Value *Address) const override {
6404     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6405 
6406     // 0-15 are the 16 integer registers.
6407     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6408     return false;
6409   }
6410 
6411   unsigned getSizeOfUnwindException() const override {
6412     if (getABIInfo().isEABI()) return 88;
6413     return TargetCodeGenInfo::getSizeOfUnwindException();
6414   }
6415 
6416   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6417                            CodeGen::CodeGenModule &CGM) const override {
6418     if (GV->isDeclaration())
6419       return;
6420     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6421     if (!FD)
6422       return;
6423     auto *Fn = cast<llvm::Function>(GV);
6424 
6425     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6426       ParsedTargetAttr Attr = TA->parse();
6427       if (!Attr.BranchProtection.empty()) {
6428         TargetInfo::BranchProtectionInfo BPI;
6429         StringRef DiagMsg;
6430         StringRef Arch = Attr.Architecture.empty()
6431                              ? CGM.getTarget().getTargetOpts().CPU
6432                              : Attr.Architecture;
6433         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6434                                                       Arch, BPI, DiagMsg)) {
6435           CGM.getDiags().Report(
6436               D->getLocation(),
6437               diag::warn_target_unsupported_branch_protection_attribute)
6438               << Arch;
6439         } else {
6440           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6441           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6442                  "Unexpected SignReturnAddressScopeKind");
6443           Fn->addFnAttr(
6444               "sign-return-address",
6445               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6446 
6447           Fn->addFnAttr("branch-target-enforcement",
6448                         BPI.BranchTargetEnforcement ? "true" : "false");
6449         }
6450       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6451                  CGM.getLangOpts().hasSignReturnAddress()) {
6452         // If the Branch Protection attribute is missing, validate the target
6453         // Architecture attribute against Branch Protection command line
6454         // settings.
6455         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6456           CGM.getDiags().Report(
6457               D->getLocation(),
6458               diag::warn_target_unsupported_branch_protection_attribute)
6459               << Attr.Architecture;
6460       }
6461     }
6462 
6463     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6464     if (!Attr)
6465       return;
6466 
6467     const char *Kind;
6468     switch (Attr->getInterrupt()) {
6469     case ARMInterruptAttr::Generic: Kind = ""; break;
6470     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6471     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6472     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6473     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6474     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6475     }
6476 
6477     Fn->addFnAttr("interrupt", Kind);
6478 
6479     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6480     if (ABI == ARMABIInfo::APCS)
6481       return;
6482 
6483     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6484     // however this is not necessarily true on taking any interrupt. Instruct
6485     // the backend to perform a realignment as part of the function prologue.
6486     llvm::AttrBuilder B(Fn->getContext());
6487     B.addStackAlignmentAttr(8);
6488     Fn->addFnAttrs(B);
6489   }
6490 };
6491 
6492 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6493 public:
6494   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6495       : ARMTargetCodeGenInfo(CGT, K) {}
6496 
6497   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6498                            CodeGen::CodeGenModule &CGM) const override;
6499 
6500   void getDependentLibraryOption(llvm::StringRef Lib,
6501                                  llvm::SmallString<24> &Opt) const override {
6502     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6503   }
6504 
6505   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6506                                llvm::SmallString<32> &Opt) const override {
6507     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6508   }
6509 };
6510 
6511 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6512     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6513   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6514   if (GV->isDeclaration())
6515     return;
6516   addStackProbeTargetAttributes(D, GV, CGM);
6517 }
6518 }
6519 
6520 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6521   if (!::classifyReturnType(getCXXABI(), FI, *this))
6522     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6523                                             FI.getCallingConvention());
6524 
6525   for (auto &I : FI.arguments())
6526     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6527                                   FI.getCallingConvention());
6528 
6529 
6530   // Always honor user-specified calling convention.
6531   if (FI.getCallingConvention() != llvm::CallingConv::C)
6532     return;
6533 
6534   llvm::CallingConv::ID cc = getRuntimeCC();
6535   if (cc != llvm::CallingConv::C)
6536     FI.setEffectiveCallingConvention(cc);
6537 }
6538 
6539 /// Return the default calling convention that LLVM will use.
6540 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6541   // The default calling convention that LLVM will infer.
6542   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6543     return llvm::CallingConv::ARM_AAPCS_VFP;
6544   else if (isEABI())
6545     return llvm::CallingConv::ARM_AAPCS;
6546   else
6547     return llvm::CallingConv::ARM_APCS;
6548 }
6549 
6550 /// Return the calling convention that our ABI would like us to use
6551 /// as the C calling convention.
6552 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6553   switch (getABIKind()) {
6554   case APCS: return llvm::CallingConv::ARM_APCS;
6555   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6556   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6557   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6558   }
6559   llvm_unreachable("bad ABI kind");
6560 }
6561 
6562 void ARMABIInfo::setCCs() {
6563   assert(getRuntimeCC() == llvm::CallingConv::C);
6564 
6565   // Don't muddy up the IR with a ton of explicit annotations if
6566   // they'd just match what LLVM will infer from the triple.
6567   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6568   if (abiCC != getLLVMDefaultCC())
6569     RuntimeCC = abiCC;
6570 }
6571 
6572 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6573   uint64_t Size = getContext().getTypeSize(Ty);
6574   if (Size <= 32) {
6575     llvm::Type *ResType =
6576         llvm::Type::getInt32Ty(getVMContext());
6577     return ABIArgInfo::getDirect(ResType);
6578   }
6579   if (Size == 64 || Size == 128) {
6580     auto *ResType = llvm::FixedVectorType::get(
6581         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6582     return ABIArgInfo::getDirect(ResType);
6583   }
6584   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6585 }
6586 
6587 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6588                                                     const Type *Base,
6589                                                     uint64_t Members) const {
6590   assert(Base && "Base class should be set for homogeneous aggregate");
6591   // Base can be a floating-point or a vector.
6592   if (const VectorType *VT = Base->getAs<VectorType>()) {
6593     // FP16 vectors should be converted to integer vectors
6594     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6595       uint64_t Size = getContext().getTypeSize(VT);
6596       auto *NewVecTy = llvm::FixedVectorType::get(
6597           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6598       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6599       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6600     }
6601   }
6602   unsigned Align = 0;
6603   if (getABIKind() == ARMABIInfo::AAPCS ||
6604       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6605     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6606     // default otherwise.
6607     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6608     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6609     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6610   }
6611   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6612 }
6613 
6614 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6615                                             unsigned functionCallConv) const {
6616   // 6.1.2.1 The following argument types are VFP CPRCs:
6617   //   A single-precision floating-point type (including promoted
6618   //   half-precision types); A double-precision floating-point type;
6619   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6620   //   with a Base Type of a single- or double-precision floating-point type,
6621   //   64-bit containerized vectors or 128-bit containerized vectors with one
6622   //   to four Elements.
6623   // Variadic functions should always marshal to the base standard.
6624   bool IsAAPCS_VFP =
6625       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6626 
6627   Ty = useFirstFieldIfTransparentUnion(Ty);
6628 
6629   // Handle illegal vector types here.
6630   if (isIllegalVectorType(Ty))
6631     return coerceIllegalVector(Ty);
6632 
6633   if (!isAggregateTypeForABI(Ty)) {
6634     // Treat an enum type as its underlying type.
6635     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6636       Ty = EnumTy->getDecl()->getIntegerType();
6637     }
6638 
6639     if (const auto *EIT = Ty->getAs<BitIntType>())
6640       if (EIT->getNumBits() > 64)
6641         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6642 
6643     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6644                                               : ABIArgInfo::getDirect());
6645   }
6646 
6647   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6648     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6649   }
6650 
6651   // Ignore empty records.
6652   if (isEmptyRecord(getContext(), Ty, true))
6653     return ABIArgInfo::getIgnore();
6654 
6655   if (IsAAPCS_VFP) {
6656     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6657     // into VFP registers.
6658     const Type *Base = nullptr;
6659     uint64_t Members = 0;
6660     if (isHomogeneousAggregate(Ty, Base, Members))
6661       return classifyHomogeneousAggregate(Ty, Base, Members);
6662   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6663     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6664     // this convention even for a variadic function: the backend will use GPRs
6665     // if needed.
6666     const Type *Base = nullptr;
6667     uint64_t Members = 0;
6668     if (isHomogeneousAggregate(Ty, Base, Members)) {
6669       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6670       llvm::Type *Ty =
6671         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6672       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6673     }
6674   }
6675 
6676   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6677       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6678     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6679     // bigger than 128-bits, they get placed in space allocated by the caller,
6680     // and a pointer is passed.
6681     return ABIArgInfo::getIndirect(
6682         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6683   }
6684 
6685   // Support byval for ARM.
6686   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6687   // most 8-byte. We realign the indirect argument if type alignment is bigger
6688   // than ABI alignment.
6689   uint64_t ABIAlign = 4;
6690   uint64_t TyAlign;
6691   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6692       getABIKind() == ARMABIInfo::AAPCS) {
6693     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6694     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6695   } else {
6696     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6697   }
6698   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6699     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6700     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6701                                    /*ByVal=*/true,
6702                                    /*Realign=*/TyAlign > ABIAlign);
6703   }
6704 
6705   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6706   // same size and alignment.
6707   if (getTarget().isRenderScriptTarget()) {
6708     return coerceToIntArray(Ty, getContext(), getVMContext());
6709   }
6710 
6711   // Otherwise, pass by coercing to a structure of the appropriate size.
6712   llvm::Type* ElemTy;
6713   unsigned SizeRegs;
6714   // FIXME: Try to match the types of the arguments more accurately where
6715   // we can.
6716   if (TyAlign <= 4) {
6717     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6718     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6719   } else {
6720     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6721     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6722   }
6723 
6724   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6725 }
6726 
6727 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6728                               llvm::LLVMContext &VMContext) {
6729   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6730   // is called integer-like if its size is less than or equal to one word, and
6731   // the offset of each of its addressable sub-fields is zero.
6732 
6733   uint64_t Size = Context.getTypeSize(Ty);
6734 
6735   // Check that the type fits in a word.
6736   if (Size > 32)
6737     return false;
6738 
6739   // FIXME: Handle vector types!
6740   if (Ty->isVectorType())
6741     return false;
6742 
6743   // Float types are never treated as "integer like".
6744   if (Ty->isRealFloatingType())
6745     return false;
6746 
6747   // If this is a builtin or pointer type then it is ok.
6748   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6749     return true;
6750 
6751   // Small complex integer types are "integer like".
6752   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6753     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6754 
6755   // Single element and zero sized arrays should be allowed, by the definition
6756   // above, but they are not.
6757 
6758   // Otherwise, it must be a record type.
6759   const RecordType *RT = Ty->getAs<RecordType>();
6760   if (!RT) return false;
6761 
6762   // Ignore records with flexible arrays.
6763   const RecordDecl *RD = RT->getDecl();
6764   if (RD->hasFlexibleArrayMember())
6765     return false;
6766 
6767   // Check that all sub-fields are at offset 0, and are themselves "integer
6768   // like".
6769   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6770 
6771   bool HadField = false;
6772   unsigned idx = 0;
6773   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6774        i != e; ++i, ++idx) {
6775     const FieldDecl *FD = *i;
6776 
6777     // Bit-fields are not addressable, we only need to verify they are "integer
6778     // like". We still have to disallow a subsequent non-bitfield, for example:
6779     //   struct { int : 0; int x }
6780     // is non-integer like according to gcc.
6781     if (FD->isBitField()) {
6782       if (!RD->isUnion())
6783         HadField = true;
6784 
6785       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6786         return false;
6787 
6788       continue;
6789     }
6790 
6791     // Check if this field is at offset 0.
6792     if (Layout.getFieldOffset(idx) != 0)
6793       return false;
6794 
6795     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6796       return false;
6797 
6798     // Only allow at most one field in a structure. This doesn't match the
6799     // wording above, but follows gcc in situations with a field following an
6800     // empty structure.
6801     if (!RD->isUnion()) {
6802       if (HadField)
6803         return false;
6804 
6805       HadField = true;
6806     }
6807   }
6808 
6809   return true;
6810 }
6811 
6812 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6813                                           unsigned functionCallConv) const {
6814 
6815   // Variadic functions should always marshal to the base standard.
6816   bool IsAAPCS_VFP =
6817       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6818 
6819   if (RetTy->isVoidType())
6820     return ABIArgInfo::getIgnore();
6821 
6822   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6823     // Large vector types should be returned via memory.
6824     if (getContext().getTypeSize(RetTy) > 128)
6825       return getNaturalAlignIndirect(RetTy);
6826     // TODO: FP16/BF16 vectors should be converted to integer vectors
6827     // This check is similar  to isIllegalVectorType - refactor?
6828     if ((!getTarget().hasLegalHalfType() &&
6829         (VT->getElementType()->isFloat16Type() ||
6830          VT->getElementType()->isHalfType())) ||
6831         (IsFloatABISoftFP &&
6832          VT->getElementType()->isBFloat16Type()))
6833       return coerceIllegalVector(RetTy);
6834   }
6835 
6836   if (!isAggregateTypeForABI(RetTy)) {
6837     // Treat an enum type as its underlying type.
6838     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6839       RetTy = EnumTy->getDecl()->getIntegerType();
6840 
6841     if (const auto *EIT = RetTy->getAs<BitIntType>())
6842       if (EIT->getNumBits() > 64)
6843         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6844 
6845     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6846                                                 : ABIArgInfo::getDirect();
6847   }
6848 
6849   // Are we following APCS?
6850   if (getABIKind() == APCS) {
6851     if (isEmptyRecord(getContext(), RetTy, false))
6852       return ABIArgInfo::getIgnore();
6853 
6854     // Complex types are all returned as packed integers.
6855     //
6856     // FIXME: Consider using 2 x vector types if the back end handles them
6857     // correctly.
6858     if (RetTy->isAnyComplexType())
6859       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6860           getVMContext(), getContext().getTypeSize(RetTy)));
6861 
6862     // Integer like structures are returned in r0.
6863     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6864       // Return in the smallest viable integer type.
6865       uint64_t Size = getContext().getTypeSize(RetTy);
6866       if (Size <= 8)
6867         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6868       if (Size <= 16)
6869         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6870       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6871     }
6872 
6873     // Otherwise return in memory.
6874     return getNaturalAlignIndirect(RetTy);
6875   }
6876 
6877   // Otherwise this is an AAPCS variant.
6878 
6879   if (isEmptyRecord(getContext(), RetTy, true))
6880     return ABIArgInfo::getIgnore();
6881 
6882   // Check for homogeneous aggregates with AAPCS-VFP.
6883   if (IsAAPCS_VFP) {
6884     const Type *Base = nullptr;
6885     uint64_t Members = 0;
6886     if (isHomogeneousAggregate(RetTy, Base, Members))
6887       return classifyHomogeneousAggregate(RetTy, Base, Members);
6888   }
6889 
6890   // Aggregates <= 4 bytes are returned in r0; other aggregates
6891   // are returned indirectly.
6892   uint64_t Size = getContext().getTypeSize(RetTy);
6893   if (Size <= 32) {
6894     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6895     // same size and alignment.
6896     if (getTarget().isRenderScriptTarget()) {
6897       return coerceToIntArray(RetTy, getContext(), getVMContext());
6898     }
6899     if (getDataLayout().isBigEndian())
6900       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6901       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6902 
6903     // Return in the smallest viable integer type.
6904     if (Size <= 8)
6905       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6906     if (Size <= 16)
6907       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6908     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6909   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6910     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6911     llvm::Type *CoerceTy =
6912         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6913     return ABIArgInfo::getDirect(CoerceTy);
6914   }
6915 
6916   return getNaturalAlignIndirect(RetTy);
6917 }
6918 
6919 /// isIllegalVector - check whether Ty is an illegal vector type.
6920 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6921   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6922     // On targets that don't support half, fp16 or bfloat, they are expanded
6923     // into float, and we don't want the ABI to depend on whether or not they
6924     // are supported in hardware. Thus return false to coerce vectors of these
6925     // types into integer vectors.
6926     // We do not depend on hasLegalHalfType for bfloat as it is a
6927     // separate IR type.
6928     if ((!getTarget().hasLegalHalfType() &&
6929         (VT->getElementType()->isFloat16Type() ||
6930          VT->getElementType()->isHalfType())) ||
6931         (IsFloatABISoftFP &&
6932          VT->getElementType()->isBFloat16Type()))
6933       return true;
6934     if (isAndroid()) {
6935       // Android shipped using Clang 3.1, which supported a slightly different
6936       // vector ABI. The primary differences were that 3-element vector types
6937       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6938       // accepts that legacy behavior for Android only.
6939       // Check whether VT is legal.
6940       unsigned NumElements = VT->getNumElements();
6941       // NumElements should be power of 2 or equal to 3.
6942       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6943         return true;
6944     } else {
6945       // Check whether VT is legal.
6946       unsigned NumElements = VT->getNumElements();
6947       uint64_t Size = getContext().getTypeSize(VT);
6948       // NumElements should be power of 2.
6949       if (!llvm::isPowerOf2_32(NumElements))
6950         return true;
6951       // Size should be greater than 32 bits.
6952       return Size <= 32;
6953     }
6954   }
6955   return false;
6956 }
6957 
6958 /// Return true if a type contains any 16-bit floating point vectors
6959 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6960   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6961     uint64_t NElements = AT->getSize().getZExtValue();
6962     if (NElements == 0)
6963       return false;
6964     return containsAnyFP16Vectors(AT->getElementType());
6965   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6966     const RecordDecl *RD = RT->getDecl();
6967 
6968     // If this is a C++ record, check the bases first.
6969     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6970       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6971             return containsAnyFP16Vectors(B.getType());
6972           }))
6973         return true;
6974 
6975     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6976           return FD && containsAnyFP16Vectors(FD->getType());
6977         }))
6978       return true;
6979 
6980     return false;
6981   } else {
6982     if (const VectorType *VT = Ty->getAs<VectorType>())
6983       return (VT->getElementType()->isFloat16Type() ||
6984               VT->getElementType()->isBFloat16Type() ||
6985               VT->getElementType()->isHalfType());
6986     return false;
6987   }
6988 }
6989 
6990 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6991                                            llvm::Type *eltTy,
6992                                            unsigned numElts) const {
6993   if (!llvm::isPowerOf2_32(numElts))
6994     return false;
6995   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6996   if (size > 64)
6997     return false;
6998   if (vectorSize.getQuantity() != 8 &&
6999       (vectorSize.getQuantity() != 16 || numElts == 1))
7000     return false;
7001   return true;
7002 }
7003 
7004 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7005   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
7006   // double, or 64-bit or 128-bit vectors.
7007   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
7008     if (BT->getKind() == BuiltinType::Float ||
7009         BT->getKind() == BuiltinType::Double ||
7010         BT->getKind() == BuiltinType::LongDouble)
7011       return true;
7012   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
7013     unsigned VecSize = getContext().getTypeSize(VT);
7014     if (VecSize == 64 || VecSize == 128)
7015       return true;
7016   }
7017   return false;
7018 }
7019 
7020 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
7021                                                    uint64_t Members) const {
7022   return Members <= 4;
7023 }
7024 
7025 bool ARMABIInfo::isZeroLengthBitfieldPermittedInHomogeneousAggregate() const {
7026   // AAPCS32 says that the rule for whether something is a homogeneous
7027   // aggregate is applied to the output of the data layout decision. So
7028   // anything that doesn't affect the data layout also does not affect
7029   // homogeneity. In particular, zero-length bitfields don't stop a struct
7030   // being homogeneous.
7031   return true;
7032 }
7033 
7034 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
7035                                         bool acceptHalf) const {
7036   // Give precedence to user-specified calling conventions.
7037   if (callConvention != llvm::CallingConv::C)
7038     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
7039   else
7040     return (getABIKind() == AAPCS_VFP) ||
7041            (acceptHalf && (getABIKind() == AAPCS16_VFP));
7042 }
7043 
7044 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7045                               QualType Ty) const {
7046   CharUnits SlotSize = CharUnits::fromQuantity(4);
7047 
7048   // Empty records are ignored for parameter passing purposes.
7049   if (isEmptyRecord(getContext(), Ty, true)) {
7050     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
7051     auto *Load = CGF.Builder.CreateLoad(VAListAddr);
7052     Address Addr = Address(Load, CGF.Int8Ty, SlotSize);
7053     return CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
7054   }
7055 
7056   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
7057   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
7058 
7059   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7060   bool IsIndirect = false;
7061   const Type *Base = nullptr;
7062   uint64_t Members = 0;
7063   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7064     IsIndirect = true;
7065 
7066   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7067   // allocated by the caller.
7068   } else if (TySize > CharUnits::fromQuantity(16) &&
7069              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7070              !isHomogeneousAggregate(Ty, Base, Members)) {
7071     IsIndirect = true;
7072 
7073   // Otherwise, bound the type's ABI alignment.
7074   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7075   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7076   // Our callers should be prepared to handle an under-aligned address.
7077   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7078              getABIKind() == ARMABIInfo::AAPCS) {
7079     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7080     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7081   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7082     // ARMv7k allows type alignment up to 16 bytes.
7083     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7084     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7085   } else {
7086     TyAlignForABI = CharUnits::fromQuantity(4);
7087   }
7088 
7089   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7090   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7091                           SlotSize, /*AllowHigherAlign*/ true);
7092 }
7093 
7094 //===----------------------------------------------------------------------===//
7095 // NVPTX ABI Implementation
7096 //===----------------------------------------------------------------------===//
7097 
7098 namespace {
7099 
7100 class NVPTXTargetCodeGenInfo;
7101 
7102 class NVPTXABIInfo : public ABIInfo {
7103   NVPTXTargetCodeGenInfo &CGInfo;
7104 
7105 public:
7106   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7107       : ABIInfo(CGT), CGInfo(Info) {}
7108 
7109   ABIArgInfo classifyReturnType(QualType RetTy) const;
7110   ABIArgInfo classifyArgumentType(QualType Ty) const;
7111 
7112   void computeInfo(CGFunctionInfo &FI) const override;
7113   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7114                     QualType Ty) const override;
7115   bool isUnsupportedType(QualType T) const;
7116   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7117 };
7118 
7119 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7120 public:
7121   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7122       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7123 
7124   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7125                            CodeGen::CodeGenModule &M) const override;
7126   bool shouldEmitStaticExternCAliases() const override;
7127 
7128   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7129     // On the device side, surface reference is represented as an object handle
7130     // in 64-bit integer.
7131     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7132   }
7133 
7134   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7135     // On the device side, texture reference is represented as an object handle
7136     // in 64-bit integer.
7137     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7138   }
7139 
7140   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7141                                               LValue Src) const override {
7142     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7143     return true;
7144   }
7145 
7146   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7147                                               LValue Src) const override {
7148     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7149     return true;
7150   }
7151 
7152 private:
7153   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7154   // resulting MDNode to the nvvm.annotations MDNode.
7155   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7156                               int Operand);
7157 
7158   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7159                                            LValue Src) {
7160     llvm::Value *Handle = nullptr;
7161     llvm::Constant *C =
7162         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7163     // Lookup `addrspacecast` through the constant pointer if any.
7164     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7165       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7166     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7167       // Load the handle from the specific global variable using
7168       // `nvvm.texsurf.handle.internal` intrinsic.
7169       Handle = CGF.EmitRuntimeCall(
7170           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7171                                {GV->getType()}),
7172           {GV}, "texsurf_handle");
7173     } else
7174       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7175     CGF.EmitStoreOfScalar(Handle, Dst);
7176   }
7177 };
7178 
7179 /// Checks if the type is unsupported directly by the current target.
7180 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7181   ASTContext &Context = getContext();
7182   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7183     return true;
7184   if (!Context.getTargetInfo().hasFloat128Type() &&
7185       (T->isFloat128Type() ||
7186        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7187     return true;
7188   if (const auto *EIT = T->getAs<BitIntType>())
7189     return EIT->getNumBits() >
7190            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7191   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7192       Context.getTypeSize(T) > 64U)
7193     return true;
7194   if (const auto *AT = T->getAsArrayTypeUnsafe())
7195     return isUnsupportedType(AT->getElementType());
7196   const auto *RT = T->getAs<RecordType>();
7197   if (!RT)
7198     return false;
7199   const RecordDecl *RD = RT->getDecl();
7200 
7201   // If this is a C++ record, check the bases first.
7202   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7203     for (const CXXBaseSpecifier &I : CXXRD->bases())
7204       if (isUnsupportedType(I.getType()))
7205         return true;
7206 
7207   for (const FieldDecl *I : RD->fields())
7208     if (isUnsupportedType(I->getType()))
7209       return true;
7210   return false;
7211 }
7212 
7213 /// Coerce the given type into an array with maximum allowed size of elements.
7214 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7215                                                    unsigned MaxSize) const {
7216   // Alignment and Size are measured in bits.
7217   const uint64_t Size = getContext().getTypeSize(Ty);
7218   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7219   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7220   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7221   const uint64_t NumElements = (Size + Div - 1) / Div;
7222   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7223 }
7224 
7225 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7226   if (RetTy->isVoidType())
7227     return ABIArgInfo::getIgnore();
7228 
7229   if (getContext().getLangOpts().OpenMP &&
7230       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7231     return coerceToIntArrayWithLimit(RetTy, 64);
7232 
7233   // note: this is different from default ABI
7234   if (!RetTy->isScalarType())
7235     return ABIArgInfo::getDirect();
7236 
7237   // Treat an enum type as its underlying type.
7238   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7239     RetTy = EnumTy->getDecl()->getIntegerType();
7240 
7241   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7242                                                : ABIArgInfo::getDirect());
7243 }
7244 
7245 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7246   // Treat an enum type as its underlying type.
7247   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7248     Ty = EnumTy->getDecl()->getIntegerType();
7249 
7250   // Return aggregates type as indirect by value
7251   if (isAggregateTypeForABI(Ty)) {
7252     // Under CUDA device compilation, tex/surf builtin types are replaced with
7253     // object types and passed directly.
7254     if (getContext().getLangOpts().CUDAIsDevice) {
7255       if (Ty->isCUDADeviceBuiltinSurfaceType())
7256         return ABIArgInfo::getDirect(
7257             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7258       if (Ty->isCUDADeviceBuiltinTextureType())
7259         return ABIArgInfo::getDirect(
7260             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7261     }
7262     return getNaturalAlignIndirect(Ty, /* byval */ true);
7263   }
7264 
7265   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7266     if ((EIT->getNumBits() > 128) ||
7267         (!getContext().getTargetInfo().hasInt128Type() &&
7268          EIT->getNumBits() > 64))
7269       return getNaturalAlignIndirect(Ty, /* byval */ true);
7270   }
7271 
7272   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7273                                             : ABIArgInfo::getDirect());
7274 }
7275 
7276 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7277   if (!getCXXABI().classifyReturnType(FI))
7278     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7279   for (auto &I : FI.arguments())
7280     I.info = classifyArgumentType(I.type);
7281 
7282   // Always honor user-specified calling convention.
7283   if (FI.getCallingConvention() != llvm::CallingConv::C)
7284     return;
7285 
7286   FI.setEffectiveCallingConvention(getRuntimeCC());
7287 }
7288 
7289 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7290                                 QualType Ty) const {
7291   llvm_unreachable("NVPTX does not support varargs");
7292 }
7293 
7294 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7295     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7296   if (GV->isDeclaration())
7297     return;
7298   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7299   if (VD) {
7300     if (M.getLangOpts().CUDA) {
7301       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7302         addNVVMMetadata(GV, "surface", 1);
7303       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7304         addNVVMMetadata(GV, "texture", 1);
7305       return;
7306     }
7307   }
7308 
7309   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7310   if (!FD) return;
7311 
7312   llvm::Function *F = cast<llvm::Function>(GV);
7313 
7314   // Perform special handling in OpenCL mode
7315   if (M.getLangOpts().OpenCL) {
7316     // Use OpenCL function attributes to check for kernel functions
7317     // By default, all functions are device functions
7318     if (FD->hasAttr<OpenCLKernelAttr>()) {
7319       // OpenCL __kernel functions get kernel metadata
7320       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7321       addNVVMMetadata(F, "kernel", 1);
7322       // And kernel functions are not subject to inlining
7323       F->addFnAttr(llvm::Attribute::NoInline);
7324     }
7325   }
7326 
7327   // Perform special handling in CUDA mode.
7328   if (M.getLangOpts().CUDA) {
7329     // CUDA __global__ functions get a kernel metadata entry.  Since
7330     // __global__ functions cannot be called from the device, we do not
7331     // need to set the noinline attribute.
7332     if (FD->hasAttr<CUDAGlobalAttr>()) {
7333       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7334       addNVVMMetadata(F, "kernel", 1);
7335     }
7336     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7337       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7338       llvm::APSInt MaxThreads(32);
7339       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7340       if (MaxThreads > 0)
7341         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7342 
7343       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7344       // not specified in __launch_bounds__ or if the user specified a 0 value,
7345       // we don't have to add a PTX directive.
7346       if (Attr->getMinBlocks()) {
7347         llvm::APSInt MinBlocks(32);
7348         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7349         if (MinBlocks > 0)
7350           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7351           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7352       }
7353     }
7354   }
7355 }
7356 
7357 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7358                                              StringRef Name, int Operand) {
7359   llvm::Module *M = GV->getParent();
7360   llvm::LLVMContext &Ctx = M->getContext();
7361 
7362   // Get "nvvm.annotations" metadata node
7363   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7364 
7365   llvm::Metadata *MDVals[] = {
7366       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7367       llvm::ConstantAsMetadata::get(
7368           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7369   // Append metadata to nvvm.annotations
7370   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7371 }
7372 
7373 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7374   return false;
7375 }
7376 }
7377 
7378 //===----------------------------------------------------------------------===//
7379 // SystemZ ABI Implementation
7380 //===----------------------------------------------------------------------===//
7381 
7382 namespace {
7383 
7384 class SystemZABIInfo : public SwiftABIInfo {
7385   bool HasVector;
7386   bool IsSoftFloatABI;
7387 
7388 public:
7389   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7390     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7391 
7392   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7393   bool isCompoundType(QualType Ty) const;
7394   bool isVectorArgumentType(QualType Ty) const;
7395   bool isFPArgumentType(QualType Ty) const;
7396   QualType GetSingleElementType(QualType Ty) const;
7397 
7398   ABIArgInfo classifyReturnType(QualType RetTy) const;
7399   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7400 
7401   void computeInfo(CGFunctionInfo &FI) const override {
7402     if (!getCXXABI().classifyReturnType(FI))
7403       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7404     for (auto &I : FI.arguments())
7405       I.info = classifyArgumentType(I.type);
7406   }
7407 
7408   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7409                     QualType Ty) const override;
7410 
7411   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7412                                     bool asReturnValue) const override {
7413     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7414   }
7415   bool isSwiftErrorInRegister() const override {
7416     return false;
7417   }
7418 };
7419 
7420 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7421 public:
7422   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7423       : TargetCodeGenInfo(
7424             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7425 
7426   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7427                           CGBuilderTy &Builder,
7428                           CodeGenModule &CGM) const override {
7429     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7430     // Only use TDC in constrained FP mode.
7431     if (!Builder.getIsFPConstrained())
7432       return nullptr;
7433 
7434     llvm::Type *Ty = V->getType();
7435     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7436       llvm::Module &M = CGM.getModule();
7437       auto &Ctx = M.getContext();
7438       llvm::Function *TDCFunc =
7439           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7440       unsigned TDCBits = 0;
7441       switch (BuiltinID) {
7442       case Builtin::BI__builtin_isnan:
7443         TDCBits = 0xf;
7444         break;
7445       case Builtin::BIfinite:
7446       case Builtin::BI__finite:
7447       case Builtin::BIfinitef:
7448       case Builtin::BI__finitef:
7449       case Builtin::BIfinitel:
7450       case Builtin::BI__finitel:
7451       case Builtin::BI__builtin_isfinite:
7452         TDCBits = 0xfc0;
7453         break;
7454       case Builtin::BI__builtin_isinf:
7455         TDCBits = 0x30;
7456         break;
7457       default:
7458         break;
7459       }
7460       if (TDCBits)
7461         return Builder.CreateCall(
7462             TDCFunc,
7463             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7464     }
7465     return nullptr;
7466   }
7467 };
7468 }
7469 
7470 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7471   // Treat an enum type as its underlying type.
7472   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7473     Ty = EnumTy->getDecl()->getIntegerType();
7474 
7475   // Promotable integer types are required to be promoted by the ABI.
7476   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7477     return true;
7478 
7479   if (const auto *EIT = Ty->getAs<BitIntType>())
7480     if (EIT->getNumBits() < 64)
7481       return true;
7482 
7483   // 32-bit values must also be promoted.
7484   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7485     switch (BT->getKind()) {
7486     case BuiltinType::Int:
7487     case BuiltinType::UInt:
7488       return true;
7489     default:
7490       return false;
7491     }
7492   return false;
7493 }
7494 
7495 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7496   return (Ty->isAnyComplexType() ||
7497           Ty->isVectorType() ||
7498           isAggregateTypeForABI(Ty));
7499 }
7500 
7501 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7502   return (HasVector &&
7503           Ty->isVectorType() &&
7504           getContext().getTypeSize(Ty) <= 128);
7505 }
7506 
7507 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7508   if (IsSoftFloatABI)
7509     return false;
7510 
7511   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7512     switch (BT->getKind()) {
7513     case BuiltinType::Float:
7514     case BuiltinType::Double:
7515       return true;
7516     default:
7517       return false;
7518     }
7519 
7520   return false;
7521 }
7522 
7523 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7524   const RecordType *RT = Ty->getAs<RecordType>();
7525 
7526   if (RT && RT->isStructureOrClassType()) {
7527     const RecordDecl *RD = RT->getDecl();
7528     QualType Found;
7529 
7530     // If this is a C++ record, check the bases first.
7531     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7532       for (const auto &I : CXXRD->bases()) {
7533         QualType Base = I.getType();
7534 
7535         // Empty bases don't affect things either way.
7536         if (isEmptyRecord(getContext(), Base, true))
7537           continue;
7538 
7539         if (!Found.isNull())
7540           return Ty;
7541         Found = GetSingleElementType(Base);
7542       }
7543 
7544     // Check the fields.
7545     for (const auto *FD : RD->fields()) {
7546       // Unlike isSingleElementStruct(), empty structure and array fields
7547       // do count.  So do anonymous bitfields that aren't zero-sized.
7548 
7549       // Like isSingleElementStruct(), ignore C++20 empty data members.
7550       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7551           isEmptyRecord(getContext(), FD->getType(), true))
7552         continue;
7553 
7554       // Unlike isSingleElementStruct(), arrays do not count.
7555       // Nested structures still do though.
7556       if (!Found.isNull())
7557         return Ty;
7558       Found = GetSingleElementType(FD->getType());
7559     }
7560 
7561     // Unlike isSingleElementStruct(), trailing padding is allowed.
7562     // An 8-byte aligned struct s { float f; } is passed as a double.
7563     if (!Found.isNull())
7564       return Found;
7565   }
7566 
7567   return Ty;
7568 }
7569 
7570 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7571                                   QualType Ty) const {
7572   // Assume that va_list type is correct; should be pointer to LLVM type:
7573   // struct {
7574   //   i64 __gpr;
7575   //   i64 __fpr;
7576   //   i8 *__overflow_arg_area;
7577   //   i8 *__reg_save_area;
7578   // };
7579 
7580   // Every non-vector argument occupies 8 bytes and is passed by preference
7581   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7582   // always passed on the stack.
7583   Ty = getContext().getCanonicalType(Ty);
7584   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7585   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7586   llvm::Type *DirectTy = ArgTy;
7587   ABIArgInfo AI = classifyArgumentType(Ty);
7588   bool IsIndirect = AI.isIndirect();
7589   bool InFPRs = false;
7590   bool IsVector = false;
7591   CharUnits UnpaddedSize;
7592   CharUnits DirectAlign;
7593   if (IsIndirect) {
7594     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7595     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7596   } else {
7597     if (AI.getCoerceToType())
7598       ArgTy = AI.getCoerceToType();
7599     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7600     IsVector = ArgTy->isVectorTy();
7601     UnpaddedSize = TyInfo.Width;
7602     DirectAlign = TyInfo.Align;
7603   }
7604   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7605   if (IsVector && UnpaddedSize > PaddedSize)
7606     PaddedSize = CharUnits::fromQuantity(16);
7607   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7608 
7609   CharUnits Padding = (PaddedSize - UnpaddedSize);
7610 
7611   llvm::Type *IndexTy = CGF.Int64Ty;
7612   llvm::Value *PaddedSizeV =
7613     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7614 
7615   if (IsVector) {
7616     // Work out the address of a vector argument on the stack.
7617     // Vector arguments are always passed in the high bits of a
7618     // single (8 byte) or double (16 byte) stack slot.
7619     Address OverflowArgAreaPtr =
7620         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7621     Address OverflowArgArea =
7622         Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7623                 CGF.Int8Ty, TyInfo.Align);
7624     Address MemAddr =
7625         CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7626 
7627     // Update overflow_arg_area_ptr pointer
7628     llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(
7629         OverflowArgArea.getElementType(), OverflowArgArea.getPointer(),
7630         PaddedSizeV, "overflow_arg_area");
7631     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7632 
7633     return MemAddr;
7634   }
7635 
7636   assert(PaddedSize.getQuantity() == 8);
7637 
7638   unsigned MaxRegs, RegCountField, RegSaveIndex;
7639   CharUnits RegPadding;
7640   if (InFPRs) {
7641     MaxRegs = 4; // Maximum of 4 FPR arguments
7642     RegCountField = 1; // __fpr
7643     RegSaveIndex = 16; // save offset for f0
7644     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7645   } else {
7646     MaxRegs = 5; // Maximum of 5 GPR arguments
7647     RegCountField = 0; // __gpr
7648     RegSaveIndex = 2; // save offset for r2
7649     RegPadding = Padding; // values are passed in the low bits of a GPR
7650   }
7651 
7652   Address RegCountPtr =
7653       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7654   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7655   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7656   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7657                                                  "fits_in_regs");
7658 
7659   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7660   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7661   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7662   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7663 
7664   // Emit code to load the value if it was passed in registers.
7665   CGF.EmitBlock(InRegBlock);
7666 
7667   // Work out the address of an argument register.
7668   llvm::Value *ScaledRegCount =
7669     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7670   llvm::Value *RegBase =
7671     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7672                                       + RegPadding.getQuantity());
7673   llvm::Value *RegOffset =
7674     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7675   Address RegSaveAreaPtr =
7676       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7677   llvm::Value *RegSaveArea =
7678       CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7679   Address RawRegAddr(
7680       CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"),
7681       CGF.Int8Ty, PaddedSize);
7682   Address RegAddr =
7683       CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7684 
7685   // Update the register count
7686   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7687   llvm::Value *NewRegCount =
7688     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7689   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7690   CGF.EmitBranch(ContBlock);
7691 
7692   // Emit code to load the value if it was passed in memory.
7693   CGF.EmitBlock(InMemBlock);
7694 
7695   // Work out the address of a stack argument.
7696   Address OverflowArgAreaPtr =
7697       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7698   Address OverflowArgArea =
7699       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7700               CGF.Int8Ty, PaddedSize);
7701   Address RawMemAddr =
7702       CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7703   Address MemAddr =
7704     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7705 
7706   // Update overflow_arg_area_ptr pointer
7707   llvm::Value *NewOverflowArgArea =
7708     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7709                           OverflowArgArea.getPointer(), PaddedSizeV,
7710                           "overflow_arg_area");
7711   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7712   CGF.EmitBranch(ContBlock);
7713 
7714   // Return the appropriate result.
7715   CGF.EmitBlock(ContBlock);
7716   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
7717                                  "va_arg.addr");
7718 
7719   if (IsIndirect)
7720     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), ArgTy,
7721                       TyInfo.Align);
7722 
7723   return ResAddr;
7724 }
7725 
7726 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7727   if (RetTy->isVoidType())
7728     return ABIArgInfo::getIgnore();
7729   if (isVectorArgumentType(RetTy))
7730     return ABIArgInfo::getDirect();
7731   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7732     return getNaturalAlignIndirect(RetTy);
7733   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7734                                                : ABIArgInfo::getDirect());
7735 }
7736 
7737 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7738   // Handle the generic C++ ABI.
7739   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7740     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7741 
7742   // Integers and enums are extended to full register width.
7743   if (isPromotableIntegerTypeForABI(Ty))
7744     return ABIArgInfo::getExtend(Ty);
7745 
7746   // Handle vector types and vector-like structure types.  Note that
7747   // as opposed to float-like structure types, we do not allow any
7748   // padding for vector-like structures, so verify the sizes match.
7749   uint64_t Size = getContext().getTypeSize(Ty);
7750   QualType SingleElementTy = GetSingleElementType(Ty);
7751   if (isVectorArgumentType(SingleElementTy) &&
7752       getContext().getTypeSize(SingleElementTy) == Size)
7753     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7754 
7755   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7756   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7757     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7758 
7759   // Handle small structures.
7760   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7761     // Structures with flexible arrays have variable length, so really
7762     // fail the size test above.
7763     const RecordDecl *RD = RT->getDecl();
7764     if (RD->hasFlexibleArrayMember())
7765       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7766 
7767     // The structure is passed as an unextended integer, a float, or a double.
7768     llvm::Type *PassTy;
7769     if (isFPArgumentType(SingleElementTy)) {
7770       assert(Size == 32 || Size == 64);
7771       if (Size == 32)
7772         PassTy = llvm::Type::getFloatTy(getVMContext());
7773       else
7774         PassTy = llvm::Type::getDoubleTy(getVMContext());
7775     } else
7776       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7777     return ABIArgInfo::getDirect(PassTy);
7778   }
7779 
7780   // Non-structure compounds are passed indirectly.
7781   if (isCompoundType(Ty))
7782     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7783 
7784   return ABIArgInfo::getDirect(nullptr);
7785 }
7786 
7787 //===----------------------------------------------------------------------===//
7788 // MSP430 ABI Implementation
7789 //===----------------------------------------------------------------------===//
7790 
7791 namespace {
7792 
7793 class MSP430ABIInfo : public DefaultABIInfo {
7794   static ABIArgInfo complexArgInfo() {
7795     ABIArgInfo Info = ABIArgInfo::getDirect();
7796     Info.setCanBeFlattened(false);
7797     return Info;
7798   }
7799 
7800 public:
7801   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7802 
7803   ABIArgInfo classifyReturnType(QualType RetTy) const {
7804     if (RetTy->isAnyComplexType())
7805       return complexArgInfo();
7806 
7807     return DefaultABIInfo::classifyReturnType(RetTy);
7808   }
7809 
7810   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7811     if (RetTy->isAnyComplexType())
7812       return complexArgInfo();
7813 
7814     return DefaultABIInfo::classifyArgumentType(RetTy);
7815   }
7816 
7817   // Just copy the original implementations because
7818   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7819   void computeInfo(CGFunctionInfo &FI) const override {
7820     if (!getCXXABI().classifyReturnType(FI))
7821       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7822     for (auto &I : FI.arguments())
7823       I.info = classifyArgumentType(I.type);
7824   }
7825 
7826   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7827                     QualType Ty) const override {
7828     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7829   }
7830 };
7831 
7832 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7833 public:
7834   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7835       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7836   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7837                            CodeGen::CodeGenModule &M) const override;
7838 };
7839 
7840 }
7841 
7842 void MSP430TargetCodeGenInfo::setTargetAttributes(
7843     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7844   if (GV->isDeclaration())
7845     return;
7846   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7847     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7848     if (!InterruptAttr)
7849       return;
7850 
7851     // Handle 'interrupt' attribute:
7852     llvm::Function *F = cast<llvm::Function>(GV);
7853 
7854     // Step 1: Set ISR calling convention.
7855     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7856 
7857     // Step 2: Add attributes goodness.
7858     F->addFnAttr(llvm::Attribute::NoInline);
7859     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7860   }
7861 }
7862 
7863 //===----------------------------------------------------------------------===//
7864 // MIPS ABI Implementation.  This works for both little-endian and
7865 // big-endian variants.
7866 //===----------------------------------------------------------------------===//
7867 
7868 namespace {
7869 class MipsABIInfo : public ABIInfo {
7870   bool IsO32;
7871   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7872   void CoerceToIntArgs(uint64_t TySize,
7873                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7874   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7875   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7876   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7877 public:
7878   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7879     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7880     StackAlignInBytes(IsO32 ? 8 : 16) {}
7881 
7882   ABIArgInfo classifyReturnType(QualType RetTy) const;
7883   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7884   void computeInfo(CGFunctionInfo &FI) const override;
7885   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7886                     QualType Ty) const override;
7887   ABIArgInfo extendType(QualType Ty) const;
7888 };
7889 
7890 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7891   unsigned SizeOfUnwindException;
7892 public:
7893   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7894       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7895         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7896 
7897   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7898     return 29;
7899   }
7900 
7901   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7902                            CodeGen::CodeGenModule &CGM) const override {
7903     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7904     if (!FD) return;
7905     llvm::Function *Fn = cast<llvm::Function>(GV);
7906 
7907     if (FD->hasAttr<MipsLongCallAttr>())
7908       Fn->addFnAttr("long-call");
7909     else if (FD->hasAttr<MipsShortCallAttr>())
7910       Fn->addFnAttr("short-call");
7911 
7912     // Other attributes do not have a meaning for declarations.
7913     if (GV->isDeclaration())
7914       return;
7915 
7916     if (FD->hasAttr<Mips16Attr>()) {
7917       Fn->addFnAttr("mips16");
7918     }
7919     else if (FD->hasAttr<NoMips16Attr>()) {
7920       Fn->addFnAttr("nomips16");
7921     }
7922 
7923     if (FD->hasAttr<MicroMipsAttr>())
7924       Fn->addFnAttr("micromips");
7925     else if (FD->hasAttr<NoMicroMipsAttr>())
7926       Fn->addFnAttr("nomicromips");
7927 
7928     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7929     if (!Attr)
7930       return;
7931 
7932     const char *Kind;
7933     switch (Attr->getInterrupt()) {
7934     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7935     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7936     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7937     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7938     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7939     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7940     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7941     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7942     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7943     }
7944 
7945     Fn->addFnAttr("interrupt", Kind);
7946 
7947   }
7948 
7949   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7950                                llvm::Value *Address) const override;
7951 
7952   unsigned getSizeOfUnwindException() const override {
7953     return SizeOfUnwindException;
7954   }
7955 };
7956 }
7957 
7958 void MipsABIInfo::CoerceToIntArgs(
7959     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7960   llvm::IntegerType *IntTy =
7961     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7962 
7963   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7964   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7965     ArgList.push_back(IntTy);
7966 
7967   // If necessary, add one more integer type to ArgList.
7968   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7969 
7970   if (R)
7971     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7972 }
7973 
7974 // In N32/64, an aligned double precision floating point field is passed in
7975 // a register.
7976 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7977   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7978 
7979   if (IsO32) {
7980     CoerceToIntArgs(TySize, ArgList);
7981     return llvm::StructType::get(getVMContext(), ArgList);
7982   }
7983 
7984   if (Ty->isComplexType())
7985     return CGT.ConvertType(Ty);
7986 
7987   const RecordType *RT = Ty->getAs<RecordType>();
7988 
7989   // Unions/vectors are passed in integer registers.
7990   if (!RT || !RT->isStructureOrClassType()) {
7991     CoerceToIntArgs(TySize, ArgList);
7992     return llvm::StructType::get(getVMContext(), ArgList);
7993   }
7994 
7995   const RecordDecl *RD = RT->getDecl();
7996   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7997   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7998 
7999   uint64_t LastOffset = 0;
8000   unsigned idx = 0;
8001   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
8002 
8003   // Iterate over fields in the struct/class and check if there are any aligned
8004   // double fields.
8005   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
8006        i != e; ++i, ++idx) {
8007     const QualType Ty = i->getType();
8008     const BuiltinType *BT = Ty->getAs<BuiltinType>();
8009 
8010     if (!BT || BT->getKind() != BuiltinType::Double)
8011       continue;
8012 
8013     uint64_t Offset = Layout.getFieldOffset(idx);
8014     if (Offset % 64) // Ignore doubles that are not aligned.
8015       continue;
8016 
8017     // Add ((Offset - LastOffset) / 64) args of type i64.
8018     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
8019       ArgList.push_back(I64);
8020 
8021     // Add double type.
8022     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
8023     LastOffset = Offset + 64;
8024   }
8025 
8026   CoerceToIntArgs(TySize - LastOffset, IntArgList);
8027   ArgList.append(IntArgList.begin(), IntArgList.end());
8028 
8029   return llvm::StructType::get(getVMContext(), ArgList);
8030 }
8031 
8032 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
8033                                         uint64_t Offset) const {
8034   if (OrigOffset + MinABIStackAlignInBytes > Offset)
8035     return nullptr;
8036 
8037   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
8038 }
8039 
8040 ABIArgInfo
8041 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
8042   Ty = useFirstFieldIfTransparentUnion(Ty);
8043 
8044   uint64_t OrigOffset = Offset;
8045   uint64_t TySize = getContext().getTypeSize(Ty);
8046   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
8047 
8048   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
8049                    (uint64_t)StackAlignInBytes);
8050   unsigned CurrOffset = llvm::alignTo(Offset, Align);
8051   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
8052 
8053   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
8054     // Ignore empty aggregates.
8055     if (TySize == 0)
8056       return ABIArgInfo::getIgnore();
8057 
8058     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8059       Offset = OrigOffset + MinABIStackAlignInBytes;
8060       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8061     }
8062 
8063     // If we have reached here, aggregates are passed directly by coercing to
8064     // another structure type. Padding is inserted if the offset of the
8065     // aggregate is unaligned.
8066     ABIArgInfo ArgInfo =
8067         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8068                               getPaddingType(OrigOffset, CurrOffset));
8069     ArgInfo.setInReg(true);
8070     return ArgInfo;
8071   }
8072 
8073   // Treat an enum type as its underlying type.
8074   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8075     Ty = EnumTy->getDecl()->getIntegerType();
8076 
8077   // Make sure we pass indirectly things that are too large.
8078   if (const auto *EIT = Ty->getAs<BitIntType>())
8079     if (EIT->getNumBits() > 128 ||
8080         (EIT->getNumBits() > 64 &&
8081          !getContext().getTargetInfo().hasInt128Type()))
8082       return getNaturalAlignIndirect(Ty);
8083 
8084   // All integral types are promoted to the GPR width.
8085   if (Ty->isIntegralOrEnumerationType())
8086     return extendType(Ty);
8087 
8088   return ABIArgInfo::getDirect(
8089       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8090 }
8091 
8092 llvm::Type*
8093 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8094   const RecordType *RT = RetTy->getAs<RecordType>();
8095   SmallVector<llvm::Type*, 8> RTList;
8096 
8097   if (RT && RT->isStructureOrClassType()) {
8098     const RecordDecl *RD = RT->getDecl();
8099     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8100     unsigned FieldCnt = Layout.getFieldCount();
8101 
8102     // N32/64 returns struct/classes in floating point registers if the
8103     // following conditions are met:
8104     // 1. The size of the struct/class is no larger than 128-bit.
8105     // 2. The struct/class has one or two fields all of which are floating
8106     //    point types.
8107     // 3. The offset of the first field is zero (this follows what gcc does).
8108     //
8109     // Any other composite results are returned in integer registers.
8110     //
8111     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8112       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8113       for (; b != e; ++b) {
8114         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8115 
8116         if (!BT || !BT->isFloatingPoint())
8117           break;
8118 
8119         RTList.push_back(CGT.ConvertType(b->getType()));
8120       }
8121 
8122       if (b == e)
8123         return llvm::StructType::get(getVMContext(), RTList,
8124                                      RD->hasAttr<PackedAttr>());
8125 
8126       RTList.clear();
8127     }
8128   }
8129 
8130   CoerceToIntArgs(Size, RTList);
8131   return llvm::StructType::get(getVMContext(), RTList);
8132 }
8133 
8134 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8135   uint64_t Size = getContext().getTypeSize(RetTy);
8136 
8137   if (RetTy->isVoidType())
8138     return ABIArgInfo::getIgnore();
8139 
8140   // O32 doesn't treat zero-sized structs differently from other structs.
8141   // However, N32/N64 ignores zero sized return values.
8142   if (!IsO32 && Size == 0)
8143     return ABIArgInfo::getIgnore();
8144 
8145   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8146     if (Size <= 128) {
8147       if (RetTy->isAnyComplexType())
8148         return ABIArgInfo::getDirect();
8149 
8150       // O32 returns integer vectors in registers and N32/N64 returns all small
8151       // aggregates in registers.
8152       if (!IsO32 ||
8153           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8154         ABIArgInfo ArgInfo =
8155             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8156         ArgInfo.setInReg(true);
8157         return ArgInfo;
8158       }
8159     }
8160 
8161     return getNaturalAlignIndirect(RetTy);
8162   }
8163 
8164   // Treat an enum type as its underlying type.
8165   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8166     RetTy = EnumTy->getDecl()->getIntegerType();
8167 
8168   // Make sure we pass indirectly things that are too large.
8169   if (const auto *EIT = RetTy->getAs<BitIntType>())
8170     if (EIT->getNumBits() > 128 ||
8171         (EIT->getNumBits() > 64 &&
8172          !getContext().getTargetInfo().hasInt128Type()))
8173       return getNaturalAlignIndirect(RetTy);
8174 
8175   if (isPromotableIntegerTypeForABI(RetTy))
8176     return ABIArgInfo::getExtend(RetTy);
8177 
8178   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8179       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8180     return ABIArgInfo::getSignExtend(RetTy);
8181 
8182   return ABIArgInfo::getDirect();
8183 }
8184 
8185 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8186   ABIArgInfo &RetInfo = FI.getReturnInfo();
8187   if (!getCXXABI().classifyReturnType(FI))
8188     RetInfo = classifyReturnType(FI.getReturnType());
8189 
8190   // Check if a pointer to an aggregate is passed as a hidden argument.
8191   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8192 
8193   for (auto &I : FI.arguments())
8194     I.info = classifyArgumentType(I.type, Offset);
8195 }
8196 
8197 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8198                                QualType OrigTy) const {
8199   QualType Ty = OrigTy;
8200 
8201   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8202   // Pointers are also promoted in the same way but this only matters for N32.
8203   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8204   unsigned PtrWidth = getTarget().getPointerWidth(0);
8205   bool DidPromote = false;
8206   if ((Ty->isIntegerType() &&
8207           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8208       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8209     DidPromote = true;
8210     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8211                                             Ty->isSignedIntegerType());
8212   }
8213 
8214   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8215 
8216   // The alignment of things in the argument area is never larger than
8217   // StackAlignInBytes.
8218   TyInfo.Align =
8219     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8220 
8221   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8222   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8223 
8224   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8225                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8226 
8227 
8228   // If there was a promotion, "unpromote" into a temporary.
8229   // TODO: can we just use a pointer into a subset of the original slot?
8230   if (DidPromote) {
8231     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8232     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8233 
8234     // Truncate down to the right width.
8235     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8236                                                  : CGF.IntPtrTy);
8237     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8238     if (OrigTy->isPointerType())
8239       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8240 
8241     CGF.Builder.CreateStore(V, Temp);
8242     Addr = Temp;
8243   }
8244 
8245   return Addr;
8246 }
8247 
8248 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8249   int TySize = getContext().getTypeSize(Ty);
8250 
8251   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8252   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8253     return ABIArgInfo::getSignExtend(Ty);
8254 
8255   return ABIArgInfo::getExtend(Ty);
8256 }
8257 
8258 bool
8259 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8260                                                llvm::Value *Address) const {
8261   // This information comes from gcc's implementation, which seems to
8262   // as canonical as it gets.
8263 
8264   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8265   // are aliased to pairs of single-precision FP registers.
8266   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8267 
8268   // 0-31 are the general purpose registers, $0 - $31.
8269   // 32-63 are the floating-point registers, $f0 - $f31.
8270   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8271   // 66 is the (notional, I think) register for signal-handler return.
8272   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8273 
8274   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8275   // They are one bit wide and ignored here.
8276 
8277   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8278   // (coprocessor 1 is the FP unit)
8279   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8280   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8281   // 176-181 are the DSP accumulator registers.
8282   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8283   return false;
8284 }
8285 
8286 //===----------------------------------------------------------------------===//
8287 // M68k ABI Implementation
8288 //===----------------------------------------------------------------------===//
8289 
8290 namespace {
8291 
8292 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8293 public:
8294   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8295       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8296   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8297                            CodeGen::CodeGenModule &M) const override;
8298 };
8299 
8300 } // namespace
8301 
8302 void M68kTargetCodeGenInfo::setTargetAttributes(
8303     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8304   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8305     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8306       // Handle 'interrupt' attribute:
8307       llvm::Function *F = cast<llvm::Function>(GV);
8308 
8309       // Step 1: Set ISR calling convention.
8310       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8311 
8312       // Step 2: Add attributes goodness.
8313       F->addFnAttr(llvm::Attribute::NoInline);
8314 
8315       // Step 3: Emit ISR vector alias.
8316       unsigned Num = attr->getNumber() / 2;
8317       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8318                                 "__isr_" + Twine(Num), F);
8319     }
8320   }
8321 }
8322 
8323 //===----------------------------------------------------------------------===//
8324 // AVR ABI Implementation. Documented at
8325 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8326 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8327 //===----------------------------------------------------------------------===//
8328 
8329 namespace {
8330 class AVRABIInfo : public DefaultABIInfo {
8331 private:
8332   // The total amount of registers can be used to pass parameters. It is 18 on
8333   // AVR, or 6 on AVRTiny.
8334   const unsigned ParamRegs;
8335   // The total amount of registers can be used to pass return value. It is 8 on
8336   // AVR, or 4 on AVRTiny.
8337   const unsigned RetRegs;
8338 
8339 public:
8340   AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8341       : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {}
8342 
8343   ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const {
8344     if (isAggregateTypeForABI(Ty)) {
8345       // On AVR, a return struct with size less than or equals to 8 bytes is
8346       // returned directly via registers R18-R25. On AVRTiny, a return struct
8347       // with size less than or equals to 4 bytes is returned directly via
8348       // registers R22-R25.
8349       if (getContext().getTypeSize(Ty) <= RetRegs * 8)
8350         return ABIArgInfo::getDirect();
8351       // A return struct with larger size is returned via a stack
8352       // slot, along with a pointer to it as the function's implicit argument.
8353       LargeRet = true;
8354       return getNaturalAlignIndirect(Ty);
8355     }
8356     // Otherwise we follow the default way which is compatible.
8357     return DefaultABIInfo::classifyReturnType(Ty);
8358   }
8359 
8360   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const {
8361     unsigned TySize = getContext().getTypeSize(Ty);
8362 
8363     // An int8 type argument always costs two registers like an int16.
8364     if (TySize == 8 && NumRegs >= 2) {
8365       NumRegs -= 2;
8366       return ABIArgInfo::getExtend(Ty);
8367     }
8368 
8369     // If the argument size is an odd number of bytes, round up the size
8370     // to the next even number.
8371     TySize = llvm::alignTo(TySize, 16);
8372 
8373     // Any type including an array/struct type can be passed in rgisters,
8374     // if there are enough registers left.
8375     if (TySize <= NumRegs * 8) {
8376       NumRegs -= TySize / 8;
8377       return ABIArgInfo::getDirect();
8378     }
8379 
8380     // An argument is passed either completely in registers or completely in
8381     // memory. Since there are not enough registers left, current argument
8382     // and all other unprocessed arguments should be passed in memory.
8383     // However we still need to return `ABIArgInfo::getDirect()` other than
8384     // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot
8385     // will be allocated, so the stack frame layout will be incompatible with
8386     // avr-gcc.
8387     NumRegs = 0;
8388     return ABIArgInfo::getDirect();
8389   }
8390 
8391   void computeInfo(CGFunctionInfo &FI) const override {
8392     // Decide the return type.
8393     bool LargeRet = false;
8394     if (!getCXXABI().classifyReturnType(FI))
8395       FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet);
8396 
8397     // Decide each argument type. The total number of registers can be used for
8398     // arguments depends on several factors:
8399     // 1. Arguments of varargs functions are passed on the stack. This applies
8400     //    even to the named arguments. So no register can be used.
8401     // 2. Total 18 registers can be used on avr and 6 ones on avrtiny.
8402     // 3. If the return type is a struct with too large size, two registers
8403     //    (out of 18/6) will be cost as an implicit pointer argument.
8404     unsigned NumRegs = ParamRegs;
8405     if (FI.isVariadic())
8406       NumRegs = 0;
8407     else if (LargeRet)
8408       NumRegs -= 2;
8409     for (auto &I : FI.arguments())
8410       I.info = classifyArgumentType(I.type, NumRegs);
8411   }
8412 };
8413 
8414 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8415 public:
8416   AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8417       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {}
8418 
8419   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8420                                   const VarDecl *D) const override {
8421     // Check if global/static variable is defined in address space
8422     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8423     // but not constant.
8424     if (D) {
8425       LangAS AS = D->getType().getAddressSpace();
8426       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8427           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8428         CGM.getDiags().Report(D->getLocation(),
8429                               diag::err_verify_nonconst_addrspace)
8430             << "__flash*";
8431     }
8432     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8433   }
8434 
8435   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8436                            CodeGen::CodeGenModule &CGM) const override {
8437     if (GV->isDeclaration())
8438       return;
8439     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8440     if (!FD) return;
8441     auto *Fn = cast<llvm::Function>(GV);
8442 
8443     if (FD->getAttr<AVRInterruptAttr>())
8444       Fn->addFnAttr("interrupt");
8445 
8446     if (FD->getAttr<AVRSignalAttr>())
8447       Fn->addFnAttr("signal");
8448   }
8449 };
8450 }
8451 
8452 //===----------------------------------------------------------------------===//
8453 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8454 // Currently subclassed only to implement custom OpenCL C function attribute
8455 // handling.
8456 //===----------------------------------------------------------------------===//
8457 
8458 namespace {
8459 
8460 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8461 public:
8462   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8463     : DefaultTargetCodeGenInfo(CGT) {}
8464 
8465   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8466                            CodeGen::CodeGenModule &M) const override;
8467 };
8468 
8469 void TCETargetCodeGenInfo::setTargetAttributes(
8470     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8471   if (GV->isDeclaration())
8472     return;
8473   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8474   if (!FD) return;
8475 
8476   llvm::Function *F = cast<llvm::Function>(GV);
8477 
8478   if (M.getLangOpts().OpenCL) {
8479     if (FD->hasAttr<OpenCLKernelAttr>()) {
8480       // OpenCL C Kernel functions are not subject to inlining
8481       F->addFnAttr(llvm::Attribute::NoInline);
8482       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8483       if (Attr) {
8484         // Convert the reqd_work_group_size() attributes to metadata.
8485         llvm::LLVMContext &Context = F->getContext();
8486         llvm::NamedMDNode *OpenCLMetadata =
8487             M.getModule().getOrInsertNamedMetadata(
8488                 "opencl.kernel_wg_size_info");
8489 
8490         SmallVector<llvm::Metadata *, 5> Operands;
8491         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8492 
8493         Operands.push_back(
8494             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8495                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8496         Operands.push_back(
8497             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8498                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8499         Operands.push_back(
8500             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8501                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8502 
8503         // Add a boolean constant operand for "required" (true) or "hint"
8504         // (false) for implementing the work_group_size_hint attr later.
8505         // Currently always true as the hint is not yet implemented.
8506         Operands.push_back(
8507             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8508         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8509       }
8510     }
8511   }
8512 }
8513 
8514 }
8515 
8516 //===----------------------------------------------------------------------===//
8517 // Hexagon ABI Implementation
8518 //===----------------------------------------------------------------------===//
8519 
8520 namespace {
8521 
8522 class HexagonABIInfo : public DefaultABIInfo {
8523 public:
8524   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8525 
8526 private:
8527   ABIArgInfo classifyReturnType(QualType RetTy) const;
8528   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8529   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8530 
8531   void computeInfo(CGFunctionInfo &FI) const override;
8532 
8533   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8534                     QualType Ty) const override;
8535   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8536                               QualType Ty) const;
8537   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8538                               QualType Ty) const;
8539   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8540                                    QualType Ty) const;
8541 };
8542 
8543 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8544 public:
8545   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8546       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8547 
8548   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8549     return 29;
8550   }
8551 
8552   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8553                            CodeGen::CodeGenModule &GCM) const override {
8554     if (GV->isDeclaration())
8555       return;
8556     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8557     if (!FD)
8558       return;
8559   }
8560 };
8561 
8562 } // namespace
8563 
8564 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8565   unsigned RegsLeft = 6;
8566   if (!getCXXABI().classifyReturnType(FI))
8567     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8568   for (auto &I : FI.arguments())
8569     I.info = classifyArgumentType(I.type, &RegsLeft);
8570 }
8571 
8572 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8573   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8574                        " through registers");
8575 
8576   if (*RegsLeft == 0)
8577     return false;
8578 
8579   if (Size <= 32) {
8580     (*RegsLeft)--;
8581     return true;
8582   }
8583 
8584   if (2 <= (*RegsLeft & (~1U))) {
8585     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8586     return true;
8587   }
8588 
8589   // Next available register was r5 but candidate was greater than 32-bits so it
8590   // has to go on the stack. However we still consume r5
8591   if (*RegsLeft == 1)
8592     *RegsLeft = 0;
8593 
8594   return false;
8595 }
8596 
8597 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8598                                                 unsigned *RegsLeft) const {
8599   if (!isAggregateTypeForABI(Ty)) {
8600     // Treat an enum type as its underlying type.
8601     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8602       Ty = EnumTy->getDecl()->getIntegerType();
8603 
8604     uint64_t Size = getContext().getTypeSize(Ty);
8605     if (Size <= 64)
8606       HexagonAdjustRegsLeft(Size, RegsLeft);
8607 
8608     if (Size > 64 && Ty->isBitIntType())
8609       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8610 
8611     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8612                                              : ABIArgInfo::getDirect();
8613   }
8614 
8615   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8616     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8617 
8618   // Ignore empty records.
8619   if (isEmptyRecord(getContext(), Ty, true))
8620     return ABIArgInfo::getIgnore();
8621 
8622   uint64_t Size = getContext().getTypeSize(Ty);
8623   unsigned Align = getContext().getTypeAlign(Ty);
8624 
8625   if (Size > 64)
8626     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8627 
8628   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8629     Align = Size <= 32 ? 32 : 64;
8630   if (Size <= Align) {
8631     // Pass in the smallest viable integer type.
8632     if (!llvm::isPowerOf2_64(Size))
8633       Size = llvm::NextPowerOf2(Size);
8634     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8635   }
8636   return DefaultABIInfo::classifyArgumentType(Ty);
8637 }
8638 
8639 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8640   if (RetTy->isVoidType())
8641     return ABIArgInfo::getIgnore();
8642 
8643   const TargetInfo &T = CGT.getTarget();
8644   uint64_t Size = getContext().getTypeSize(RetTy);
8645 
8646   if (RetTy->getAs<VectorType>()) {
8647     // HVX vectors are returned in vector registers or register pairs.
8648     if (T.hasFeature("hvx")) {
8649       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8650       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8651       if (Size == VecSize || Size == 2*VecSize)
8652         return ABIArgInfo::getDirectInReg();
8653     }
8654     // Large vector types should be returned via memory.
8655     if (Size > 64)
8656       return getNaturalAlignIndirect(RetTy);
8657   }
8658 
8659   if (!isAggregateTypeForABI(RetTy)) {
8660     // Treat an enum type as its underlying type.
8661     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8662       RetTy = EnumTy->getDecl()->getIntegerType();
8663 
8664     if (Size > 64 && RetTy->isBitIntType())
8665       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8666 
8667     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8668                                                 : ABIArgInfo::getDirect();
8669   }
8670 
8671   if (isEmptyRecord(getContext(), RetTy, true))
8672     return ABIArgInfo::getIgnore();
8673 
8674   // Aggregates <= 8 bytes are returned in registers, other aggregates
8675   // are returned indirectly.
8676   if (Size <= 64) {
8677     // Return in the smallest viable integer type.
8678     if (!llvm::isPowerOf2_64(Size))
8679       Size = llvm::NextPowerOf2(Size);
8680     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8681   }
8682   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8683 }
8684 
8685 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8686                                             Address VAListAddr,
8687                                             QualType Ty) const {
8688   // Load the overflow area pointer.
8689   Address __overflow_area_pointer_p =
8690       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8691   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8692       __overflow_area_pointer_p, "__overflow_area_pointer");
8693 
8694   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8695   if (Align > 4) {
8696     // Alignment should be a power of 2.
8697     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8698 
8699     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8700     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8701 
8702     // Add offset to the current pointer to access the argument.
8703     __overflow_area_pointer =
8704         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8705     llvm::Value *AsInt =
8706         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8707 
8708     // Create a mask which should be "AND"ed
8709     // with (overflow_arg_area + align - 1)
8710     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8711     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8712         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8713         "__overflow_area_pointer.align");
8714   }
8715 
8716   // Get the type of the argument from memory and bitcast
8717   // overflow area pointer to the argument type.
8718   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8719   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8720       Address(__overflow_area_pointer, CGF.Int8Ty,
8721               CharUnits::fromQuantity(Align)),
8722       PTy);
8723 
8724   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8725   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8726 
8727   __overflow_area_pointer = CGF.Builder.CreateGEP(
8728       CGF.Int8Ty, __overflow_area_pointer,
8729       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8730       "__overflow_area_pointer.next");
8731   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8732 
8733   return AddrTyped;
8734 }
8735 
8736 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8737                                             Address VAListAddr,
8738                                             QualType Ty) const {
8739   // FIXME: Need to handle alignment
8740   llvm::Type *BP = CGF.Int8PtrTy;
8741   CGBuilderTy &Builder = CGF.Builder;
8742   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8743   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8744   // Handle address alignment for type alignment > 32 bits
8745   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8746   if (TyAlign > 4) {
8747     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8748     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8749     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8750     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8751     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8752   }
8753   Address AddrTyped = Builder.CreateElementBitCast(
8754       Address(Addr, CGF.Int8Ty, CharUnits::fromQuantity(TyAlign)),
8755       CGF.ConvertType(Ty));
8756 
8757   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8758   llvm::Value *NextAddr = Builder.CreateGEP(
8759       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8760   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8761 
8762   return AddrTyped;
8763 }
8764 
8765 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8766                                                  Address VAListAddr,
8767                                                  QualType Ty) const {
8768   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8769 
8770   if (ArgSize > 8)
8771     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8772 
8773   // Here we have check if the argument is in register area or
8774   // in overflow area.
8775   // If the saved register area pointer + argsize rounded up to alignment >
8776   // saved register area end pointer, argument is in overflow area.
8777   unsigned RegsLeft = 6;
8778   Ty = CGF.getContext().getCanonicalType(Ty);
8779   (void)classifyArgumentType(Ty, &RegsLeft);
8780 
8781   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8782   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8783   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8784   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8785 
8786   // Get rounded size of the argument.GCC does not allow vararg of
8787   // size < 4 bytes. We follow the same logic here.
8788   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8789   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8790 
8791   // Argument may be in saved register area
8792   CGF.EmitBlock(MaybeRegBlock);
8793 
8794   // Load the current saved register area pointer.
8795   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8796       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8797   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8798       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8799 
8800   // Load the saved register area end pointer.
8801   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8802       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8803   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8804       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8805 
8806   // If the size of argument is > 4 bytes, check if the stack
8807   // location is aligned to 8 bytes
8808   if (ArgAlign > 4) {
8809 
8810     llvm::Value *__current_saved_reg_area_pointer_int =
8811         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8812                                    CGF.Int32Ty);
8813 
8814     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8815         __current_saved_reg_area_pointer_int,
8816         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8817         "align_current_saved_reg_area_pointer");
8818 
8819     __current_saved_reg_area_pointer_int =
8820         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8821                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8822                               "align_current_saved_reg_area_pointer");
8823 
8824     __current_saved_reg_area_pointer =
8825         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8826                                    __current_saved_reg_area_pointer->getType(),
8827                                    "align_current_saved_reg_area_pointer");
8828   }
8829 
8830   llvm::Value *__new_saved_reg_area_pointer =
8831       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8832                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8833                             "__new_saved_reg_area_pointer");
8834 
8835   llvm::Value *UsingStack = nullptr;
8836   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8837                                          __saved_reg_area_end_pointer);
8838 
8839   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8840 
8841   // Argument in saved register area
8842   // Implement the block where argument is in register saved area
8843   CGF.EmitBlock(InRegBlock);
8844 
8845   llvm::Type *PTy = CGF.ConvertType(Ty);
8846   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8847       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8848 
8849   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8850                           __current_saved_reg_area_pointer_p);
8851 
8852   CGF.EmitBranch(ContBlock);
8853 
8854   // Argument in overflow area
8855   // Implement the block where the argument is in overflow area.
8856   CGF.EmitBlock(OnStackBlock);
8857 
8858   // Load the overflow area pointer
8859   Address __overflow_area_pointer_p =
8860       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8861   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8862       __overflow_area_pointer_p, "__overflow_area_pointer");
8863 
8864   // Align the overflow area pointer according to the alignment of the argument
8865   if (ArgAlign > 4) {
8866     llvm::Value *__overflow_area_pointer_int =
8867         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8868 
8869     __overflow_area_pointer_int =
8870         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8871                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8872                               "align_overflow_area_pointer");
8873 
8874     __overflow_area_pointer_int =
8875         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8876                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8877                               "align_overflow_area_pointer");
8878 
8879     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8880         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8881         "align_overflow_area_pointer");
8882   }
8883 
8884   // Get the pointer for next argument in overflow area and store it
8885   // to overflow area pointer.
8886   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8887       CGF.Int8Ty, __overflow_area_pointer,
8888       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8889       "__overflow_area_pointer.next");
8890 
8891   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8892                           __overflow_area_pointer_p);
8893 
8894   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8895                           __current_saved_reg_area_pointer_p);
8896 
8897   // Bitcast the overflow area pointer to the type of argument.
8898   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8899   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8900       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8901 
8902   CGF.EmitBranch(ContBlock);
8903 
8904   // Get the correct pointer to load the variable argument
8905   // Implement the ContBlock
8906   CGF.EmitBlock(ContBlock);
8907 
8908   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
8909   llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy);
8910   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8911   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8912   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8913 
8914   return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign));
8915 }
8916 
8917 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8918                                   QualType Ty) const {
8919 
8920   if (getTarget().getTriple().isMusl())
8921     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8922 
8923   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8924 }
8925 
8926 //===----------------------------------------------------------------------===//
8927 // Lanai ABI Implementation
8928 //===----------------------------------------------------------------------===//
8929 
8930 namespace {
8931 class LanaiABIInfo : public DefaultABIInfo {
8932 public:
8933   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8934 
8935   bool shouldUseInReg(QualType Ty, CCState &State) const;
8936 
8937   void computeInfo(CGFunctionInfo &FI) const override {
8938     CCState State(FI);
8939     // Lanai uses 4 registers to pass arguments unless the function has the
8940     // regparm attribute set.
8941     if (FI.getHasRegParm()) {
8942       State.FreeRegs = FI.getRegParm();
8943     } else {
8944       State.FreeRegs = 4;
8945     }
8946 
8947     if (!getCXXABI().classifyReturnType(FI))
8948       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8949     for (auto &I : FI.arguments())
8950       I.info = classifyArgumentType(I.type, State);
8951   }
8952 
8953   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8954   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8955 };
8956 } // end anonymous namespace
8957 
8958 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8959   unsigned Size = getContext().getTypeSize(Ty);
8960   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8961 
8962   if (SizeInRegs == 0)
8963     return false;
8964 
8965   if (SizeInRegs > State.FreeRegs) {
8966     State.FreeRegs = 0;
8967     return false;
8968   }
8969 
8970   State.FreeRegs -= SizeInRegs;
8971 
8972   return true;
8973 }
8974 
8975 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8976                                            CCState &State) const {
8977   if (!ByVal) {
8978     if (State.FreeRegs) {
8979       --State.FreeRegs; // Non-byval indirects just use one pointer.
8980       return getNaturalAlignIndirectInReg(Ty);
8981     }
8982     return getNaturalAlignIndirect(Ty, false);
8983   }
8984 
8985   // Compute the byval alignment.
8986   const unsigned MinABIStackAlignInBytes = 4;
8987   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8988   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8989                                  /*Realign=*/TypeAlign >
8990                                      MinABIStackAlignInBytes);
8991 }
8992 
8993 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8994                                               CCState &State) const {
8995   // Check with the C++ ABI first.
8996   const RecordType *RT = Ty->getAs<RecordType>();
8997   if (RT) {
8998     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8999     if (RAA == CGCXXABI::RAA_Indirect) {
9000       return getIndirectResult(Ty, /*ByVal=*/false, State);
9001     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
9002       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
9003     }
9004   }
9005 
9006   if (isAggregateTypeForABI(Ty)) {
9007     // Structures with flexible arrays are always indirect.
9008     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9009       return getIndirectResult(Ty, /*ByVal=*/true, State);
9010 
9011     // Ignore empty structs/unions.
9012     if (isEmptyRecord(getContext(), Ty, true))
9013       return ABIArgInfo::getIgnore();
9014 
9015     llvm::LLVMContext &LLVMContext = getVMContext();
9016     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
9017     if (SizeInRegs <= State.FreeRegs) {
9018       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9019       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9020       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9021       State.FreeRegs -= SizeInRegs;
9022       return ABIArgInfo::getDirectInReg(Result);
9023     } else {
9024       State.FreeRegs = 0;
9025     }
9026     return getIndirectResult(Ty, true, State);
9027   }
9028 
9029   // Treat an enum type as its underlying type.
9030   if (const auto *EnumTy = Ty->getAs<EnumType>())
9031     Ty = EnumTy->getDecl()->getIntegerType();
9032 
9033   bool InReg = shouldUseInReg(Ty, State);
9034 
9035   // Don't pass >64 bit integers in registers.
9036   if (const auto *EIT = Ty->getAs<BitIntType>())
9037     if (EIT->getNumBits() > 64)
9038       return getIndirectResult(Ty, /*ByVal=*/true, State);
9039 
9040   if (isPromotableIntegerTypeForABI(Ty)) {
9041     if (InReg)
9042       return ABIArgInfo::getDirectInReg();
9043     return ABIArgInfo::getExtend(Ty);
9044   }
9045   if (InReg)
9046     return ABIArgInfo::getDirectInReg();
9047   return ABIArgInfo::getDirect();
9048 }
9049 
9050 namespace {
9051 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
9052 public:
9053   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9054       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
9055 };
9056 }
9057 
9058 //===----------------------------------------------------------------------===//
9059 // AMDGPU ABI Implementation
9060 //===----------------------------------------------------------------------===//
9061 
9062 namespace {
9063 
9064 class AMDGPUABIInfo final : public DefaultABIInfo {
9065 private:
9066   static const unsigned MaxNumRegsForArgsRet = 16;
9067 
9068   unsigned numRegsForType(QualType Ty) const;
9069 
9070   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
9071   bool isHomogeneousAggregateSmallEnough(const Type *Base,
9072                                          uint64_t Members) const override;
9073 
9074   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
9075   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
9076                                        unsigned ToAS) const {
9077     // Single value types.
9078     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
9079     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
9080       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
9081     return Ty;
9082   }
9083 
9084 public:
9085   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
9086     DefaultABIInfo(CGT) {}
9087 
9088   ABIArgInfo classifyReturnType(QualType RetTy) const;
9089   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
9090   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
9091 
9092   void computeInfo(CGFunctionInfo &FI) const override;
9093   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9094                     QualType Ty) const override;
9095 };
9096 
9097 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
9098   return true;
9099 }
9100 
9101 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
9102   const Type *Base, uint64_t Members) const {
9103   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
9104 
9105   // Homogeneous Aggregates may occupy at most 16 registers.
9106   return Members * NumRegs <= MaxNumRegsForArgsRet;
9107 }
9108 
9109 /// Estimate number of registers the type will use when passed in registers.
9110 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
9111   unsigned NumRegs = 0;
9112 
9113   if (const VectorType *VT = Ty->getAs<VectorType>()) {
9114     // Compute from the number of elements. The reported size is based on the
9115     // in-memory size, which includes the padding 4th element for 3-vectors.
9116     QualType EltTy = VT->getElementType();
9117     unsigned EltSize = getContext().getTypeSize(EltTy);
9118 
9119     // 16-bit element vectors should be passed as packed.
9120     if (EltSize == 16)
9121       return (VT->getNumElements() + 1) / 2;
9122 
9123     unsigned EltNumRegs = (EltSize + 31) / 32;
9124     return EltNumRegs * VT->getNumElements();
9125   }
9126 
9127   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9128     const RecordDecl *RD = RT->getDecl();
9129     assert(!RD->hasFlexibleArrayMember());
9130 
9131     for (const FieldDecl *Field : RD->fields()) {
9132       QualType FieldTy = Field->getType();
9133       NumRegs += numRegsForType(FieldTy);
9134     }
9135 
9136     return NumRegs;
9137   }
9138 
9139   return (getContext().getTypeSize(Ty) + 31) / 32;
9140 }
9141 
9142 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9143   llvm::CallingConv::ID CC = FI.getCallingConvention();
9144 
9145   if (!getCXXABI().classifyReturnType(FI))
9146     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9147 
9148   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9149   for (auto &Arg : FI.arguments()) {
9150     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9151       Arg.info = classifyKernelArgumentType(Arg.type);
9152     } else {
9153       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9154     }
9155   }
9156 }
9157 
9158 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9159                                  QualType Ty) const {
9160   llvm_unreachable("AMDGPU does not support varargs");
9161 }
9162 
9163 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9164   if (isAggregateTypeForABI(RetTy)) {
9165     // Records with non-trivial destructors/copy-constructors should not be
9166     // returned by value.
9167     if (!getRecordArgABI(RetTy, getCXXABI())) {
9168       // Ignore empty structs/unions.
9169       if (isEmptyRecord(getContext(), RetTy, true))
9170         return ABIArgInfo::getIgnore();
9171 
9172       // Lower single-element structs to just return a regular value.
9173       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9174         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9175 
9176       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9177         const RecordDecl *RD = RT->getDecl();
9178         if (RD->hasFlexibleArrayMember())
9179           return DefaultABIInfo::classifyReturnType(RetTy);
9180       }
9181 
9182       // Pack aggregates <= 4 bytes into single VGPR or pair.
9183       uint64_t Size = getContext().getTypeSize(RetTy);
9184       if (Size <= 16)
9185         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9186 
9187       if (Size <= 32)
9188         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9189 
9190       if (Size <= 64) {
9191         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9192         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9193       }
9194 
9195       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9196         return ABIArgInfo::getDirect();
9197     }
9198   }
9199 
9200   // Otherwise just do the default thing.
9201   return DefaultABIInfo::classifyReturnType(RetTy);
9202 }
9203 
9204 /// For kernels all parameters are really passed in a special buffer. It doesn't
9205 /// make sense to pass anything byval, so everything must be direct.
9206 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9207   Ty = useFirstFieldIfTransparentUnion(Ty);
9208 
9209   // TODO: Can we omit empty structs?
9210 
9211   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9212     Ty = QualType(SeltTy, 0);
9213 
9214   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9215   llvm::Type *LTy = OrigLTy;
9216   if (getContext().getLangOpts().HIP) {
9217     LTy = coerceKernelArgumentType(
9218         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9219         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9220   }
9221 
9222   // FIXME: Should also use this for OpenCL, but it requires addressing the
9223   // problem of kernels being called.
9224   //
9225   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9226   // to global address space when using byref. This would require implementing a
9227   // new kind of coercion of the in-memory type when for indirect arguments.
9228   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9229       isAggregateTypeForABI(Ty)) {
9230     return ABIArgInfo::getIndirectAliased(
9231         getContext().getTypeAlignInChars(Ty),
9232         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9233         false /*Realign*/, nullptr /*Padding*/);
9234   }
9235 
9236   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9237   // individual elements, which confuses the Clover OpenCL backend; therefore we
9238   // have to set it to false here. Other args of getDirect() are just defaults.
9239   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9240 }
9241 
9242 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9243                                                unsigned &NumRegsLeft) const {
9244   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9245 
9246   Ty = useFirstFieldIfTransparentUnion(Ty);
9247 
9248   if (isAggregateTypeForABI(Ty)) {
9249     // Records with non-trivial destructors/copy-constructors should not be
9250     // passed by value.
9251     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9252       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9253 
9254     // Ignore empty structs/unions.
9255     if (isEmptyRecord(getContext(), Ty, true))
9256       return ABIArgInfo::getIgnore();
9257 
9258     // Lower single-element structs to just pass a regular value. TODO: We
9259     // could do reasonable-size multiple-element structs too, using getExpand(),
9260     // though watch out for things like bitfields.
9261     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9262       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9263 
9264     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9265       const RecordDecl *RD = RT->getDecl();
9266       if (RD->hasFlexibleArrayMember())
9267         return DefaultABIInfo::classifyArgumentType(Ty);
9268     }
9269 
9270     // Pack aggregates <= 8 bytes into single VGPR or pair.
9271     uint64_t Size = getContext().getTypeSize(Ty);
9272     if (Size <= 64) {
9273       unsigned NumRegs = (Size + 31) / 32;
9274       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9275 
9276       if (Size <= 16)
9277         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9278 
9279       if (Size <= 32)
9280         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9281 
9282       // XXX: Should this be i64 instead, and should the limit increase?
9283       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9284       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9285     }
9286 
9287     if (NumRegsLeft > 0) {
9288       unsigned NumRegs = numRegsForType(Ty);
9289       if (NumRegsLeft >= NumRegs) {
9290         NumRegsLeft -= NumRegs;
9291         return ABIArgInfo::getDirect();
9292       }
9293     }
9294   }
9295 
9296   // Otherwise just do the default thing.
9297   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9298   if (!ArgInfo.isIndirect()) {
9299     unsigned NumRegs = numRegsForType(Ty);
9300     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9301   }
9302 
9303   return ArgInfo;
9304 }
9305 
9306 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9307 public:
9308   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9309       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9310 
9311   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9312                                  CodeGenModule &CGM) const;
9313 
9314   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9315                            CodeGen::CodeGenModule &M) const override;
9316   unsigned getOpenCLKernelCallingConv() const override;
9317 
9318   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9319       llvm::PointerType *T, QualType QT) const override;
9320 
9321   LangAS getASTAllocaAddressSpace() const override {
9322     return getLangASFromTargetAS(
9323         getABIInfo().getDataLayout().getAllocaAddrSpace());
9324   }
9325   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9326                                   const VarDecl *D) const override;
9327   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9328                                          SyncScope Scope,
9329                                          llvm::AtomicOrdering Ordering,
9330                                          llvm::LLVMContext &Ctx) const override;
9331   llvm::Function *
9332   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9333                             llvm::Function *BlockInvokeFunc,
9334                             llvm::Type *BlockTy) const override;
9335   bool shouldEmitStaticExternCAliases() const override;
9336   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9337 };
9338 }
9339 
9340 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9341                                               llvm::GlobalValue *GV) {
9342   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9343     return false;
9344 
9345   return D->hasAttr<OpenCLKernelAttr>() ||
9346          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9347          (isa<VarDecl>(D) &&
9348           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9349            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9350            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9351 }
9352 
9353 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9354     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9355   const auto *ReqdWGS =
9356       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9357   const bool IsOpenCLKernel =
9358       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9359   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9360 
9361   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9362   if (ReqdWGS || FlatWGS) {
9363     unsigned Min = 0;
9364     unsigned Max = 0;
9365     if (FlatWGS) {
9366       Min = FlatWGS->getMin()
9367                 ->EvaluateKnownConstInt(M.getContext())
9368                 .getExtValue();
9369       Max = FlatWGS->getMax()
9370                 ->EvaluateKnownConstInt(M.getContext())
9371                 .getExtValue();
9372     }
9373     if (ReqdWGS && Min == 0 && Max == 0)
9374       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9375 
9376     if (Min != 0) {
9377       assert(Min <= Max && "Min must be less than or equal Max");
9378 
9379       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9380       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9381     } else
9382       assert(Max == 0 && "Max must be zero");
9383   } else if (IsOpenCLKernel || IsHIPKernel) {
9384     // By default, restrict the maximum size to a value specified by
9385     // --gpu-max-threads-per-block=n or its default value for HIP.
9386     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9387     const unsigned DefaultMaxWorkGroupSize =
9388         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9389                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9390     std::string AttrVal =
9391         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9392     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9393   }
9394 
9395   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9396     unsigned Min =
9397         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9398     unsigned Max = Attr->getMax() ? Attr->getMax()
9399                                         ->EvaluateKnownConstInt(M.getContext())
9400                                         .getExtValue()
9401                                   : 0;
9402 
9403     if (Min != 0) {
9404       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9405 
9406       std::string AttrVal = llvm::utostr(Min);
9407       if (Max != 0)
9408         AttrVal = AttrVal + "," + llvm::utostr(Max);
9409       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9410     } else
9411       assert(Max == 0 && "Max must be zero");
9412   }
9413 
9414   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9415     unsigned NumSGPR = Attr->getNumSGPR();
9416 
9417     if (NumSGPR != 0)
9418       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9419   }
9420 
9421   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9422     uint32_t NumVGPR = Attr->getNumVGPR();
9423 
9424     if (NumVGPR != 0)
9425       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9426   }
9427 }
9428 
9429 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9430     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9431   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9432     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9433     GV->setDSOLocal(true);
9434   }
9435 
9436   if (GV->isDeclaration())
9437     return;
9438 
9439   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9440   if (!F)
9441     return;
9442 
9443   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9444   if (FD)
9445     setFunctionDeclAttributes(FD, F, M);
9446 
9447   const bool IsHIPKernel =
9448       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9449 
9450   if (IsHIPKernel)
9451     F->addFnAttr("uniform-work-group-size", "true");
9452 
9453   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9454     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9455 
9456   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9457     F->addFnAttr("amdgpu-ieee", "false");
9458 }
9459 
9460 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9461   return llvm::CallingConv::AMDGPU_KERNEL;
9462 }
9463 
9464 // Currently LLVM assumes null pointers always have value 0,
9465 // which results in incorrectly transformed IR. Therefore, instead of
9466 // emitting null pointers in private and local address spaces, a null
9467 // pointer in generic address space is emitted which is casted to a
9468 // pointer in local or private address space.
9469 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9470     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9471     QualType QT) const {
9472   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9473     return llvm::ConstantPointerNull::get(PT);
9474 
9475   auto &Ctx = CGM.getContext();
9476   auto NPT = llvm::PointerType::getWithSamePointeeType(
9477       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9478   return llvm::ConstantExpr::getAddrSpaceCast(
9479       llvm::ConstantPointerNull::get(NPT), PT);
9480 }
9481 
9482 LangAS
9483 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9484                                                   const VarDecl *D) const {
9485   assert(!CGM.getLangOpts().OpenCL &&
9486          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9487          "Address space agnostic languages only");
9488   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9489       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9490   if (!D)
9491     return DefaultGlobalAS;
9492 
9493   LangAS AddrSpace = D->getType().getAddressSpace();
9494   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9495   if (AddrSpace != LangAS::Default)
9496     return AddrSpace;
9497 
9498   // Only promote to address space 4 if VarDecl has constant initialization.
9499   if (CGM.isTypeConstant(D->getType(), false) &&
9500       D->hasConstantInitialization()) {
9501     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9502       return *ConstAS;
9503   }
9504   return DefaultGlobalAS;
9505 }
9506 
9507 llvm::SyncScope::ID
9508 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9509                                             SyncScope Scope,
9510                                             llvm::AtomicOrdering Ordering,
9511                                             llvm::LLVMContext &Ctx) const {
9512   std::string Name;
9513   switch (Scope) {
9514   case SyncScope::HIPSingleThread:
9515     Name = "singlethread";
9516     break;
9517   case SyncScope::HIPWavefront:
9518   case SyncScope::OpenCLSubGroup:
9519     Name = "wavefront";
9520     break;
9521   case SyncScope::HIPWorkgroup:
9522   case SyncScope::OpenCLWorkGroup:
9523     Name = "workgroup";
9524     break;
9525   case SyncScope::HIPAgent:
9526   case SyncScope::OpenCLDevice:
9527     Name = "agent";
9528     break;
9529   case SyncScope::HIPSystem:
9530   case SyncScope::OpenCLAllSVMDevices:
9531     Name = "";
9532     break;
9533   }
9534 
9535   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9536     if (!Name.empty())
9537       Name = Twine(Twine(Name) + Twine("-")).str();
9538 
9539     Name = Twine(Twine(Name) + Twine("one-as")).str();
9540   }
9541 
9542   return Ctx.getOrInsertSyncScopeID(Name);
9543 }
9544 
9545 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9546   return false;
9547 }
9548 
9549 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9550     const FunctionType *&FT) const {
9551   FT = getABIInfo().getContext().adjustFunctionType(
9552       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9553 }
9554 
9555 //===----------------------------------------------------------------------===//
9556 // SPARC v8 ABI Implementation.
9557 // Based on the SPARC Compliance Definition version 2.4.1.
9558 //
9559 // Ensures that complex values are passed in registers.
9560 //
9561 namespace {
9562 class SparcV8ABIInfo : public DefaultABIInfo {
9563 public:
9564   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9565 
9566 private:
9567   ABIArgInfo classifyReturnType(QualType RetTy) const;
9568   void computeInfo(CGFunctionInfo &FI) const override;
9569 };
9570 } // end anonymous namespace
9571 
9572 
9573 ABIArgInfo
9574 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9575   if (Ty->isAnyComplexType()) {
9576     return ABIArgInfo::getDirect();
9577   }
9578   else {
9579     return DefaultABIInfo::classifyReturnType(Ty);
9580   }
9581 }
9582 
9583 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9584 
9585   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9586   for (auto &Arg : FI.arguments())
9587     Arg.info = classifyArgumentType(Arg.type);
9588 }
9589 
9590 namespace {
9591 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9592 public:
9593   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9594       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9595 
9596   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9597                                    llvm::Value *Address) const override {
9598     int Offset;
9599     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9600       Offset = 12;
9601     else
9602       Offset = 8;
9603     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9604                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9605   }
9606 
9607   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9608                                    llvm::Value *Address) const override {
9609     int Offset;
9610     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9611       Offset = -12;
9612     else
9613       Offset = -8;
9614     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9615                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9616   }
9617 };
9618 } // end anonymous namespace
9619 
9620 //===----------------------------------------------------------------------===//
9621 // SPARC v9 ABI Implementation.
9622 // Based on the SPARC Compliance Definition version 2.4.1.
9623 //
9624 // Function arguments a mapped to a nominal "parameter array" and promoted to
9625 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9626 // the array, structs larger than 16 bytes are passed indirectly.
9627 //
9628 // One case requires special care:
9629 //
9630 //   struct mixed {
9631 //     int i;
9632 //     float f;
9633 //   };
9634 //
9635 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9636 // parameter array, but the int is passed in an integer register, and the float
9637 // is passed in a floating point register. This is represented as two arguments
9638 // with the LLVM IR inreg attribute:
9639 //
9640 //   declare void f(i32 inreg %i, float inreg %f)
9641 //
9642 // The code generator will only allocate 4 bytes from the parameter array for
9643 // the inreg arguments. All other arguments are allocated a multiple of 8
9644 // bytes.
9645 //
9646 namespace {
9647 class SparcV9ABIInfo : public ABIInfo {
9648 public:
9649   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9650 
9651 private:
9652   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9653   void computeInfo(CGFunctionInfo &FI) const override;
9654   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9655                     QualType Ty) const override;
9656 
9657   // Coercion type builder for structs passed in registers. The coercion type
9658   // serves two purposes:
9659   //
9660   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9661   //    in registers.
9662   // 2. Expose aligned floating point elements as first-level elements, so the
9663   //    code generator knows to pass them in floating point registers.
9664   //
9665   // We also compute the InReg flag which indicates that the struct contains
9666   // aligned 32-bit floats.
9667   //
9668   struct CoerceBuilder {
9669     llvm::LLVMContext &Context;
9670     const llvm::DataLayout &DL;
9671     SmallVector<llvm::Type*, 8> Elems;
9672     uint64_t Size;
9673     bool InReg;
9674 
9675     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9676       : Context(c), DL(dl), Size(0), InReg(false) {}
9677 
9678     // Pad Elems with integers until Size is ToSize.
9679     void pad(uint64_t ToSize) {
9680       assert(ToSize >= Size && "Cannot remove elements");
9681       if (ToSize == Size)
9682         return;
9683 
9684       // Finish the current 64-bit word.
9685       uint64_t Aligned = llvm::alignTo(Size, 64);
9686       if (Aligned > Size && Aligned <= ToSize) {
9687         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9688         Size = Aligned;
9689       }
9690 
9691       // Add whole 64-bit words.
9692       while (Size + 64 <= ToSize) {
9693         Elems.push_back(llvm::Type::getInt64Ty(Context));
9694         Size += 64;
9695       }
9696 
9697       // Final in-word padding.
9698       if (Size < ToSize) {
9699         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9700         Size = ToSize;
9701       }
9702     }
9703 
9704     // Add a floating point element at Offset.
9705     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9706       // Unaligned floats are treated as integers.
9707       if (Offset % Bits)
9708         return;
9709       // The InReg flag is only required if there are any floats < 64 bits.
9710       if (Bits < 64)
9711         InReg = true;
9712       pad(Offset);
9713       Elems.push_back(Ty);
9714       Size = Offset + Bits;
9715     }
9716 
9717     // Add a struct type to the coercion type, starting at Offset (in bits).
9718     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9719       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9720       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9721         llvm::Type *ElemTy = StrTy->getElementType(i);
9722         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9723         switch (ElemTy->getTypeID()) {
9724         case llvm::Type::StructTyID:
9725           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9726           break;
9727         case llvm::Type::FloatTyID:
9728           addFloat(ElemOffset, ElemTy, 32);
9729           break;
9730         case llvm::Type::DoubleTyID:
9731           addFloat(ElemOffset, ElemTy, 64);
9732           break;
9733         case llvm::Type::FP128TyID:
9734           addFloat(ElemOffset, ElemTy, 128);
9735           break;
9736         case llvm::Type::PointerTyID:
9737           if (ElemOffset % 64 == 0) {
9738             pad(ElemOffset);
9739             Elems.push_back(ElemTy);
9740             Size += 64;
9741           }
9742           break;
9743         default:
9744           break;
9745         }
9746       }
9747     }
9748 
9749     // Check if Ty is a usable substitute for the coercion type.
9750     bool isUsableType(llvm::StructType *Ty) const {
9751       return llvm::makeArrayRef(Elems) == Ty->elements();
9752     }
9753 
9754     // Get the coercion type as a literal struct type.
9755     llvm::Type *getType() const {
9756       if (Elems.size() == 1)
9757         return Elems.front();
9758       else
9759         return llvm::StructType::get(Context, Elems);
9760     }
9761   };
9762 };
9763 } // end anonymous namespace
9764 
9765 ABIArgInfo
9766 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9767   if (Ty->isVoidType())
9768     return ABIArgInfo::getIgnore();
9769 
9770   uint64_t Size = getContext().getTypeSize(Ty);
9771 
9772   // Anything too big to fit in registers is passed with an explicit indirect
9773   // pointer / sret pointer.
9774   if (Size > SizeLimit)
9775     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9776 
9777   // Treat an enum type as its underlying type.
9778   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9779     Ty = EnumTy->getDecl()->getIntegerType();
9780 
9781   // Integer types smaller than a register are extended.
9782   if (Size < 64 && Ty->isIntegerType())
9783     return ABIArgInfo::getExtend(Ty);
9784 
9785   if (const auto *EIT = Ty->getAs<BitIntType>())
9786     if (EIT->getNumBits() < 64)
9787       return ABIArgInfo::getExtend(Ty);
9788 
9789   // Other non-aggregates go in registers.
9790   if (!isAggregateTypeForABI(Ty))
9791     return ABIArgInfo::getDirect();
9792 
9793   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9794   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9795   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9796     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9797 
9798   // This is a small aggregate type that should be passed in registers.
9799   // Build a coercion type from the LLVM struct type.
9800   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9801   if (!StrTy)
9802     return ABIArgInfo::getDirect();
9803 
9804   CoerceBuilder CB(getVMContext(), getDataLayout());
9805   CB.addStruct(0, StrTy);
9806   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9807 
9808   // Try to use the original type for coercion.
9809   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9810 
9811   if (CB.InReg)
9812     return ABIArgInfo::getDirectInReg(CoerceTy);
9813   else
9814     return ABIArgInfo::getDirect(CoerceTy);
9815 }
9816 
9817 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9818                                   QualType Ty) const {
9819   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9820   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9821   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9822     AI.setCoerceToType(ArgTy);
9823 
9824   CharUnits SlotSize = CharUnits::fromQuantity(8);
9825 
9826   CGBuilderTy &Builder = CGF.Builder;
9827   Address Addr = Address(Builder.CreateLoad(VAListAddr, "ap.cur"),
9828                          getVAListElementType(CGF), SlotSize);
9829   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9830 
9831   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9832 
9833   Address ArgAddr = Address::invalid();
9834   CharUnits Stride;
9835   switch (AI.getKind()) {
9836   case ABIArgInfo::Expand:
9837   case ABIArgInfo::CoerceAndExpand:
9838   case ABIArgInfo::InAlloca:
9839     llvm_unreachable("Unsupported ABI kind for va_arg");
9840 
9841   case ABIArgInfo::Extend: {
9842     Stride = SlotSize;
9843     CharUnits Offset = SlotSize - TypeInfo.Width;
9844     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9845     break;
9846   }
9847 
9848   case ABIArgInfo::Direct: {
9849     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9850     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9851     ArgAddr = Addr;
9852     break;
9853   }
9854 
9855   case ABIArgInfo::Indirect:
9856   case ABIArgInfo::IndirectAliased:
9857     Stride = SlotSize;
9858     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9859     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), ArgTy,
9860                       TypeInfo.Align);
9861     break;
9862 
9863   case ABIArgInfo::Ignore:
9864     return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align);
9865   }
9866 
9867   // Update VAList.
9868   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9869   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9870 
9871   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9872 }
9873 
9874 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9875   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9876   for (auto &I : FI.arguments())
9877     I.info = classifyType(I.type, 16 * 8);
9878 }
9879 
9880 namespace {
9881 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9882 public:
9883   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9884       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9885 
9886   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9887     return 14;
9888   }
9889 
9890   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9891                                llvm::Value *Address) const override;
9892 
9893   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9894                                    llvm::Value *Address) const override {
9895     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9896                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9897   }
9898 
9899   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9900                                    llvm::Value *Address) const override {
9901     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9902                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9903   }
9904 };
9905 } // end anonymous namespace
9906 
9907 bool
9908 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9909                                                 llvm::Value *Address) const {
9910   // This is calculated from the LLVM and GCC tables and verified
9911   // against gcc output.  AFAIK all ABIs use the same encoding.
9912 
9913   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9914 
9915   llvm::IntegerType *i8 = CGF.Int8Ty;
9916   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9917   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9918 
9919   // 0-31: the 8-byte general-purpose registers
9920   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9921 
9922   // 32-63: f0-31, the 4-byte floating-point registers
9923   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9924 
9925   //   Y   = 64
9926   //   PSR = 65
9927   //   WIM = 66
9928   //   TBR = 67
9929   //   PC  = 68
9930   //   NPC = 69
9931   //   FSR = 70
9932   //   CSR = 71
9933   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9934 
9935   // 72-87: d0-15, the 8-byte floating-point registers
9936   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9937 
9938   return false;
9939 }
9940 
9941 // ARC ABI implementation.
9942 namespace {
9943 
9944 class ARCABIInfo : public DefaultABIInfo {
9945 public:
9946   using DefaultABIInfo::DefaultABIInfo;
9947 
9948 private:
9949   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9950                     QualType Ty) const override;
9951 
9952   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9953     if (!State.FreeRegs)
9954       return;
9955     if (Info.isIndirect() && Info.getInReg())
9956       State.FreeRegs--;
9957     else if (Info.isDirect() && Info.getInReg()) {
9958       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9959       if (sz < State.FreeRegs)
9960         State.FreeRegs -= sz;
9961       else
9962         State.FreeRegs = 0;
9963     }
9964   }
9965 
9966   void computeInfo(CGFunctionInfo &FI) const override {
9967     CCState State(FI);
9968     // ARC uses 8 registers to pass arguments.
9969     State.FreeRegs = 8;
9970 
9971     if (!getCXXABI().classifyReturnType(FI))
9972       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9973     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9974     for (auto &I : FI.arguments()) {
9975       I.info = classifyArgumentType(I.type, State.FreeRegs);
9976       updateState(I.info, I.type, State);
9977     }
9978   }
9979 
9980   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9981   ABIArgInfo getIndirectByValue(QualType Ty) const;
9982   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9983   ABIArgInfo classifyReturnType(QualType RetTy) const;
9984 };
9985 
9986 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9987 public:
9988   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9989       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9990 };
9991 
9992 
9993 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9994   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9995                        getNaturalAlignIndirect(Ty, false);
9996 }
9997 
9998 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9999   // Compute the byval alignment.
10000   const unsigned MinABIStackAlignInBytes = 4;
10001   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
10002   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
10003                                  TypeAlign > MinABIStackAlignInBytes);
10004 }
10005 
10006 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10007                               QualType Ty) const {
10008   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
10009                           getContext().getTypeInfoInChars(Ty),
10010                           CharUnits::fromQuantity(4), true);
10011 }
10012 
10013 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
10014                                             uint8_t FreeRegs) const {
10015   // Handle the generic C++ ABI.
10016   const RecordType *RT = Ty->getAs<RecordType>();
10017   if (RT) {
10018     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
10019     if (RAA == CGCXXABI::RAA_Indirect)
10020       return getIndirectByRef(Ty, FreeRegs > 0);
10021 
10022     if (RAA == CGCXXABI::RAA_DirectInMemory)
10023       return getIndirectByValue(Ty);
10024   }
10025 
10026   // Treat an enum type as its underlying type.
10027   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10028     Ty = EnumTy->getDecl()->getIntegerType();
10029 
10030   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
10031 
10032   if (isAggregateTypeForABI(Ty)) {
10033     // Structures with flexible arrays are always indirect.
10034     if (RT && RT->getDecl()->hasFlexibleArrayMember())
10035       return getIndirectByValue(Ty);
10036 
10037     // Ignore empty structs/unions.
10038     if (isEmptyRecord(getContext(), Ty, true))
10039       return ABIArgInfo::getIgnore();
10040 
10041     llvm::LLVMContext &LLVMContext = getVMContext();
10042 
10043     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
10044     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
10045     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
10046 
10047     return FreeRegs >= SizeInRegs ?
10048         ABIArgInfo::getDirectInReg(Result) :
10049         ABIArgInfo::getDirect(Result, 0, nullptr, false);
10050   }
10051 
10052   if (const auto *EIT = Ty->getAs<BitIntType>())
10053     if (EIT->getNumBits() > 64)
10054       return getIndirectByValue(Ty);
10055 
10056   return isPromotableIntegerTypeForABI(Ty)
10057              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
10058                                        : ABIArgInfo::getExtend(Ty))
10059              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
10060                                        : ABIArgInfo::getDirect());
10061 }
10062 
10063 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
10064   if (RetTy->isAnyComplexType())
10065     return ABIArgInfo::getDirectInReg();
10066 
10067   // Arguments of size > 4 registers are indirect.
10068   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
10069   if (RetSize > 4)
10070     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
10071 
10072   return DefaultABIInfo::classifyReturnType(RetTy);
10073 }
10074 
10075 } // End anonymous namespace.
10076 
10077 //===----------------------------------------------------------------------===//
10078 // XCore ABI Implementation
10079 //===----------------------------------------------------------------------===//
10080 
10081 namespace {
10082 
10083 /// A SmallStringEnc instance is used to build up the TypeString by passing
10084 /// it by reference between functions that append to it.
10085 typedef llvm::SmallString<128> SmallStringEnc;
10086 
10087 /// TypeStringCache caches the meta encodings of Types.
10088 ///
10089 /// The reason for caching TypeStrings is two fold:
10090 ///   1. To cache a type's encoding for later uses;
10091 ///   2. As a means to break recursive member type inclusion.
10092 ///
10093 /// A cache Entry can have a Status of:
10094 ///   NonRecursive:   The type encoding is not recursive;
10095 ///   Recursive:      The type encoding is recursive;
10096 ///   Incomplete:     An incomplete TypeString;
10097 ///   IncompleteUsed: An incomplete TypeString that has been used in a
10098 ///                   Recursive type encoding.
10099 ///
10100 /// A NonRecursive entry will have all of its sub-members expanded as fully
10101 /// as possible. Whilst it may contain types which are recursive, the type
10102 /// itself is not recursive and thus its encoding may be safely used whenever
10103 /// the type is encountered.
10104 ///
10105 /// A Recursive entry will have all of its sub-members expanded as fully as
10106 /// possible. The type itself is recursive and it may contain other types which
10107 /// are recursive. The Recursive encoding must not be used during the expansion
10108 /// of a recursive type's recursive branch. For simplicity the code uses
10109 /// IncompleteCount to reject all usage of Recursive encodings for member types.
10110 ///
10111 /// An Incomplete entry is always a RecordType and only encodes its
10112 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
10113 /// are placed into the cache during type expansion as a means to identify and
10114 /// handle recursive inclusion of types as sub-members. If there is recursion
10115 /// the entry becomes IncompleteUsed.
10116 ///
10117 /// During the expansion of a RecordType's members:
10118 ///
10119 ///   If the cache contains a NonRecursive encoding for the member type, the
10120 ///   cached encoding is used;
10121 ///
10122 ///   If the cache contains a Recursive encoding for the member type, the
10123 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10124 ///
10125 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10126 ///   cache to break potential recursive inclusion of itself as a sub-member;
10127 ///
10128 ///   Once a member RecordType has been expanded, its temporary incomplete
10129 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10130 ///   it is swapped back in;
10131 ///
10132 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10133 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10134 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10135 ///
10136 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10137 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10138 ///   Else the member is part of a recursive type and thus the recursion has
10139 ///   been exited too soon for the encoding to be correct for the member.
10140 ///
10141 class TypeStringCache {
10142   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10143   struct Entry {
10144     std::string Str;     // The encoded TypeString for the type.
10145     enum Status State;   // Information about the encoding in 'Str'.
10146     std::string Swapped; // A temporary place holder for a Recursive encoding
10147                          // during the expansion of RecordType's members.
10148   };
10149   std::map<const IdentifierInfo *, struct Entry> Map;
10150   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10151   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10152 public:
10153   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10154   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10155   bool removeIncomplete(const IdentifierInfo *ID);
10156   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10157                      bool IsRecursive);
10158   StringRef lookupStr(const IdentifierInfo *ID);
10159 };
10160 
10161 /// TypeString encodings for enum & union fields must be order.
10162 /// FieldEncoding is a helper for this ordering process.
10163 class FieldEncoding {
10164   bool HasName;
10165   std::string Enc;
10166 public:
10167   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10168   StringRef str() { return Enc; }
10169   bool operator<(const FieldEncoding &rhs) const {
10170     if (HasName != rhs.HasName) return HasName;
10171     return Enc < rhs.Enc;
10172   }
10173 };
10174 
10175 class XCoreABIInfo : public DefaultABIInfo {
10176 public:
10177   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10178   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10179                     QualType Ty) const override;
10180 };
10181 
10182 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10183   mutable TypeStringCache TSC;
10184   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10185                     const CodeGen::CodeGenModule &M) const;
10186 
10187 public:
10188   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10189       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10190   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10191                           const llvm::MapVector<GlobalDecl, StringRef>
10192                               &MangledDeclNames) const override;
10193 };
10194 
10195 } // End anonymous namespace.
10196 
10197 // TODO: this implementation is likely now redundant with the default
10198 // EmitVAArg.
10199 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10200                                 QualType Ty) const {
10201   CGBuilderTy &Builder = CGF.Builder;
10202 
10203   // Get the VAList.
10204   CharUnits SlotSize = CharUnits::fromQuantity(4);
10205   Address AP = Address(Builder.CreateLoad(VAListAddr),
10206                        getVAListElementType(CGF), SlotSize);
10207 
10208   // Handle the argument.
10209   ABIArgInfo AI = classifyArgumentType(Ty);
10210   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10211   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10212   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10213     AI.setCoerceToType(ArgTy);
10214   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10215 
10216   Address Val = Address::invalid();
10217   CharUnits ArgSize = CharUnits::Zero();
10218   switch (AI.getKind()) {
10219   case ABIArgInfo::Expand:
10220   case ABIArgInfo::CoerceAndExpand:
10221   case ABIArgInfo::InAlloca:
10222     llvm_unreachable("Unsupported ABI kind for va_arg");
10223   case ABIArgInfo::Ignore:
10224     Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign);
10225     ArgSize = CharUnits::Zero();
10226     break;
10227   case ABIArgInfo::Extend:
10228   case ABIArgInfo::Direct:
10229     Val = Builder.CreateElementBitCast(AP, ArgTy);
10230     ArgSize = CharUnits::fromQuantity(
10231         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10232     ArgSize = ArgSize.alignTo(SlotSize);
10233     break;
10234   case ABIArgInfo::Indirect:
10235   case ABIArgInfo::IndirectAliased:
10236     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10237     Val = Address(Builder.CreateLoad(Val), ArgTy, TypeAlign);
10238     ArgSize = SlotSize;
10239     break;
10240   }
10241 
10242   // Increment the VAList.
10243   if (!ArgSize.isZero()) {
10244     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10245     Builder.CreateStore(APN.getPointer(), VAListAddr);
10246   }
10247 
10248   return Val;
10249 }
10250 
10251 /// During the expansion of a RecordType, an incomplete TypeString is placed
10252 /// into the cache as a means to identify and break recursion.
10253 /// If there is a Recursive encoding in the cache, it is swapped out and will
10254 /// be reinserted by removeIncomplete().
10255 /// All other types of encoding should have been used rather than arriving here.
10256 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10257                                     std::string StubEnc) {
10258   if (!ID)
10259     return;
10260   Entry &E = Map[ID];
10261   assert( (E.Str.empty() || E.State == Recursive) &&
10262          "Incorrectly use of addIncomplete");
10263   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10264   E.Swapped.swap(E.Str); // swap out the Recursive
10265   E.Str.swap(StubEnc);
10266   E.State = Incomplete;
10267   ++IncompleteCount;
10268 }
10269 
10270 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10271 /// must be removed from the cache.
10272 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10273 /// Returns true if the RecordType was defined recursively.
10274 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10275   if (!ID)
10276     return false;
10277   auto I = Map.find(ID);
10278   assert(I != Map.end() && "Entry not present");
10279   Entry &E = I->second;
10280   assert( (E.State == Incomplete ||
10281            E.State == IncompleteUsed) &&
10282          "Entry must be an incomplete type");
10283   bool IsRecursive = false;
10284   if (E.State == IncompleteUsed) {
10285     // We made use of our Incomplete encoding, thus we are recursive.
10286     IsRecursive = true;
10287     --IncompleteUsedCount;
10288   }
10289   if (E.Swapped.empty())
10290     Map.erase(I);
10291   else {
10292     // Swap the Recursive back.
10293     E.Swapped.swap(E.Str);
10294     E.Swapped.clear();
10295     E.State = Recursive;
10296   }
10297   --IncompleteCount;
10298   return IsRecursive;
10299 }
10300 
10301 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10302 /// Recursive (viz: all sub-members were expanded as fully as possible).
10303 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10304                                     bool IsRecursive) {
10305   if (!ID || IncompleteUsedCount)
10306     return; // No key or it is is an incomplete sub-type so don't add.
10307   Entry &E = Map[ID];
10308   if (IsRecursive && !E.Str.empty()) {
10309     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10310            "This is not the same Recursive entry");
10311     // The parent container was not recursive after all, so we could have used
10312     // this Recursive sub-member entry after all, but we assumed the worse when
10313     // we started viz: IncompleteCount!=0.
10314     return;
10315   }
10316   assert(E.Str.empty() && "Entry already present");
10317   E.Str = Str.str();
10318   E.State = IsRecursive? Recursive : NonRecursive;
10319 }
10320 
10321 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10322 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10323 /// encoding is Recursive, return an empty StringRef.
10324 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10325   if (!ID)
10326     return StringRef();   // We have no key.
10327   auto I = Map.find(ID);
10328   if (I == Map.end())
10329     return StringRef();   // We have no encoding.
10330   Entry &E = I->second;
10331   if (E.State == Recursive && IncompleteCount)
10332     return StringRef();   // We don't use Recursive encodings for member types.
10333 
10334   if (E.State == Incomplete) {
10335     // The incomplete type is being used to break out of recursion.
10336     E.State = IncompleteUsed;
10337     ++IncompleteUsedCount;
10338   }
10339   return E.Str;
10340 }
10341 
10342 /// The XCore ABI includes a type information section that communicates symbol
10343 /// type information to the linker. The linker uses this information to verify
10344 /// safety/correctness of things such as array bound and pointers et al.
10345 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10346 /// This type information (TypeString) is emitted into meta data for all global
10347 /// symbols: definitions, declarations, functions & variables.
10348 ///
10349 /// The TypeString carries type, qualifier, name, size & value details.
10350 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10351 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10352 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10353 ///
10354 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10355                           const CodeGen::CodeGenModule &CGM,
10356                           TypeStringCache &TSC);
10357 
10358 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10359 void XCoreTargetCodeGenInfo::emitTargetMD(
10360     const Decl *D, llvm::GlobalValue *GV,
10361     const CodeGen::CodeGenModule &CGM) const {
10362   SmallStringEnc Enc;
10363   if (getTypeString(Enc, D, CGM, TSC)) {
10364     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10365     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10366                                 llvm::MDString::get(Ctx, Enc.str())};
10367     llvm::NamedMDNode *MD =
10368       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10369     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10370   }
10371 }
10372 
10373 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10374     CodeGen::CodeGenModule &CGM,
10375     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10376   // Warning, new MangledDeclNames may be appended within this loop.
10377   // We rely on MapVector insertions adding new elements to the end
10378   // of the container.
10379   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10380     auto Val = *(MangledDeclNames.begin() + I);
10381     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10382     if (GV) {
10383       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10384       emitTargetMD(D, GV, CGM);
10385     }
10386   }
10387 }
10388 
10389 //===----------------------------------------------------------------------===//
10390 // Base ABI and target codegen info implementation common between SPIR and
10391 // SPIR-V.
10392 //===----------------------------------------------------------------------===//
10393 
10394 namespace {
10395 class CommonSPIRABIInfo : public DefaultABIInfo {
10396 public:
10397   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10398 
10399 private:
10400   void setCCs();
10401 };
10402 
10403 class SPIRVABIInfo : public CommonSPIRABIInfo {
10404 public:
10405   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10406   void computeInfo(CGFunctionInfo &FI) const override;
10407 
10408 private:
10409   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10410 };
10411 } // end anonymous namespace
10412 namespace {
10413 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10414 public:
10415   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10416       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10417   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10418       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10419 
10420   LangAS getASTAllocaAddressSpace() const override {
10421     return getLangASFromTargetAS(
10422         getABIInfo().getDataLayout().getAllocaAddrSpace());
10423   }
10424 
10425   unsigned getOpenCLKernelCallingConv() const override;
10426 };
10427 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10428 public:
10429   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10430       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10431   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10432 };
10433 } // End anonymous namespace.
10434 
10435 void CommonSPIRABIInfo::setCCs() {
10436   assert(getRuntimeCC() == llvm::CallingConv::C);
10437   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10438 }
10439 
10440 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10441   if (getContext().getLangOpts().CUDAIsDevice) {
10442     // Coerce pointer arguments with default address space to CrossWorkGroup
10443     // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the
10444     // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space.
10445     llvm::Type *LTy = CGT.ConvertType(Ty);
10446     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10447     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10448     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10449     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10450       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10451       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10452     }
10453 
10454     // Force copying aggregate type in kernel arguments by value when
10455     // compiling CUDA targeting SPIR-V. This is required for the object
10456     // copied to be valid on the device.
10457     // This behavior follows the CUDA spec
10458     // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-function-argument-processing,
10459     // and matches the NVPTX implementation.
10460     if (isAggregateTypeForABI(Ty))
10461       return getNaturalAlignIndirect(Ty, /* byval */ true);
10462   }
10463   return classifyArgumentType(Ty);
10464 }
10465 
10466 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10467   // The logic is same as in DefaultABIInfo with an exception on the kernel
10468   // arguments handling.
10469   llvm::CallingConv::ID CC = FI.getCallingConvention();
10470 
10471   if (!getCXXABI().classifyReturnType(FI))
10472     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10473 
10474   for (auto &I : FI.arguments()) {
10475     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10476       I.info = classifyKernelArgumentType(I.type);
10477     } else {
10478       I.info = classifyArgumentType(I.type);
10479     }
10480   }
10481 }
10482 
10483 namespace clang {
10484 namespace CodeGen {
10485 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10486   if (CGM.getTarget().getTriple().isSPIRV())
10487     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10488   else
10489     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10490 }
10491 }
10492 }
10493 
10494 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10495   return llvm::CallingConv::SPIR_KERNEL;
10496 }
10497 
10498 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10499     const FunctionType *&FT) const {
10500   // Convert HIP kernels to SPIR-V kernels.
10501   if (getABIInfo().getContext().getLangOpts().HIP) {
10502     FT = getABIInfo().getContext().adjustFunctionType(
10503         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10504     return;
10505   }
10506 }
10507 
10508 static bool appendType(SmallStringEnc &Enc, QualType QType,
10509                        const CodeGen::CodeGenModule &CGM,
10510                        TypeStringCache &TSC);
10511 
10512 /// Helper function for appendRecordType().
10513 /// Builds a SmallVector containing the encoded field types in declaration
10514 /// order.
10515 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10516                              const RecordDecl *RD,
10517                              const CodeGen::CodeGenModule &CGM,
10518                              TypeStringCache &TSC) {
10519   for (const auto *Field : RD->fields()) {
10520     SmallStringEnc Enc;
10521     Enc += "m(";
10522     Enc += Field->getName();
10523     Enc += "){";
10524     if (Field->isBitField()) {
10525       Enc += "b(";
10526       llvm::raw_svector_ostream OS(Enc);
10527       OS << Field->getBitWidthValue(CGM.getContext());
10528       Enc += ':';
10529     }
10530     if (!appendType(Enc, Field->getType(), CGM, TSC))
10531       return false;
10532     if (Field->isBitField())
10533       Enc += ')';
10534     Enc += '}';
10535     FE.emplace_back(!Field->getName().empty(), Enc);
10536   }
10537   return true;
10538 }
10539 
10540 /// Appends structure and union types to Enc and adds encoding to cache.
10541 /// Recursively calls appendType (via extractFieldType) for each field.
10542 /// Union types have their fields ordered according to the ABI.
10543 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10544                              const CodeGen::CodeGenModule &CGM,
10545                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10546   // Append the cached TypeString if we have one.
10547   StringRef TypeString = TSC.lookupStr(ID);
10548   if (!TypeString.empty()) {
10549     Enc += TypeString;
10550     return true;
10551   }
10552 
10553   // Start to emit an incomplete TypeString.
10554   size_t Start = Enc.size();
10555   Enc += (RT->isUnionType()? 'u' : 's');
10556   Enc += '(';
10557   if (ID)
10558     Enc += ID->getName();
10559   Enc += "){";
10560 
10561   // We collect all encoded fields and order as necessary.
10562   bool IsRecursive = false;
10563   const RecordDecl *RD = RT->getDecl()->getDefinition();
10564   if (RD && !RD->field_empty()) {
10565     // An incomplete TypeString stub is placed in the cache for this RecordType
10566     // so that recursive calls to this RecordType will use it whilst building a
10567     // complete TypeString for this RecordType.
10568     SmallVector<FieldEncoding, 16> FE;
10569     std::string StubEnc(Enc.substr(Start).str());
10570     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10571     TSC.addIncomplete(ID, std::move(StubEnc));
10572     if (!extractFieldType(FE, RD, CGM, TSC)) {
10573       (void) TSC.removeIncomplete(ID);
10574       return false;
10575     }
10576     IsRecursive = TSC.removeIncomplete(ID);
10577     // The ABI requires unions to be sorted but not structures.
10578     // See FieldEncoding::operator< for sort algorithm.
10579     if (RT->isUnionType())
10580       llvm::sort(FE);
10581     // We can now complete the TypeString.
10582     unsigned E = FE.size();
10583     for (unsigned I = 0; I != E; ++I) {
10584       if (I)
10585         Enc += ',';
10586       Enc += FE[I].str();
10587     }
10588   }
10589   Enc += '}';
10590   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10591   return true;
10592 }
10593 
10594 /// Appends enum types to Enc and adds the encoding to the cache.
10595 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10596                            TypeStringCache &TSC,
10597                            const IdentifierInfo *ID) {
10598   // Append the cached TypeString if we have one.
10599   StringRef TypeString = TSC.lookupStr(ID);
10600   if (!TypeString.empty()) {
10601     Enc += TypeString;
10602     return true;
10603   }
10604 
10605   size_t Start = Enc.size();
10606   Enc += "e(";
10607   if (ID)
10608     Enc += ID->getName();
10609   Enc += "){";
10610 
10611   // We collect all encoded enumerations and order them alphanumerically.
10612   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10613     SmallVector<FieldEncoding, 16> FE;
10614     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10615          ++I) {
10616       SmallStringEnc EnumEnc;
10617       EnumEnc += "m(";
10618       EnumEnc += I->getName();
10619       EnumEnc += "){";
10620       I->getInitVal().toString(EnumEnc);
10621       EnumEnc += '}';
10622       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10623     }
10624     llvm::sort(FE);
10625     unsigned E = FE.size();
10626     for (unsigned I = 0; I != E; ++I) {
10627       if (I)
10628         Enc += ',';
10629       Enc += FE[I].str();
10630     }
10631   }
10632   Enc += '}';
10633   TSC.addIfComplete(ID, Enc.substr(Start), false);
10634   return true;
10635 }
10636 
10637 /// Appends type's qualifier to Enc.
10638 /// This is done prior to appending the type's encoding.
10639 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10640   // Qualifiers are emitted in alphabetical order.
10641   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10642   int Lookup = 0;
10643   if (QT.isConstQualified())
10644     Lookup += 1<<0;
10645   if (QT.isRestrictQualified())
10646     Lookup += 1<<1;
10647   if (QT.isVolatileQualified())
10648     Lookup += 1<<2;
10649   Enc += Table[Lookup];
10650 }
10651 
10652 /// Appends built-in types to Enc.
10653 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10654   const char *EncType;
10655   switch (BT->getKind()) {
10656     case BuiltinType::Void:
10657       EncType = "0";
10658       break;
10659     case BuiltinType::Bool:
10660       EncType = "b";
10661       break;
10662     case BuiltinType::Char_U:
10663       EncType = "uc";
10664       break;
10665     case BuiltinType::UChar:
10666       EncType = "uc";
10667       break;
10668     case BuiltinType::SChar:
10669       EncType = "sc";
10670       break;
10671     case BuiltinType::UShort:
10672       EncType = "us";
10673       break;
10674     case BuiltinType::Short:
10675       EncType = "ss";
10676       break;
10677     case BuiltinType::UInt:
10678       EncType = "ui";
10679       break;
10680     case BuiltinType::Int:
10681       EncType = "si";
10682       break;
10683     case BuiltinType::ULong:
10684       EncType = "ul";
10685       break;
10686     case BuiltinType::Long:
10687       EncType = "sl";
10688       break;
10689     case BuiltinType::ULongLong:
10690       EncType = "ull";
10691       break;
10692     case BuiltinType::LongLong:
10693       EncType = "sll";
10694       break;
10695     case BuiltinType::Float:
10696       EncType = "ft";
10697       break;
10698     case BuiltinType::Double:
10699       EncType = "d";
10700       break;
10701     case BuiltinType::LongDouble:
10702       EncType = "ld";
10703       break;
10704     default:
10705       return false;
10706   }
10707   Enc += EncType;
10708   return true;
10709 }
10710 
10711 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10712 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10713                               const CodeGen::CodeGenModule &CGM,
10714                               TypeStringCache &TSC) {
10715   Enc += "p(";
10716   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10717     return false;
10718   Enc += ')';
10719   return true;
10720 }
10721 
10722 /// Appends array encoding to Enc before calling appendType for the element.
10723 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10724                             const ArrayType *AT,
10725                             const CodeGen::CodeGenModule &CGM,
10726                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10727   if (AT->getSizeModifier() != ArrayType::Normal)
10728     return false;
10729   Enc += "a(";
10730   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10731     CAT->getSize().toStringUnsigned(Enc);
10732   else
10733     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10734   Enc += ':';
10735   // The Qualifiers should be attached to the type rather than the array.
10736   appendQualifier(Enc, QT);
10737   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10738     return false;
10739   Enc += ')';
10740   return true;
10741 }
10742 
10743 /// Appends a function encoding to Enc, calling appendType for the return type
10744 /// and the arguments.
10745 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10746                              const CodeGen::CodeGenModule &CGM,
10747                              TypeStringCache &TSC) {
10748   Enc += "f{";
10749   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10750     return false;
10751   Enc += "}(";
10752   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10753     // N.B. we are only interested in the adjusted param types.
10754     auto I = FPT->param_type_begin();
10755     auto E = FPT->param_type_end();
10756     if (I != E) {
10757       do {
10758         if (!appendType(Enc, *I, CGM, TSC))
10759           return false;
10760         ++I;
10761         if (I != E)
10762           Enc += ',';
10763       } while (I != E);
10764       if (FPT->isVariadic())
10765         Enc += ",va";
10766     } else {
10767       if (FPT->isVariadic())
10768         Enc += "va";
10769       else
10770         Enc += '0';
10771     }
10772   }
10773   Enc += ')';
10774   return true;
10775 }
10776 
10777 /// Handles the type's qualifier before dispatching a call to handle specific
10778 /// type encodings.
10779 static bool appendType(SmallStringEnc &Enc, QualType QType,
10780                        const CodeGen::CodeGenModule &CGM,
10781                        TypeStringCache &TSC) {
10782 
10783   QualType QT = QType.getCanonicalType();
10784 
10785   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10786     // The Qualifiers should be attached to the type rather than the array.
10787     // Thus we don't call appendQualifier() here.
10788     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10789 
10790   appendQualifier(Enc, QT);
10791 
10792   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10793     return appendBuiltinType(Enc, BT);
10794 
10795   if (const PointerType *PT = QT->getAs<PointerType>())
10796     return appendPointerType(Enc, PT, CGM, TSC);
10797 
10798   if (const EnumType *ET = QT->getAs<EnumType>())
10799     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10800 
10801   if (const RecordType *RT = QT->getAsStructureType())
10802     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10803 
10804   if (const RecordType *RT = QT->getAsUnionType())
10805     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10806 
10807   if (const FunctionType *FT = QT->getAs<FunctionType>())
10808     return appendFunctionType(Enc, FT, CGM, TSC);
10809 
10810   return false;
10811 }
10812 
10813 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10814                           const CodeGen::CodeGenModule &CGM,
10815                           TypeStringCache &TSC) {
10816   if (!D)
10817     return false;
10818 
10819   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10820     if (FD->getLanguageLinkage() != CLanguageLinkage)
10821       return false;
10822     return appendType(Enc, FD->getType(), CGM, TSC);
10823   }
10824 
10825   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10826     if (VD->getLanguageLinkage() != CLanguageLinkage)
10827       return false;
10828     QualType QT = VD->getType().getCanonicalType();
10829     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10830       // Global ArrayTypes are given a size of '*' if the size is unknown.
10831       // The Qualifiers should be attached to the type rather than the array.
10832       // Thus we don't call appendQualifier() here.
10833       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10834     }
10835     return appendType(Enc, QT, CGM, TSC);
10836   }
10837   return false;
10838 }
10839 
10840 //===----------------------------------------------------------------------===//
10841 // RISCV ABI Implementation
10842 //===----------------------------------------------------------------------===//
10843 
10844 namespace {
10845 class RISCVABIInfo : public DefaultABIInfo {
10846 private:
10847   // Size of the integer ('x') registers in bits.
10848   unsigned XLen;
10849   // Size of the floating point ('f') registers in bits. Note that the target
10850   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10851   // with soft float ABI has FLen==0).
10852   unsigned FLen;
10853   static const int NumArgGPRs = 8;
10854   static const int NumArgFPRs = 8;
10855   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10856                                       llvm::Type *&Field1Ty,
10857                                       CharUnits &Field1Off,
10858                                       llvm::Type *&Field2Ty,
10859                                       CharUnits &Field2Off) const;
10860 
10861 public:
10862   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10863       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10864 
10865   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10866   // non-virtual, but computeInfo is virtual, so we overload it.
10867   void computeInfo(CGFunctionInfo &FI) const override;
10868 
10869   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10870                                   int &ArgFPRsLeft) const;
10871   ABIArgInfo classifyReturnType(QualType RetTy) const;
10872 
10873   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10874                     QualType Ty) const override;
10875 
10876   ABIArgInfo extendType(QualType Ty) const;
10877 
10878   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10879                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10880                                 CharUnits &Field2Off, int &NeededArgGPRs,
10881                                 int &NeededArgFPRs) const;
10882   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10883                                                CharUnits Field1Off,
10884                                                llvm::Type *Field2Ty,
10885                                                CharUnits Field2Off) const;
10886 };
10887 } // end anonymous namespace
10888 
10889 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10890   QualType RetTy = FI.getReturnType();
10891   if (!getCXXABI().classifyReturnType(FI))
10892     FI.getReturnInfo() = classifyReturnType(RetTy);
10893 
10894   // IsRetIndirect is true if classifyArgumentType indicated the value should
10895   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10896   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10897   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10898   // list and pass indirectly on RV32.
10899   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10900   if (!IsRetIndirect && RetTy->isScalarType() &&
10901       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10902     if (RetTy->isComplexType() && FLen) {
10903       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10904       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10905     } else {
10906       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10907       IsRetIndirect = true;
10908     }
10909   }
10910 
10911   // We must track the number of GPRs used in order to conform to the RISC-V
10912   // ABI, as integer scalars passed in registers should have signext/zeroext
10913   // when promoted, but are anyext if passed on the stack. As GPR usage is
10914   // different for variadic arguments, we must also track whether we are
10915   // examining a vararg or not.
10916   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10917   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10918   int NumFixedArgs = FI.getNumRequiredArgs();
10919 
10920   int ArgNum = 0;
10921   for (auto &ArgInfo : FI.arguments()) {
10922     bool IsFixed = ArgNum < NumFixedArgs;
10923     ArgInfo.info =
10924         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10925     ArgNum++;
10926   }
10927 }
10928 
10929 // Returns true if the struct is a potential candidate for the floating point
10930 // calling convention. If this function returns true, the caller is
10931 // responsible for checking that if there is only a single field then that
10932 // field is a float.
10933 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10934                                                   llvm::Type *&Field1Ty,
10935                                                   CharUnits &Field1Off,
10936                                                   llvm::Type *&Field2Ty,
10937                                                   CharUnits &Field2Off) const {
10938   bool IsInt = Ty->isIntegralOrEnumerationType();
10939   bool IsFloat = Ty->isRealFloatingType();
10940 
10941   if (IsInt || IsFloat) {
10942     uint64_t Size = getContext().getTypeSize(Ty);
10943     if (IsInt && Size > XLen)
10944       return false;
10945     // Can't be eligible if larger than the FP registers. Half precision isn't
10946     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10947     // default to the integer ABI in that case.
10948     if (IsFloat && (Size > FLen || Size < 32))
10949       return false;
10950     // Can't be eligible if an integer type was already found (int+int pairs
10951     // are not eligible).
10952     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10953       return false;
10954     if (!Field1Ty) {
10955       Field1Ty = CGT.ConvertType(Ty);
10956       Field1Off = CurOff;
10957       return true;
10958     }
10959     if (!Field2Ty) {
10960       Field2Ty = CGT.ConvertType(Ty);
10961       Field2Off = CurOff;
10962       return true;
10963     }
10964     return false;
10965   }
10966 
10967   if (auto CTy = Ty->getAs<ComplexType>()) {
10968     if (Field1Ty)
10969       return false;
10970     QualType EltTy = CTy->getElementType();
10971     if (getContext().getTypeSize(EltTy) > FLen)
10972       return false;
10973     Field1Ty = CGT.ConvertType(EltTy);
10974     Field1Off = CurOff;
10975     Field2Ty = Field1Ty;
10976     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10977     return true;
10978   }
10979 
10980   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10981     uint64_t ArraySize = ATy->getSize().getZExtValue();
10982     QualType EltTy = ATy->getElementType();
10983     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10984     for (uint64_t i = 0; i < ArraySize; ++i) {
10985       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10986                                                 Field1Off, Field2Ty, Field2Off);
10987       if (!Ret)
10988         return false;
10989       CurOff += EltSize;
10990     }
10991     return true;
10992   }
10993 
10994   if (const auto *RTy = Ty->getAs<RecordType>()) {
10995     // Structures with either a non-trivial destructor or a non-trivial
10996     // copy constructor are not eligible for the FP calling convention.
10997     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10998       return false;
10999     if (isEmptyRecord(getContext(), Ty, true))
11000       return true;
11001     const RecordDecl *RD = RTy->getDecl();
11002     // Unions aren't eligible unless they're empty (which is caught above).
11003     if (RD->isUnion())
11004       return false;
11005     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
11006     // If this is a C++ record, check the bases first.
11007     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
11008       for (const CXXBaseSpecifier &B : CXXRD->bases()) {
11009         const auto *BDecl =
11010             cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());
11011         CharUnits BaseOff = Layout.getBaseClassOffset(BDecl);
11012         bool Ret = detectFPCCEligibleStructHelper(B.getType(), CurOff + BaseOff,
11013                                                   Field1Ty, Field1Off, Field2Ty,
11014                                                   Field2Off);
11015         if (!Ret)
11016           return false;
11017       }
11018     }
11019     int ZeroWidthBitFieldCount = 0;
11020     for (const FieldDecl *FD : RD->fields()) {
11021       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
11022       QualType QTy = FD->getType();
11023       if (FD->isBitField()) {
11024         unsigned BitWidth = FD->getBitWidthValue(getContext());
11025         // Allow a bitfield with a type greater than XLen as long as the
11026         // bitwidth is XLen or less.
11027         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
11028           QTy = getContext().getIntTypeForBitwidth(XLen, false);
11029         if (BitWidth == 0) {
11030           ZeroWidthBitFieldCount++;
11031           continue;
11032         }
11033       }
11034 
11035       bool Ret = detectFPCCEligibleStructHelper(
11036           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
11037           Field1Ty, Field1Off, Field2Ty, Field2Off);
11038       if (!Ret)
11039         return false;
11040 
11041       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
11042       // or int+fp structs, but are ignored for a struct with an fp field and
11043       // any number of zero-width bitfields.
11044       if (Field2Ty && ZeroWidthBitFieldCount > 0)
11045         return false;
11046     }
11047     return Field1Ty != nullptr;
11048   }
11049 
11050   return false;
11051 }
11052 
11053 // Determine if a struct is eligible for passing according to the floating
11054 // point calling convention (i.e., when flattened it contains a single fp
11055 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
11056 // NeededArgGPRs are incremented appropriately.
11057 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
11058                                             CharUnits &Field1Off,
11059                                             llvm::Type *&Field2Ty,
11060                                             CharUnits &Field2Off,
11061                                             int &NeededArgGPRs,
11062                                             int &NeededArgFPRs) const {
11063   Field1Ty = nullptr;
11064   Field2Ty = nullptr;
11065   NeededArgGPRs = 0;
11066   NeededArgFPRs = 0;
11067   bool IsCandidate = detectFPCCEligibleStructHelper(
11068       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
11069   // Not really a candidate if we have a single int but no float.
11070   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
11071     return false;
11072   if (!IsCandidate)
11073     return false;
11074   if (Field1Ty && Field1Ty->isFloatingPointTy())
11075     NeededArgFPRs++;
11076   else if (Field1Ty)
11077     NeededArgGPRs++;
11078   if (Field2Ty && Field2Ty->isFloatingPointTy())
11079     NeededArgFPRs++;
11080   else if (Field2Ty)
11081     NeededArgGPRs++;
11082   return true;
11083 }
11084 
11085 // Call getCoerceAndExpand for the two-element flattened struct described by
11086 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
11087 // appropriate coerceToType and unpaddedCoerceToType.
11088 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
11089     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
11090     CharUnits Field2Off) const {
11091   SmallVector<llvm::Type *, 3> CoerceElts;
11092   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
11093   if (!Field1Off.isZero())
11094     CoerceElts.push_back(llvm::ArrayType::get(
11095         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
11096 
11097   CoerceElts.push_back(Field1Ty);
11098   UnpaddedCoerceElts.push_back(Field1Ty);
11099 
11100   if (!Field2Ty) {
11101     return ABIArgInfo::getCoerceAndExpand(
11102         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
11103         UnpaddedCoerceElts[0]);
11104   }
11105 
11106   CharUnits Field2Align =
11107       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
11108   CharUnits Field1End = Field1Off +
11109       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
11110   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
11111 
11112   CharUnits Padding = CharUnits::Zero();
11113   if (Field2Off > Field2OffNoPadNoPack)
11114     Padding = Field2Off - Field2OffNoPadNoPack;
11115   else if (Field2Off != Field2Align && Field2Off > Field1End)
11116     Padding = Field2Off - Field1End;
11117 
11118   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
11119 
11120   if (!Padding.isZero())
11121     CoerceElts.push_back(llvm::ArrayType::get(
11122         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
11123 
11124   CoerceElts.push_back(Field2Ty);
11125   UnpaddedCoerceElts.push_back(Field2Ty);
11126 
11127   auto CoerceToType =
11128       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
11129   auto UnpaddedCoerceToType =
11130       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
11131 
11132   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
11133 }
11134 
11135 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
11136                                               int &ArgGPRsLeft,
11137                                               int &ArgFPRsLeft) const {
11138   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
11139   Ty = useFirstFieldIfTransparentUnion(Ty);
11140 
11141   // Structures with either a non-trivial destructor or a non-trivial
11142   // copy constructor are always passed indirectly.
11143   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11144     if (ArgGPRsLeft)
11145       ArgGPRsLeft -= 1;
11146     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11147                                            CGCXXABI::RAA_DirectInMemory);
11148   }
11149 
11150   // Ignore empty structs/unions.
11151   if (isEmptyRecord(getContext(), Ty, true))
11152     return ABIArgInfo::getIgnore();
11153 
11154   uint64_t Size = getContext().getTypeSize(Ty);
11155 
11156   // Pass floating point values via FPRs if possible.
11157   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11158       FLen >= Size && ArgFPRsLeft) {
11159     ArgFPRsLeft--;
11160     return ABIArgInfo::getDirect();
11161   }
11162 
11163   // Complex types for the hard float ABI must be passed direct rather than
11164   // using CoerceAndExpand.
11165   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11166     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11167     if (getContext().getTypeSize(EltTy) <= FLen) {
11168       ArgFPRsLeft -= 2;
11169       return ABIArgInfo::getDirect();
11170     }
11171   }
11172 
11173   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11174     llvm::Type *Field1Ty = nullptr;
11175     llvm::Type *Field2Ty = nullptr;
11176     CharUnits Field1Off = CharUnits::Zero();
11177     CharUnits Field2Off = CharUnits::Zero();
11178     int NeededArgGPRs = 0;
11179     int NeededArgFPRs = 0;
11180     bool IsCandidate =
11181         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11182                                  NeededArgGPRs, NeededArgFPRs);
11183     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11184         NeededArgFPRs <= ArgFPRsLeft) {
11185       ArgGPRsLeft -= NeededArgGPRs;
11186       ArgFPRsLeft -= NeededArgFPRs;
11187       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11188                                                Field2Off);
11189     }
11190   }
11191 
11192   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11193   bool MustUseStack = false;
11194   // Determine the number of GPRs needed to pass the current argument
11195   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11196   // register pairs, so may consume 3 registers.
11197   int NeededArgGPRs = 1;
11198   if (!IsFixed && NeededAlign == 2 * XLen)
11199     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11200   else if (Size > XLen && Size <= 2 * XLen)
11201     NeededArgGPRs = 2;
11202 
11203   if (NeededArgGPRs > ArgGPRsLeft) {
11204     MustUseStack = true;
11205     NeededArgGPRs = ArgGPRsLeft;
11206   }
11207 
11208   ArgGPRsLeft -= NeededArgGPRs;
11209 
11210   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11211     // Treat an enum type as its underlying type.
11212     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11213       Ty = EnumTy->getDecl()->getIntegerType();
11214 
11215     // All integral types are promoted to XLen width, unless passed on the
11216     // stack.
11217     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11218       return extendType(Ty);
11219     }
11220 
11221     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11222       if (EIT->getNumBits() < XLen && !MustUseStack)
11223         return extendType(Ty);
11224       if (EIT->getNumBits() > 128 ||
11225           (!getContext().getTargetInfo().hasInt128Type() &&
11226            EIT->getNumBits() > 64))
11227         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11228     }
11229 
11230     return ABIArgInfo::getDirect();
11231   }
11232 
11233   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11234   // so coerce to integers.
11235   if (Size <= 2 * XLen) {
11236     unsigned Alignment = getContext().getTypeAlign(Ty);
11237 
11238     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11239     // required, and a 2-element XLen array if only XLen alignment is required.
11240     if (Size <= XLen) {
11241       return ABIArgInfo::getDirect(
11242           llvm::IntegerType::get(getVMContext(), XLen));
11243     } else if (Alignment == 2 * XLen) {
11244       return ABIArgInfo::getDirect(
11245           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11246     } else {
11247       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11248           llvm::IntegerType::get(getVMContext(), XLen), 2));
11249     }
11250   }
11251   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11252 }
11253 
11254 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11255   if (RetTy->isVoidType())
11256     return ABIArgInfo::getIgnore();
11257 
11258   int ArgGPRsLeft = 2;
11259   int ArgFPRsLeft = FLen ? 2 : 0;
11260 
11261   // The rules for return and argument types are the same, so defer to
11262   // classifyArgumentType.
11263   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11264                               ArgFPRsLeft);
11265 }
11266 
11267 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11268                                 QualType Ty) const {
11269   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11270 
11271   // Empty records are ignored for parameter passing purposes.
11272   if (isEmptyRecord(getContext(), Ty, true)) {
11273     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
11274                            getVAListElementType(CGF), SlotSize);
11275     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11276     return Addr;
11277   }
11278 
11279   auto TInfo = getContext().getTypeInfoInChars(Ty);
11280 
11281   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11282   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11283 
11284   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11285                           SlotSize, /*AllowHigherAlign=*/true);
11286 }
11287 
11288 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11289   int TySize = getContext().getTypeSize(Ty);
11290   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11291   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11292     return ABIArgInfo::getSignExtend(Ty);
11293   return ABIArgInfo::getExtend(Ty);
11294 }
11295 
11296 namespace {
11297 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11298 public:
11299   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11300                          unsigned FLen)
11301       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11302 
11303   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11304                            CodeGen::CodeGenModule &CGM) const override {
11305     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11306     if (!FD) return;
11307 
11308     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11309     if (!Attr)
11310       return;
11311 
11312     const char *Kind;
11313     switch (Attr->getInterrupt()) {
11314     case RISCVInterruptAttr::user: Kind = "user"; break;
11315     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11316     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11317     }
11318 
11319     auto *Fn = cast<llvm::Function>(GV);
11320 
11321     Fn->addFnAttr("interrupt", Kind);
11322   }
11323 };
11324 } // namespace
11325 
11326 //===----------------------------------------------------------------------===//
11327 // VE ABI Implementation.
11328 //
11329 namespace {
11330 class VEABIInfo : public DefaultABIInfo {
11331 public:
11332   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11333 
11334 private:
11335   ABIArgInfo classifyReturnType(QualType RetTy) const;
11336   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11337   void computeInfo(CGFunctionInfo &FI) const override;
11338 };
11339 } // end anonymous namespace
11340 
11341 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11342   if (Ty->isAnyComplexType())
11343     return ABIArgInfo::getDirect();
11344   uint64_t Size = getContext().getTypeSize(Ty);
11345   if (Size < 64 && Ty->isIntegerType())
11346     return ABIArgInfo::getExtend(Ty);
11347   return DefaultABIInfo::classifyReturnType(Ty);
11348 }
11349 
11350 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11351   if (Ty->isAnyComplexType())
11352     return ABIArgInfo::getDirect();
11353   uint64_t Size = getContext().getTypeSize(Ty);
11354   if (Size < 64 && Ty->isIntegerType())
11355     return ABIArgInfo::getExtend(Ty);
11356   return DefaultABIInfo::classifyArgumentType(Ty);
11357 }
11358 
11359 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11360   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11361   for (auto &Arg : FI.arguments())
11362     Arg.info = classifyArgumentType(Arg.type);
11363 }
11364 
11365 namespace {
11366 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11367 public:
11368   VETargetCodeGenInfo(CodeGenTypes &CGT)
11369       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11370   // VE ABI requires the arguments of variadic and prototype-less functions
11371   // are passed in both registers and memory.
11372   bool isNoProtoCallVariadic(const CallArgList &args,
11373                              const FunctionNoProtoType *fnType) const override {
11374     return true;
11375   }
11376 };
11377 } // end anonymous namespace
11378 
11379 //===----------------------------------------------------------------------===//
11380 // CSKY ABI Implementation
11381 //===----------------------------------------------------------------------===//
11382 namespace {
11383 class CSKYABIInfo : public DefaultABIInfo {
11384   static const int NumArgGPRs = 4;
11385   static const int NumArgFPRs = 4;
11386 
11387   static const unsigned XLen = 32;
11388   unsigned FLen;
11389 
11390 public:
11391   CSKYABIInfo(CodeGen::CodeGenTypes &CGT, unsigned FLen)
11392       : DefaultABIInfo(CGT), FLen(FLen) {}
11393 
11394   void computeInfo(CGFunctionInfo &FI) const override;
11395   ABIArgInfo classifyArgumentType(QualType Ty, int &ArgGPRsLeft,
11396                                   int &ArgFPRsLeft,
11397                                   bool isReturnType = false) const;
11398   ABIArgInfo classifyReturnType(QualType RetTy) const;
11399 
11400   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11401                     QualType Ty) const override;
11402 };
11403 
11404 } // end anonymous namespace
11405 
11406 void CSKYABIInfo::computeInfo(CGFunctionInfo &FI) const {
11407   QualType RetTy = FI.getReturnType();
11408   if (!getCXXABI().classifyReturnType(FI))
11409     FI.getReturnInfo() = classifyReturnType(RetTy);
11410 
11411   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
11412 
11413   // We must track the number of GPRs used in order to conform to the CSKY
11414   // ABI, as integer scalars passed in registers should have signext/zeroext
11415   // when promoted.
11416   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
11417   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
11418 
11419   for (auto &ArgInfo : FI.arguments()) {
11420     ArgInfo.info = classifyArgumentType(ArgInfo.type, ArgGPRsLeft, ArgFPRsLeft);
11421   }
11422 }
11423 
11424 Address CSKYABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11425                                QualType Ty) const {
11426   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11427 
11428   // Empty records are ignored for parameter passing purposes.
11429   if (isEmptyRecord(getContext(), Ty, true)) {
11430     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
11431                            getVAListElementType(CGF), SlotSize);
11432     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11433     return Addr;
11434   }
11435 
11436   auto TInfo = getContext().getTypeInfoInChars(Ty);
11437 
11438   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, false, TInfo, SlotSize,
11439                           /*AllowHigherAlign=*/true);
11440 }
11441 
11442 ABIArgInfo CSKYABIInfo::classifyArgumentType(QualType Ty, int &ArgGPRsLeft,
11443                                              int &ArgFPRsLeft,
11444                                              bool isReturnType) const {
11445   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
11446   Ty = useFirstFieldIfTransparentUnion(Ty);
11447 
11448   // Structures with either a non-trivial destructor or a non-trivial
11449   // copy constructor are always passed indirectly.
11450   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11451     if (ArgGPRsLeft)
11452       ArgGPRsLeft -= 1;
11453     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11454                                            CGCXXABI::RAA_DirectInMemory);
11455   }
11456 
11457   // Ignore empty structs/unions.
11458   if (isEmptyRecord(getContext(), Ty, true))
11459     return ABIArgInfo::getIgnore();
11460 
11461   if (!Ty->getAsUnionType())
11462     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
11463       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
11464 
11465   uint64_t Size = getContext().getTypeSize(Ty);
11466   // Pass floating point values via FPRs if possible.
11467   if (Ty->isFloatingType() && !Ty->isComplexType() && FLen >= Size &&
11468       ArgFPRsLeft) {
11469     ArgFPRsLeft--;
11470     return ABIArgInfo::getDirect();
11471   }
11472 
11473   // Complex types for the hard float ABI must be passed direct rather than
11474   // using CoerceAndExpand.
11475   if (Ty->isComplexType() && FLen && !isReturnType) {
11476     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11477     if (getContext().getTypeSize(EltTy) <= FLen) {
11478       ArgFPRsLeft -= 2;
11479       return ABIArgInfo::getDirect();
11480     }
11481   }
11482 
11483   if (!isAggregateTypeForABI(Ty)) {
11484     // Treat an enum type as its underlying type.
11485     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11486       Ty = EnumTy->getDecl()->getIntegerType();
11487 
11488     // All integral types are promoted to XLen width, unless passed on the
11489     // stack.
11490     if (Size < XLen && Ty->isIntegralOrEnumerationType())
11491       return ABIArgInfo::getExtend(Ty);
11492 
11493     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11494       if (EIT->getNumBits() < XLen)
11495         return ABIArgInfo::getExtend(Ty);
11496     }
11497 
11498     return ABIArgInfo::getDirect();
11499   }
11500 
11501   // For argument type, the first 4*XLen parts of aggregate will be passed
11502   // in registers, and the rest will be passed in stack.
11503   // So we can coerce to integers directly and let backend handle it correctly.
11504   // For return type, aggregate which <= 2*XLen will be returned in registers.
11505   // Otherwise, aggregate will be returned indirectly.
11506   if (!isReturnType || (isReturnType && Size <= 2 * XLen)) {
11507     if (Size <= XLen) {
11508       return ABIArgInfo::getDirect(
11509           llvm::IntegerType::get(getVMContext(), XLen));
11510     } else {
11511       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11512           llvm::IntegerType::get(getVMContext(), XLen), (Size + 31) / XLen));
11513     }
11514   }
11515   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11516 }
11517 
11518 ABIArgInfo CSKYABIInfo::classifyReturnType(QualType RetTy) const {
11519   if (RetTy->isVoidType())
11520     return ABIArgInfo::getIgnore();
11521 
11522   int ArgGPRsLeft = 2;
11523   int ArgFPRsLeft = FLen ? 1 : 0;
11524 
11525   // The rules for return and argument types are the same, so defer to
11526   // classifyArgumentType.
11527   return classifyArgumentType(RetTy, ArgGPRsLeft, ArgFPRsLeft, true);
11528 }
11529 
11530 namespace {
11531 class CSKYTargetCodeGenInfo : public TargetCodeGenInfo {
11532 public:
11533   CSKYTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned FLen)
11534       : TargetCodeGenInfo(std::make_unique<CSKYABIInfo>(CGT, FLen)) {}
11535 };
11536 } // end anonymous namespace
11537 
11538 //===----------------------------------------------------------------------===//
11539 // Driver code
11540 //===----------------------------------------------------------------------===//
11541 
11542 bool CodeGenModule::supportsCOMDAT() const {
11543   return getTriple().supportsCOMDAT();
11544 }
11545 
11546 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11547   if (TheTargetCodeGenInfo)
11548     return *TheTargetCodeGenInfo;
11549 
11550   // Helper to set the unique_ptr while still keeping the return value.
11551   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11552     this->TheTargetCodeGenInfo.reset(P);
11553     return *P;
11554   };
11555 
11556   const llvm::Triple &Triple = getTarget().getTriple();
11557   switch (Triple.getArch()) {
11558   default:
11559     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11560 
11561   case llvm::Triple::le32:
11562     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11563   case llvm::Triple::m68k:
11564     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11565   case llvm::Triple::mips:
11566   case llvm::Triple::mipsel:
11567     if (Triple.getOS() == llvm::Triple::NaCl)
11568       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11569     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11570 
11571   case llvm::Triple::mips64:
11572   case llvm::Triple::mips64el:
11573     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11574 
11575   case llvm::Triple::avr: {
11576     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
11577     // on avrtiny. For passing return value, R18~R25 are used on avr, and
11578     // R22~R25 are used on avrtiny.
11579     unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18;
11580     unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8;
11581     return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR));
11582   }
11583 
11584   case llvm::Triple::aarch64:
11585   case llvm::Triple::aarch64_32:
11586   case llvm::Triple::aarch64_be: {
11587     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11588     if (getTarget().getABI() == "darwinpcs")
11589       Kind = AArch64ABIInfo::DarwinPCS;
11590     else if (Triple.isOSWindows())
11591       return SetCGInfo(
11592           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11593 
11594     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11595   }
11596 
11597   case llvm::Triple::wasm32:
11598   case llvm::Triple::wasm64: {
11599     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11600     if (getTarget().getABI() == "experimental-mv")
11601       Kind = WebAssemblyABIInfo::ExperimentalMV;
11602     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11603   }
11604 
11605   case llvm::Triple::arm:
11606   case llvm::Triple::armeb:
11607   case llvm::Triple::thumb:
11608   case llvm::Triple::thumbeb: {
11609     if (Triple.getOS() == llvm::Triple::Win32) {
11610       return SetCGInfo(
11611           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11612     }
11613 
11614     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11615     StringRef ABIStr = getTarget().getABI();
11616     if (ABIStr == "apcs-gnu")
11617       Kind = ARMABIInfo::APCS;
11618     else if (ABIStr == "aapcs16")
11619       Kind = ARMABIInfo::AAPCS16_VFP;
11620     else if (CodeGenOpts.FloatABI == "hard" ||
11621              (CodeGenOpts.FloatABI != "soft" &&
11622               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11623                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11624                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11625       Kind = ARMABIInfo::AAPCS_VFP;
11626 
11627     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11628   }
11629 
11630   case llvm::Triple::ppc: {
11631     if (Triple.isOSAIX())
11632       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11633 
11634     bool IsSoftFloat =
11635         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11636     bool RetSmallStructInRegABI =
11637         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11638     return SetCGInfo(
11639         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11640   }
11641   case llvm::Triple::ppcle: {
11642     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11643     bool RetSmallStructInRegABI =
11644         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11645     return SetCGInfo(
11646         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11647   }
11648   case llvm::Triple::ppc64:
11649     if (Triple.isOSAIX())
11650       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11651 
11652     if (Triple.isOSBinFormatELF()) {
11653       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11654       if (getTarget().getABI() == "elfv2")
11655         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11656       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11657 
11658       return SetCGInfo(
11659           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11660     }
11661     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11662   case llvm::Triple::ppc64le: {
11663     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11664     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11665     if (getTarget().getABI() == "elfv1")
11666       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11667     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11668 
11669     return SetCGInfo(
11670         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11671   }
11672 
11673   case llvm::Triple::nvptx:
11674   case llvm::Triple::nvptx64:
11675     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11676 
11677   case llvm::Triple::msp430:
11678     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11679 
11680   case llvm::Triple::riscv32:
11681   case llvm::Triple::riscv64: {
11682     StringRef ABIStr = getTarget().getABI();
11683     unsigned XLen = getTarget().getPointerWidth(0);
11684     unsigned ABIFLen = 0;
11685     if (ABIStr.endswith("f"))
11686       ABIFLen = 32;
11687     else if (ABIStr.endswith("d"))
11688       ABIFLen = 64;
11689     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11690   }
11691 
11692   case llvm::Triple::systemz: {
11693     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11694     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11695     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11696   }
11697 
11698   case llvm::Triple::tce:
11699   case llvm::Triple::tcele:
11700     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11701 
11702   case llvm::Triple::x86: {
11703     bool IsDarwinVectorABI = Triple.isOSDarwin();
11704     bool RetSmallStructInRegABI =
11705         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11706     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11707 
11708     if (Triple.getOS() == llvm::Triple::Win32) {
11709       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11710           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11711           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11712     } else {
11713       return SetCGInfo(new X86_32TargetCodeGenInfo(
11714           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11715           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11716           CodeGenOpts.FloatABI == "soft"));
11717     }
11718   }
11719 
11720   case llvm::Triple::x86_64: {
11721     StringRef ABI = getTarget().getABI();
11722     X86AVXABILevel AVXLevel =
11723         (ABI == "avx512"
11724              ? X86AVXABILevel::AVX512
11725              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11726 
11727     switch (Triple.getOS()) {
11728     case llvm::Triple::Win32:
11729       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11730     default:
11731       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11732     }
11733   }
11734   case llvm::Triple::hexagon:
11735     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11736   case llvm::Triple::lanai:
11737     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11738   case llvm::Triple::r600:
11739     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11740   case llvm::Triple::amdgcn:
11741     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11742   case llvm::Triple::sparc:
11743     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11744   case llvm::Triple::sparcv9:
11745     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11746   case llvm::Triple::xcore:
11747     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11748   case llvm::Triple::arc:
11749     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11750   case llvm::Triple::spir:
11751   case llvm::Triple::spir64:
11752     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11753   case llvm::Triple::spirv32:
11754   case llvm::Triple::spirv64:
11755     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11756   case llvm::Triple::ve:
11757     return SetCGInfo(new VETargetCodeGenInfo(Types));
11758   case llvm::Triple::csky: {
11759     bool IsSoftFloat = !getTarget().hasFeature("hard-float-abi");
11760     bool hasFP64 = getTarget().hasFeature("fpuv2_df") ||
11761                    getTarget().hasFeature("fpuv3_df");
11762     return SetCGInfo(new CSKYTargetCodeGenInfo(Types, IsSoftFloat ? 0
11763                                                       : hasFP64   ? 64
11764                                                                   : 32));
11765   }
11766   }
11767 }
11768 
11769 /// Create an OpenCL kernel for an enqueued block.
11770 ///
11771 /// The kernel has the same function type as the block invoke function. Its
11772 /// name is the name of the block invoke function postfixed with "_kernel".
11773 /// It simply calls the block invoke function then returns.
11774 llvm::Function *
11775 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11776                                              llvm::Function *Invoke,
11777                                              llvm::Type *BlockTy) const {
11778   auto *InvokeFT = Invoke->getFunctionType();
11779   auto &C = CGF.getLLVMContext();
11780   std::string Name = Invoke->getName().str() + "_kernel";
11781   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C),
11782                                      InvokeFT->params(), false);
11783   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11784                                    &CGF.CGM.getModule());
11785   auto IP = CGF.Builder.saveIP();
11786   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11787   auto &Builder = CGF.Builder;
11788   Builder.SetInsertPoint(BB);
11789   llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args()));
11790   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11791   call->setCallingConv(Invoke->getCallingConv());
11792   Builder.CreateRetVoid();
11793   Builder.restoreIP(IP);
11794   return F;
11795 }
11796 
11797 /// Create an OpenCL kernel for an enqueued block.
11798 ///
11799 /// The type of the first argument (the block literal) is the struct type
11800 /// of the block literal instead of a pointer type. The first argument
11801 /// (block literal) is passed directly by value to the kernel. The kernel
11802 /// allocates the same type of struct on stack and stores the block literal
11803 /// to it and passes its pointer to the block invoke function. The kernel
11804 /// has "enqueued-block" function attribute and kernel argument metadata.
11805 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11806     CodeGenFunction &CGF, llvm::Function *Invoke,
11807     llvm::Type *BlockTy) const {
11808   auto &Builder = CGF.Builder;
11809   auto &C = CGF.getLLVMContext();
11810 
11811   auto *InvokeFT = Invoke->getFunctionType();
11812   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11813   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11814   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11815   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11816   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11817   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11818   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11819 
11820   ArgTys.push_back(BlockTy);
11821   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11822   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11823   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11824   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11825   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11826   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11827   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11828     ArgTys.push_back(InvokeFT->getParamType(I));
11829     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11830     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11831     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11832     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11833     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11834     ArgNames.push_back(
11835         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11836   }
11837   std::string Name = Invoke->getName().str() + "_kernel";
11838   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11839   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11840                                    &CGF.CGM.getModule());
11841   F->addFnAttr("enqueued-block");
11842   auto IP = CGF.Builder.saveIP();
11843   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11844   Builder.SetInsertPoint(BB);
11845   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11846   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11847   BlockPtr->setAlignment(BlockAlign);
11848   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11849   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11850   llvm::SmallVector<llvm::Value *, 2> Args;
11851   Args.push_back(Cast);
11852   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11853     Args.push_back(I);
11854   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11855   call->setCallingConv(Invoke->getCallingConv());
11856   Builder.CreateRetVoid();
11857   Builder.restoreIP(IP);
11858 
11859   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11860   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11861   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11862   F->setMetadata("kernel_arg_base_type",
11863                  llvm::MDNode::get(C, ArgBaseTypeNames));
11864   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11865   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11866     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11867 
11868   return F;
11869 }
11870