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> // std::sort
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 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
244   raw_ostream &OS = llvm::errs();
245   OS << "(ABIArgInfo Kind=";
246   switch (TheKind) {
247   case Direct:
248     OS << "Direct Type=";
249     if (llvm::Type *Ty = getCoerceToType())
250       Ty->print(OS);
251     else
252       OS << "null";
253     break;
254   case Extend:
255     OS << "Extend";
256     break;
257   case Ignore:
258     OS << "Ignore";
259     break;
260   case InAlloca:
261     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
262     break;
263   case Indirect:
264     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
265        << " ByVal=" << getIndirectByVal()
266        << " Realign=" << getIndirectRealign();
267     break;
268   case IndirectAliased:
269     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
270        << " AadrSpace=" << getIndirectAddrSpace()
271        << " Realign=" << getIndirectRealign();
272     break;
273   case Expand:
274     OS << "Expand";
275     break;
276   case CoerceAndExpand:
277     OS << "CoerceAndExpand Type=";
278     getCoerceAndExpandType()->print(OS);
279     break;
280   }
281   OS << ")\n";
282 }
283 
284 // Dynamically round a pointer up to a multiple of the given alignment.
285 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
286                                                   llvm::Value *Ptr,
287                                                   CharUnits Align) {
288   llvm::Value *PtrAsInt = Ptr;
289   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
290   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
291   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
292         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
293   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
294            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
295   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
296                                         Ptr->getType(),
297                                         Ptr->getName() + ".aligned");
298   return PtrAsInt;
299 }
300 
301 /// Emit va_arg for a platform using the common void* representation,
302 /// where arguments are simply emitted in an array of slots on the stack.
303 ///
304 /// This version implements the core direct-value passing rules.
305 ///
306 /// \param SlotSize - The size and alignment of a stack slot.
307 ///   Each argument will be allocated to a multiple of this number of
308 ///   slots, and all the slots will be aligned to this value.
309 /// \param AllowHigherAlign - The slot alignment is not a cap;
310 ///   an argument type with an alignment greater than the slot size
311 ///   will be emitted on a higher-alignment address, potentially
312 ///   leaving one or more empty slots behind as padding.  If this
313 ///   is false, the returned address might be less-aligned than
314 ///   DirectAlign.
315 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
316                                       Address VAListAddr,
317                                       llvm::Type *DirectTy,
318                                       CharUnits DirectSize,
319                                       CharUnits DirectAlign,
320                                       CharUnits SlotSize,
321                                       bool AllowHigherAlign) {
322   // Cast the element type to i8* if necessary.  Some platforms define
323   // va_list as a struct containing an i8* instead of just an i8*.
324   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
325     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
326 
327   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
328 
329   // If the CC aligns values higher than the slot size, do so if needed.
330   Address Addr = Address::invalid();
331   if (AllowHigherAlign && DirectAlign > SlotSize) {
332     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
333                    CGF.Int8Ty, DirectAlign);
334   } else {
335     Addr = Address(Ptr, CGF.Int8Ty, SlotSize);
336   }
337 
338   // Advance the pointer past the argument, then store that back.
339   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
340   Address NextPtr =
341       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
342   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
343 
344   // If the argument is smaller than a slot, and this is a big-endian
345   // target, the argument will be right-adjusted in its slot.
346   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
347       !DirectTy->isStructTy()) {
348     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
349   }
350 
351   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
352   return Addr;
353 }
354 
355 /// Emit va_arg for a platform using the common void* representation,
356 /// where arguments are simply emitted in an array of slots on the stack.
357 ///
358 /// \param IsIndirect - Values of this type are passed indirectly.
359 /// \param ValueInfo - The size and alignment of this type, generally
360 ///   computed with getContext().getTypeInfoInChars(ValueTy).
361 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
362 ///   Each argument will be allocated to a multiple of this number of
363 ///   slots, and all the slots will be aligned to this value.
364 /// \param AllowHigherAlign - The slot alignment is not a cap;
365 ///   an argument type with an alignment greater than the slot size
366 ///   will be emitted on a higher-alignment address, potentially
367 ///   leaving one or more empty slots behind as padding.
368 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
369                                 QualType ValueTy, bool IsIndirect,
370                                 TypeInfoChars ValueInfo,
371                                 CharUnits SlotSizeAndAlign,
372                                 bool AllowHigherAlign) {
373   // The size and alignment of the value that was passed directly.
374   CharUnits DirectSize, DirectAlign;
375   if (IsIndirect) {
376     DirectSize = CGF.getPointerSize();
377     DirectAlign = CGF.getPointerAlign();
378   } else {
379     DirectSize = ValueInfo.Width;
380     DirectAlign = ValueInfo.Align;
381   }
382 
383   // Cast the address we've calculated to the right type.
384   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
385   if (IsIndirect)
386     DirectTy = DirectTy->getPointerTo(0);
387 
388   Address Addr =
389       emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
390                              SlotSizeAndAlign, AllowHigherAlign);
391 
392   if (IsIndirect) {
393     Addr = Address(CGF.Builder.CreateLoad(Addr), ElementTy, ValueInfo.Align);
394   }
395 
396   return Addr;
397 }
398 
399 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
400                                     QualType Ty, CharUnits SlotSize,
401                                     CharUnits EltSize, const ComplexType *CTy) {
402   Address Addr =
403       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
404                              SlotSize, SlotSize, /*AllowHigher*/ true);
405 
406   Address RealAddr = Addr;
407   Address ImagAddr = RealAddr;
408   if (CGF.CGM.getDataLayout().isBigEndian()) {
409     RealAddr =
410         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
411     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
412                                                       2 * SlotSize - EltSize);
413   } else {
414     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
415   }
416 
417   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
418   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
419   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
420   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
421   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
422 
423   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
424   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
425                          /*init*/ true);
426   return Temp;
427 }
428 
429 static Address emitMergePHI(CodeGenFunction &CGF,
430                             Address Addr1, llvm::BasicBlock *Block1,
431                             Address Addr2, llvm::BasicBlock *Block2,
432                             const llvm::Twine &Name = "") {
433   assert(Addr1.getType() == Addr2.getType());
434   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
435   PHI->addIncoming(Addr1.getPointer(), Block1);
436   PHI->addIncoming(Addr2.getPointer(), Block2);
437   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
438   return Address(PHI, Addr1.getElementType(), Align);
439 }
440 
441 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
442 
443 // If someone can figure out a general rule for this, that would be great.
444 // It's probably just doomed to be platform-dependent, though.
445 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
446   // Verified for:
447   //   x86-64     FreeBSD, Linux, Darwin
448   //   x86-32     FreeBSD, Linux, Darwin
449   //   PowerPC    Linux, Darwin
450   //   ARM        Darwin (*not* EABI)
451   //   AArch64    Linux
452   return 32;
453 }
454 
455 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
456                                      const FunctionNoProtoType *fnType) const {
457   // The following conventions are known to require this to be false:
458   //   x86_stdcall
459   //   MIPS
460   // For everything else, we just prefer false unless we opt out.
461   return false;
462 }
463 
464 void
465 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
466                                              llvm::SmallString<24> &Opt) const {
467   // This assumes the user is passing a library name like "rt" instead of a
468   // filename like "librt.a/so", and that they don't care whether it's static or
469   // dynamic.
470   Opt = "-l";
471   Opt += Lib;
472 }
473 
474 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
475   // OpenCL kernels are called via an explicit runtime API with arguments
476   // set with clSetKernelArg(), not as normal sub-functions.
477   // Return SPIR_KERNEL by default as the kernel calling convention to
478   // ensure the fingerprint is fixed such way that each OpenCL argument
479   // gets one matching argument in the produced kernel function argument
480   // list to enable feasible implementation of clSetKernelArg() with
481   // aggregates etc. In case we would use the default C calling conv here,
482   // clSetKernelArg() might break depending on the target-specific
483   // conventions; different targets might split structs passed as values
484   // to multiple function arguments etc.
485   return llvm::CallingConv::SPIR_KERNEL;
486 }
487 
488 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
489     llvm::PointerType *T, QualType QT) const {
490   return llvm::ConstantPointerNull::get(T);
491 }
492 
493 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
494                                                    const VarDecl *D) const {
495   assert(!CGM.getLangOpts().OpenCL &&
496          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
497          "Address space agnostic languages only");
498   return D ? D->getType().getAddressSpace() : LangAS::Default;
499 }
500 
501 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
502     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
503     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
504   // Since target may map different address spaces in AST to the same address
505   // space, an address space conversion may end up as a bitcast.
506   if (auto *C = dyn_cast<llvm::Constant>(Src))
507     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
508   // Try to preserve the source's name to make IR more readable.
509   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
510       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
511 }
512 
513 llvm::Constant *
514 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
515                                         LangAS SrcAddr, LangAS DestAddr,
516                                         llvm::Type *DestTy) const {
517   // Since target may map different address spaces in AST to the same address
518   // space, an address space conversion may end up as a bitcast.
519   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
520 }
521 
522 llvm::SyncScope::ID
523 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
524                                       SyncScope Scope,
525                                       llvm::AtomicOrdering Ordering,
526                                       llvm::LLVMContext &Ctx) const {
527   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
528 }
529 
530 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
531 
532 /// isEmptyField - Return true iff a the field is "empty", that is it
533 /// is an unnamed bit-field or an (array of) empty record(s).
534 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
535                          bool AllowArrays) {
536   if (FD->isUnnamedBitfield())
537     return true;
538 
539   QualType FT = FD->getType();
540 
541   // Constant arrays of empty records count as empty, strip them off.
542   // Constant arrays of zero length always count as empty.
543   bool WasArray = false;
544   if (AllowArrays)
545     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
546       if (AT->getSize() == 0)
547         return true;
548       FT = AT->getElementType();
549       // The [[no_unique_address]] special case below does not apply to
550       // arrays of C++ empty records, so we need to remember this fact.
551       WasArray = true;
552     }
553 
554   const RecordType *RT = FT->getAs<RecordType>();
555   if (!RT)
556     return false;
557 
558   // C++ record fields are never empty, at least in the Itanium ABI.
559   //
560   // FIXME: We should use a predicate for whether this behavior is true in the
561   // current ABI.
562   //
563   // The exception to the above rule are fields marked with the
564   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
565   // according to the Itanium ABI.  The exception applies only to records,
566   // not arrays of records, so we must also check whether we stripped off an
567   // array type above.
568   if (isa<CXXRecordDecl>(RT->getDecl()) &&
569       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
570     return false;
571 
572   return isEmptyRecord(Context, FT, AllowArrays);
573 }
574 
575 /// isEmptyRecord - Return true iff a structure contains only empty
576 /// fields. Note that a structure with a flexible array member is not
577 /// considered empty.
578 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
579   const RecordType *RT = T->getAs<RecordType>();
580   if (!RT)
581     return false;
582   const RecordDecl *RD = RT->getDecl();
583   if (RD->hasFlexibleArrayMember())
584     return false;
585 
586   // If this is a C++ record, check the bases first.
587   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
588     for (const auto &I : CXXRD->bases())
589       if (!isEmptyRecord(Context, I.getType(), true))
590         return false;
591 
592   for (const auto *I : RD->fields())
593     if (!isEmptyField(Context, I, AllowArrays))
594       return false;
595   return true;
596 }
597 
598 /// isSingleElementStruct - Determine if a structure is a "single
599 /// element struct", i.e. it has exactly one non-empty field or
600 /// exactly one field which is itself a single element
601 /// struct. Structures with flexible array members are never
602 /// considered single element structs.
603 ///
604 /// \return The field declaration for the single non-empty field, if
605 /// it exists.
606 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
607   const RecordType *RT = T->getAs<RecordType>();
608   if (!RT)
609     return nullptr;
610 
611   const RecordDecl *RD = RT->getDecl();
612   if (RD->hasFlexibleArrayMember())
613     return nullptr;
614 
615   const Type *Found = nullptr;
616 
617   // If this is a C++ record, check the bases first.
618   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
619     for (const auto &I : CXXRD->bases()) {
620       // Ignore empty records.
621       if (isEmptyRecord(Context, I.getType(), true))
622         continue;
623 
624       // If we already found an element then this isn't a single-element struct.
625       if (Found)
626         return nullptr;
627 
628       // If this is non-empty and not a single element struct, the composite
629       // cannot be a single element struct.
630       Found = isSingleElementStruct(I.getType(), Context);
631       if (!Found)
632         return nullptr;
633     }
634   }
635 
636   // Check for single element.
637   for (const auto *FD : RD->fields()) {
638     QualType FT = FD->getType();
639 
640     // Ignore empty fields.
641     if (isEmptyField(Context, FD, true))
642       continue;
643 
644     // If we already found an element then this isn't a single-element
645     // struct.
646     if (Found)
647       return nullptr;
648 
649     // Treat single element arrays as the element.
650     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
651       if (AT->getSize().getZExtValue() != 1)
652         break;
653       FT = AT->getElementType();
654     }
655 
656     if (!isAggregateTypeForABI(FT)) {
657       Found = FT.getTypePtr();
658     } else {
659       Found = isSingleElementStruct(FT, Context);
660       if (!Found)
661         return nullptr;
662     }
663   }
664 
665   // We don't consider a struct a single-element struct if it has
666   // padding beyond the element type.
667   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
668     return nullptr;
669 
670   return Found;
671 }
672 
673 namespace {
674 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
675                        const ABIArgInfo &AI) {
676   // This default implementation defers to the llvm backend's va_arg
677   // instruction. It can handle only passing arguments directly
678   // (typically only handled in the backend for primitive types), or
679   // aggregates passed indirectly by pointer (NOTE: if the "byval"
680   // flag has ABI impact in the callee, this implementation cannot
681   // work.)
682 
683   // Only a few cases are covered here at the moment -- those needed
684   // by the default abi.
685   llvm::Value *Val;
686 
687   if (AI.isIndirect()) {
688     assert(!AI.getPaddingType() &&
689            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
690     assert(
691         !AI.getIndirectRealign() &&
692         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
693 
694     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
695     CharUnits TyAlignForABI = TyInfo.Align;
696 
697     llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty);
698     llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy);
699     llvm::Value *Addr =
700         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
701     return Address(Addr, ElementTy, TyAlignForABI);
702   } else {
703     assert((AI.isDirect() || AI.isExtend()) &&
704            "Unexpected ArgInfo Kind in generic VAArg emitter!");
705 
706     assert(!AI.getInReg() &&
707            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
708     assert(!AI.getPaddingType() &&
709            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
710     assert(!AI.getDirectOffset() &&
711            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
712     assert(!AI.getCoerceToType() &&
713            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
714 
715     Address Temp = CGF.CreateMemTemp(Ty, "varet");
716     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
717                                   CGF.ConvertTypeForMem(Ty));
718     CGF.Builder.CreateStore(Val, Temp);
719     return Temp;
720   }
721 }
722 
723 /// DefaultABIInfo - The default implementation for ABI specific
724 /// details. This implementation provides information which results in
725 /// self-consistent and sensible LLVM IR generation, but does not
726 /// conform to any particular ABI.
727 class DefaultABIInfo : public ABIInfo {
728 public:
729   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
730 
731   ABIArgInfo classifyReturnType(QualType RetTy) const;
732   ABIArgInfo classifyArgumentType(QualType RetTy) const;
733 
734   void computeInfo(CGFunctionInfo &FI) const override {
735     if (!getCXXABI().classifyReturnType(FI))
736       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
737     for (auto &I : FI.arguments())
738       I.info = classifyArgumentType(I.type);
739   }
740 
741   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
742                     QualType Ty) const override {
743     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
744   }
745 };
746 
747 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
748 public:
749   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
750       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
751 };
752 
753 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
754   Ty = useFirstFieldIfTransparentUnion(Ty);
755 
756   if (isAggregateTypeForABI(Ty)) {
757     // Records with non-trivial destructors/copy-constructors should not be
758     // passed by value.
759     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
760       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
761 
762     return getNaturalAlignIndirect(Ty);
763   }
764 
765   // Treat an enum type as its underlying type.
766   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
767     Ty = EnumTy->getDecl()->getIntegerType();
768 
769   ASTContext &Context = getContext();
770   if (const auto *EIT = Ty->getAs<BitIntType>())
771     if (EIT->getNumBits() >
772         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
773                                 ? Context.Int128Ty
774                                 : Context.LongLongTy))
775       return getNaturalAlignIndirect(Ty);
776 
777   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
778                                             : ABIArgInfo::getDirect());
779 }
780 
781 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
782   if (RetTy->isVoidType())
783     return ABIArgInfo::getIgnore();
784 
785   if (isAggregateTypeForABI(RetTy))
786     return getNaturalAlignIndirect(RetTy);
787 
788   // Treat an enum type as its underlying type.
789   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
790     RetTy = EnumTy->getDecl()->getIntegerType();
791 
792   if (const auto *EIT = RetTy->getAs<BitIntType>())
793     if (EIT->getNumBits() >
794         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
795                                      ? getContext().Int128Ty
796                                      : getContext().LongLongTy))
797       return getNaturalAlignIndirect(RetTy);
798 
799   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
800                                                : ABIArgInfo::getDirect());
801 }
802 
803 //===----------------------------------------------------------------------===//
804 // WebAssembly ABI Implementation
805 //
806 // This is a very simple ABI that relies a lot on DefaultABIInfo.
807 //===----------------------------------------------------------------------===//
808 
809 class WebAssemblyABIInfo final : public SwiftABIInfo {
810 public:
811   enum ABIKind {
812     MVP = 0,
813     ExperimentalMV = 1,
814   };
815 
816 private:
817   DefaultABIInfo defaultInfo;
818   ABIKind Kind;
819 
820 public:
821   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
822       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
823 
824 private:
825   ABIArgInfo classifyReturnType(QualType RetTy) const;
826   ABIArgInfo classifyArgumentType(QualType Ty) const;
827 
828   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
829   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
830   // overload them.
831   void computeInfo(CGFunctionInfo &FI) const override {
832     if (!getCXXABI().classifyReturnType(FI))
833       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
834     for (auto &Arg : FI.arguments())
835       Arg.info = classifyArgumentType(Arg.type);
836   }
837 
838   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
839                     QualType Ty) const override;
840 
841   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
842                                     bool asReturnValue) const override {
843     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
844   }
845 
846   bool isSwiftErrorInRegister() const override {
847     return false;
848   }
849 };
850 
851 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
852 public:
853   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
854                                         WebAssemblyABIInfo::ABIKind K)
855       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
856 
857   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
858                            CodeGen::CodeGenModule &CGM) const override {
859     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
860     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
861       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
862         llvm::Function *Fn = cast<llvm::Function>(GV);
863         llvm::AttrBuilder B(GV->getContext());
864         B.addAttribute("wasm-import-module", Attr->getImportModule());
865         Fn->addFnAttrs(B);
866       }
867       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
868         llvm::Function *Fn = cast<llvm::Function>(GV);
869         llvm::AttrBuilder B(GV->getContext());
870         B.addAttribute("wasm-import-name", Attr->getImportName());
871         Fn->addFnAttrs(B);
872       }
873       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
874         llvm::Function *Fn = cast<llvm::Function>(GV);
875         llvm::AttrBuilder B(GV->getContext());
876         B.addAttribute("wasm-export-name", Attr->getExportName());
877         Fn->addFnAttrs(B);
878       }
879     }
880 
881     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
882       llvm::Function *Fn = cast<llvm::Function>(GV);
883       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
884         Fn->addFnAttr("no-prototype");
885     }
886   }
887 };
888 
889 /// Classify argument of given type \p Ty.
890 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
891   Ty = useFirstFieldIfTransparentUnion(Ty);
892 
893   if (isAggregateTypeForABI(Ty)) {
894     // Records with non-trivial destructors/copy-constructors should not be
895     // passed by value.
896     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
897       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
898     // Ignore empty structs/unions.
899     if (isEmptyRecord(getContext(), Ty, true))
900       return ABIArgInfo::getIgnore();
901     // Lower single-element structs to just pass a regular value. TODO: We
902     // could do reasonable-size multiple-element structs too, using getExpand(),
903     // though watch out for things like bitfields.
904     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
905       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
906     // For the experimental multivalue ABI, fully expand all other aggregates
907     if (Kind == ABIKind::ExperimentalMV) {
908       const RecordType *RT = Ty->getAs<RecordType>();
909       assert(RT);
910       bool HasBitField = false;
911       for (auto *Field : RT->getDecl()->fields()) {
912         if (Field->isBitField()) {
913           HasBitField = true;
914           break;
915         }
916       }
917       if (!HasBitField)
918         return ABIArgInfo::getExpand();
919     }
920   }
921 
922   // Otherwise just do the default thing.
923   return defaultInfo.classifyArgumentType(Ty);
924 }
925 
926 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
927   if (isAggregateTypeForABI(RetTy)) {
928     // Records with non-trivial destructors/copy-constructors should not be
929     // returned by value.
930     if (!getRecordArgABI(RetTy, getCXXABI())) {
931       // Ignore empty structs/unions.
932       if (isEmptyRecord(getContext(), RetTy, true))
933         return ABIArgInfo::getIgnore();
934       // Lower single-element structs to just return a regular value. TODO: We
935       // could do reasonable-size multiple-element structs too, using
936       // ABIArgInfo::getDirect().
937       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
938         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
939       // For the experimental multivalue ABI, return all other aggregates
940       if (Kind == ABIKind::ExperimentalMV)
941         return ABIArgInfo::getDirect();
942     }
943   }
944 
945   // Otherwise just do the default thing.
946   return defaultInfo.classifyReturnType(RetTy);
947 }
948 
949 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
950                                       QualType Ty) const {
951   bool IsIndirect = isAggregateTypeForABI(Ty) &&
952                     !isEmptyRecord(getContext(), Ty, true) &&
953                     !isSingleElementStruct(Ty, getContext());
954   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
955                           getContext().getTypeInfoInChars(Ty),
956                           CharUnits::fromQuantity(4),
957                           /*AllowHigherAlign=*/true);
958 }
959 
960 //===----------------------------------------------------------------------===//
961 // le32/PNaCl bitcode ABI Implementation
962 //
963 // This is a simplified version of the x86_32 ABI.  Arguments and return values
964 // are always passed on the stack.
965 //===----------------------------------------------------------------------===//
966 
967 class PNaClABIInfo : public ABIInfo {
968  public:
969   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
970 
971   ABIArgInfo classifyReturnType(QualType RetTy) const;
972   ABIArgInfo classifyArgumentType(QualType RetTy) const;
973 
974   void computeInfo(CGFunctionInfo &FI) const override;
975   Address EmitVAArg(CodeGenFunction &CGF,
976                     Address VAListAddr, QualType Ty) const override;
977 };
978 
979 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
980  public:
981    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
982        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
983 };
984 
985 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
986   if (!getCXXABI().classifyReturnType(FI))
987     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
988 
989   for (auto &I : FI.arguments())
990     I.info = classifyArgumentType(I.type);
991 }
992 
993 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
994                                 QualType Ty) const {
995   // The PNaCL ABI is a bit odd, in that varargs don't use normal
996   // function classification. Structs get passed directly for varargs
997   // functions, through a rewriting transform in
998   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
999   // this target to actually support a va_arg instructions with an
1000   // aggregate type, unlike other targets.
1001   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
1002 }
1003 
1004 /// Classify argument of given type \p Ty.
1005 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1006   if (isAggregateTypeForABI(Ty)) {
1007     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1008       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1009     return getNaturalAlignIndirect(Ty);
1010   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1011     // Treat an enum type as its underlying type.
1012     Ty = EnumTy->getDecl()->getIntegerType();
1013   } else if (Ty->isFloatingType()) {
1014     // Floating-point types don't go inreg.
1015     return ABIArgInfo::getDirect();
1016   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1017     // Treat bit-precise integers as integers if <= 64, otherwise pass
1018     // indirectly.
1019     if (EIT->getNumBits() > 64)
1020       return getNaturalAlignIndirect(Ty);
1021     return ABIArgInfo::getDirect();
1022   }
1023 
1024   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1025                                             : ABIArgInfo::getDirect());
1026 }
1027 
1028 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1029   if (RetTy->isVoidType())
1030     return ABIArgInfo::getIgnore();
1031 
1032   // In the PNaCl ABI we always return records/structures on the stack.
1033   if (isAggregateTypeForABI(RetTy))
1034     return getNaturalAlignIndirect(RetTy);
1035 
1036   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1037   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1038     if (EIT->getNumBits() > 64)
1039       return getNaturalAlignIndirect(RetTy);
1040     return ABIArgInfo::getDirect();
1041   }
1042 
1043   // Treat an enum type as its underlying type.
1044   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1045     RetTy = EnumTy->getDecl()->getIntegerType();
1046 
1047   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1048                                                : ABIArgInfo::getDirect());
1049 }
1050 
1051 /// IsX86_MMXType - Return true if this is an MMX type.
1052 bool IsX86_MMXType(llvm::Type *IRType) {
1053   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1054   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1055     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1056     IRType->getScalarSizeInBits() != 64;
1057 }
1058 
1059 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1060                                           StringRef Constraint,
1061                                           llvm::Type* Ty) {
1062   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1063                      .Cases("y", "&y", "^Ym", true)
1064                      .Default(false);
1065   if (IsMMXCons && Ty->isVectorTy()) {
1066     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1067         64) {
1068       // Invalid MMX constraint
1069       return nullptr;
1070     }
1071 
1072     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1073   }
1074 
1075   // No operation needed
1076   return Ty;
1077 }
1078 
1079 /// Returns true if this type can be passed in SSE registers with the
1080 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1081 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1082   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1083     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1084       if (BT->getKind() == BuiltinType::LongDouble) {
1085         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1086             &llvm::APFloat::x87DoubleExtended())
1087           return false;
1088       }
1089       return true;
1090     }
1091   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1092     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1093     // registers specially.
1094     unsigned VecSize = Context.getTypeSize(VT);
1095     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1096       return true;
1097   }
1098   return false;
1099 }
1100 
1101 /// Returns true if this aggregate is small enough to be passed in SSE registers
1102 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1103 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1104   return NumMembers <= 4;
1105 }
1106 
1107 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1108 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1109   auto AI = ABIArgInfo::getDirect(T);
1110   AI.setInReg(true);
1111   AI.setCanBeFlattened(false);
1112   return AI;
1113 }
1114 
1115 //===----------------------------------------------------------------------===//
1116 // X86-32 ABI Implementation
1117 //===----------------------------------------------------------------------===//
1118 
1119 /// Similar to llvm::CCState, but for Clang.
1120 struct CCState {
1121   CCState(CGFunctionInfo &FI)
1122       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1123 
1124   llvm::SmallBitVector IsPreassigned;
1125   unsigned CC = CallingConv::CC_C;
1126   unsigned FreeRegs = 0;
1127   unsigned FreeSSERegs = 0;
1128 };
1129 
1130 /// X86_32ABIInfo - The X86-32 ABI information.
1131 class X86_32ABIInfo : public SwiftABIInfo {
1132   enum Class {
1133     Integer,
1134     Float
1135   };
1136 
1137   static const unsigned MinABIStackAlignInBytes = 4;
1138 
1139   bool IsDarwinVectorABI;
1140   bool IsRetSmallStructInRegABI;
1141   bool IsWin32StructABI;
1142   bool IsSoftFloatABI;
1143   bool IsMCUABI;
1144   bool IsLinuxABI;
1145   unsigned DefaultNumRegisterParameters;
1146 
1147   static bool isRegisterSize(unsigned Size) {
1148     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1149   }
1150 
1151   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1152     // FIXME: Assumes vectorcall is in use.
1153     return isX86VectorTypeForVectorCall(getContext(), Ty);
1154   }
1155 
1156   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1157                                          uint64_t NumMembers) const override {
1158     // FIXME: Assumes vectorcall is in use.
1159     return isX86VectorCallAggregateSmallEnough(NumMembers);
1160   }
1161 
1162   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1163 
1164   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1165   /// such that the argument will be passed in memory.
1166   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1167 
1168   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1169 
1170   /// Return the alignment to use for the given type on the stack.
1171   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1172 
1173   Class classify(QualType Ty) const;
1174   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1175   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1176 
1177   /// Updates the number of available free registers, returns
1178   /// true if any registers were allocated.
1179   bool updateFreeRegs(QualType Ty, CCState &State) const;
1180 
1181   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1182                                 bool &NeedsPadding) const;
1183   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1184 
1185   bool canExpandIndirectArgument(QualType Ty) const;
1186 
1187   /// Rewrite the function info so that all memory arguments use
1188   /// inalloca.
1189   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1190 
1191   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1192                            CharUnits &StackOffset, ABIArgInfo &Info,
1193                            QualType Type) const;
1194   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1195 
1196 public:
1197 
1198   void computeInfo(CGFunctionInfo &FI) const override;
1199   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1200                     QualType Ty) const override;
1201 
1202   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1203                 bool RetSmallStructInRegABI, bool Win32StructABI,
1204                 unsigned NumRegisterParameters, bool SoftFloatABI)
1205     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1206       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1207       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1208       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1209       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1210                  CGT.getTarget().getTriple().isOSCygMing()),
1211       DefaultNumRegisterParameters(NumRegisterParameters) {}
1212 
1213   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1214                                     bool asReturnValue) const override {
1215     // LLVM's x86-32 lowering currently only assigns up to three
1216     // integer registers and three fp registers.  Oddly, it'll use up to
1217     // four vector registers for vectors, but those can overlap with the
1218     // scalar registers.
1219     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1220   }
1221 
1222   bool isSwiftErrorInRegister() const override {
1223     // x86-32 lowering does not support passing swifterror in a register.
1224     return false;
1225   }
1226 };
1227 
1228 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1229 public:
1230   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1231                           bool RetSmallStructInRegABI, bool Win32StructABI,
1232                           unsigned NumRegisterParameters, bool SoftFloatABI)
1233       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1234             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1235             NumRegisterParameters, SoftFloatABI)) {}
1236 
1237   static bool isStructReturnInRegABI(
1238       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1239 
1240   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1241                            CodeGen::CodeGenModule &CGM) const override;
1242 
1243   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1244     // Darwin uses different dwarf register numbers for EH.
1245     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1246     return 4;
1247   }
1248 
1249   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1250                                llvm::Value *Address) const override;
1251 
1252   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1253                                   StringRef Constraint,
1254                                   llvm::Type* Ty) const override {
1255     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1256   }
1257 
1258   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1259                                 std::string &Constraints,
1260                                 std::vector<llvm::Type *> &ResultRegTypes,
1261                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1262                                 std::vector<LValue> &ResultRegDests,
1263                                 std::string &AsmString,
1264                                 unsigned NumOutputs) const override;
1265 
1266   llvm::Constant *
1267   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1268     unsigned Sig = (0xeb << 0) |  // jmp rel8
1269                    (0x06 << 8) |  //           .+0x08
1270                    ('v' << 16) |
1271                    ('2' << 24);
1272     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1273   }
1274 
1275   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1276     return "movl\t%ebp, %ebp"
1277            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1278   }
1279 };
1280 
1281 }
1282 
1283 /// Rewrite input constraint references after adding some output constraints.
1284 /// In the case where there is one output and one input and we add one output,
1285 /// we need to replace all operand references greater than or equal to 1:
1286 ///     mov $0, $1
1287 ///     mov eax, $1
1288 /// The result will be:
1289 ///     mov $0, $2
1290 ///     mov eax, $2
1291 static void rewriteInputConstraintReferences(unsigned FirstIn,
1292                                              unsigned NumNewOuts,
1293                                              std::string &AsmString) {
1294   std::string Buf;
1295   llvm::raw_string_ostream OS(Buf);
1296   size_t Pos = 0;
1297   while (Pos < AsmString.size()) {
1298     size_t DollarStart = AsmString.find('$', Pos);
1299     if (DollarStart == std::string::npos)
1300       DollarStart = AsmString.size();
1301     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1302     if (DollarEnd == std::string::npos)
1303       DollarEnd = AsmString.size();
1304     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1305     Pos = DollarEnd;
1306     size_t NumDollars = DollarEnd - DollarStart;
1307     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1308       // We have an operand reference.
1309       size_t DigitStart = Pos;
1310       if (AsmString[DigitStart] == '{') {
1311         OS << '{';
1312         ++DigitStart;
1313       }
1314       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1315       if (DigitEnd == std::string::npos)
1316         DigitEnd = AsmString.size();
1317       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1318       unsigned OperandIndex;
1319       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1320         if (OperandIndex >= FirstIn)
1321           OperandIndex += NumNewOuts;
1322         OS << OperandIndex;
1323       } else {
1324         OS << OperandStr;
1325       }
1326       Pos = DigitEnd;
1327     }
1328   }
1329   AsmString = std::move(OS.str());
1330 }
1331 
1332 /// Add output constraints for EAX:EDX because they are return registers.
1333 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1334     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1335     std::vector<llvm::Type *> &ResultRegTypes,
1336     std::vector<llvm::Type *> &ResultTruncRegTypes,
1337     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1338     unsigned NumOutputs) const {
1339   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1340 
1341   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1342   // larger.
1343   if (!Constraints.empty())
1344     Constraints += ',';
1345   if (RetWidth <= 32) {
1346     Constraints += "={eax}";
1347     ResultRegTypes.push_back(CGF.Int32Ty);
1348   } else {
1349     // Use the 'A' constraint for EAX:EDX.
1350     Constraints += "=A";
1351     ResultRegTypes.push_back(CGF.Int64Ty);
1352   }
1353 
1354   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1355   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1356   ResultTruncRegTypes.push_back(CoerceTy);
1357 
1358   // Coerce the integer by bitcasting the return slot pointer.
1359   ReturnSlot.setAddress(
1360       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1361   ResultRegDests.push_back(ReturnSlot);
1362 
1363   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1364 }
1365 
1366 /// shouldReturnTypeInRegister - Determine if the given type should be
1367 /// returned in a register (for the Darwin and MCU ABI).
1368 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1369                                                ASTContext &Context) const {
1370   uint64_t Size = Context.getTypeSize(Ty);
1371 
1372   // For i386, type must be register sized.
1373   // For the MCU ABI, it only needs to be <= 8-byte
1374   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1375    return false;
1376 
1377   if (Ty->isVectorType()) {
1378     // 64- and 128- bit vectors inside structures are not returned in
1379     // registers.
1380     if (Size == 64 || Size == 128)
1381       return false;
1382 
1383     return true;
1384   }
1385 
1386   // If this is a builtin, pointer, enum, complex type, member pointer, or
1387   // member function pointer it is ok.
1388   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1389       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1390       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1391     return true;
1392 
1393   // Arrays are treated like records.
1394   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1395     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1396 
1397   // Otherwise, it must be a record type.
1398   const RecordType *RT = Ty->getAs<RecordType>();
1399   if (!RT) return false;
1400 
1401   // FIXME: Traverse bases here too.
1402 
1403   // Structure types are passed in register if all fields would be
1404   // passed in a register.
1405   for (const auto *FD : RT->getDecl()->fields()) {
1406     // Empty fields are ignored.
1407     if (isEmptyField(Context, FD, true))
1408       continue;
1409 
1410     // Check fields recursively.
1411     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1412       return false;
1413   }
1414   return true;
1415 }
1416 
1417 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1418   // Treat complex types as the element type.
1419   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1420     Ty = CTy->getElementType();
1421 
1422   // Check for a type which we know has a simple scalar argument-passing
1423   // convention without any padding.  (We're specifically looking for 32
1424   // and 64-bit integer and integer-equivalents, float, and double.)
1425   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1426       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1427     return false;
1428 
1429   uint64_t Size = Context.getTypeSize(Ty);
1430   return Size == 32 || Size == 64;
1431 }
1432 
1433 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1434                           uint64_t &Size) {
1435   for (const auto *FD : RD->fields()) {
1436     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1437     // argument is smaller than 32-bits, expanding the struct will create
1438     // alignment padding.
1439     if (!is32Or64BitBasicType(FD->getType(), Context))
1440       return false;
1441 
1442     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1443     // how to expand them yet, and the predicate for telling if a bitfield still
1444     // counts as "basic" is more complicated than what we were doing previously.
1445     if (FD->isBitField())
1446       return false;
1447 
1448     Size += Context.getTypeSize(FD->getType());
1449   }
1450   return true;
1451 }
1452 
1453 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1454                                  uint64_t &Size) {
1455   // Don't do this if there are any non-empty bases.
1456   for (const CXXBaseSpecifier &Base : RD->bases()) {
1457     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1458                               Size))
1459       return false;
1460   }
1461   if (!addFieldSizes(Context, RD, Size))
1462     return false;
1463   return true;
1464 }
1465 
1466 /// Test whether an argument type which is to be passed indirectly (on the
1467 /// stack) would have the equivalent layout if it was expanded into separate
1468 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1469 /// optimizations.
1470 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1471   // We can only expand structure types.
1472   const RecordType *RT = Ty->getAs<RecordType>();
1473   if (!RT)
1474     return false;
1475   const RecordDecl *RD = RT->getDecl();
1476   uint64_t Size = 0;
1477   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1478     if (!IsWin32StructABI) {
1479       // On non-Windows, we have to conservatively match our old bitcode
1480       // prototypes in order to be ABI-compatible at the bitcode level.
1481       if (!CXXRD->isCLike())
1482         return false;
1483     } else {
1484       // Don't do this for dynamic classes.
1485       if (CXXRD->isDynamicClass())
1486         return false;
1487     }
1488     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1489       return false;
1490   } else {
1491     if (!addFieldSizes(getContext(), RD, Size))
1492       return false;
1493   }
1494 
1495   // We can do this if there was no alignment padding.
1496   return Size == getContext().getTypeSize(Ty);
1497 }
1498 
1499 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1500   // If the return value is indirect, then the hidden argument is consuming one
1501   // integer register.
1502   if (State.FreeRegs) {
1503     --State.FreeRegs;
1504     if (!IsMCUABI)
1505       return getNaturalAlignIndirectInReg(RetTy);
1506   }
1507   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1508 }
1509 
1510 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1511                                              CCState &State) const {
1512   if (RetTy->isVoidType())
1513     return ABIArgInfo::getIgnore();
1514 
1515   const Type *Base = nullptr;
1516   uint64_t NumElts = 0;
1517   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1518        State.CC == llvm::CallingConv::X86_RegCall) &&
1519       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1520     // The LLVM struct type for such an aggregate should lower properly.
1521     return ABIArgInfo::getDirect();
1522   }
1523 
1524   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1525     // On Darwin, some vectors are returned in registers.
1526     if (IsDarwinVectorABI) {
1527       uint64_t Size = getContext().getTypeSize(RetTy);
1528 
1529       // 128-bit vectors are a special case; they are returned in
1530       // registers and we need to make sure to pick a type the LLVM
1531       // backend will like.
1532       if (Size == 128)
1533         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1534             llvm::Type::getInt64Ty(getVMContext()), 2));
1535 
1536       // Always return in register if it fits in a general purpose
1537       // register, or if it is 64 bits and has a single element.
1538       if ((Size == 8 || Size == 16 || Size == 32) ||
1539           (Size == 64 && VT->getNumElements() == 1))
1540         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1541                                                             Size));
1542 
1543       return getIndirectReturnResult(RetTy, State);
1544     }
1545 
1546     return ABIArgInfo::getDirect();
1547   }
1548 
1549   if (isAggregateTypeForABI(RetTy)) {
1550     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1551       // Structures with flexible arrays are always indirect.
1552       if (RT->getDecl()->hasFlexibleArrayMember())
1553         return getIndirectReturnResult(RetTy, State);
1554     }
1555 
1556     // If specified, structs and unions are always indirect.
1557     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1558       return getIndirectReturnResult(RetTy, State);
1559 
1560     // Ignore empty structs/unions.
1561     if (isEmptyRecord(getContext(), RetTy, true))
1562       return ABIArgInfo::getIgnore();
1563 
1564     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1565     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1566       QualType ET = getContext().getCanonicalType(CT->getElementType());
1567       if (ET->isFloat16Type())
1568         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1569             llvm::Type::getHalfTy(getVMContext()), 2));
1570     }
1571 
1572     // Small structures which are register sized are generally returned
1573     // in a register.
1574     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1575       uint64_t Size = getContext().getTypeSize(RetTy);
1576 
1577       // As a special-case, if the struct is a "single-element" struct, and
1578       // the field is of type "float" or "double", return it in a
1579       // floating-point register. (MSVC does not apply this special case.)
1580       // We apply a similar transformation for pointer types to improve the
1581       // quality of the generated IR.
1582       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1583         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1584             || SeltTy->hasPointerRepresentation())
1585           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1586 
1587       // FIXME: We should be able to narrow this integer in cases with dead
1588       // padding.
1589       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1590     }
1591 
1592     return getIndirectReturnResult(RetTy, State);
1593   }
1594 
1595   // Treat an enum type as its underlying type.
1596   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1597     RetTy = EnumTy->getDecl()->getIntegerType();
1598 
1599   if (const auto *EIT = RetTy->getAs<BitIntType>())
1600     if (EIT->getNumBits() > 64)
1601       return getIndirectReturnResult(RetTy, State);
1602 
1603   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1604                                                : ABIArgInfo::getDirect());
1605 }
1606 
1607 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1608   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1609 }
1610 
1611 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1612   const RecordType *RT = Ty->getAs<RecordType>();
1613   if (!RT)
1614     return false;
1615   const RecordDecl *RD = RT->getDecl();
1616 
1617   // If this is a C++ record, check the bases first.
1618   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1619     for (const auto &I : CXXRD->bases())
1620       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1621         return false;
1622 
1623   for (const auto *i : RD->fields()) {
1624     QualType FT = i->getType();
1625 
1626     if (isSIMDVectorType(Context, FT))
1627       return true;
1628 
1629     if (isRecordWithSIMDVectorType(Context, FT))
1630       return true;
1631   }
1632 
1633   return false;
1634 }
1635 
1636 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1637                                                  unsigned Align) const {
1638   // Otherwise, if the alignment is less than or equal to the minimum ABI
1639   // alignment, just use the default; the backend will handle this.
1640   if (Align <= MinABIStackAlignInBytes)
1641     return 0; // Use default alignment.
1642 
1643   if (IsLinuxABI) {
1644     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1645     // want to spend any effort dealing with the ramifications of ABI breaks.
1646     //
1647     // If the vector type is __m128/__m256/__m512, return the default alignment.
1648     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1649       return Align;
1650   }
1651   // On non-Darwin, the stack type alignment is always 4.
1652   if (!IsDarwinVectorABI) {
1653     // Set explicit alignment, since we may need to realign the top.
1654     return MinABIStackAlignInBytes;
1655   }
1656 
1657   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1658   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1659                       isRecordWithSIMDVectorType(getContext(), Ty)))
1660     return 16;
1661 
1662   return MinABIStackAlignInBytes;
1663 }
1664 
1665 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1666                                             CCState &State) const {
1667   if (!ByVal) {
1668     if (State.FreeRegs) {
1669       --State.FreeRegs; // Non-byval indirects just use one pointer.
1670       if (!IsMCUABI)
1671         return getNaturalAlignIndirectInReg(Ty);
1672     }
1673     return getNaturalAlignIndirect(Ty, false);
1674   }
1675 
1676   // Compute the byval alignment.
1677   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1678   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1679   if (StackAlign == 0)
1680     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1681 
1682   // If the stack alignment is less than the type alignment, realign the
1683   // argument.
1684   bool Realign = TypeAlign > StackAlign;
1685   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1686                                  /*ByVal=*/true, Realign);
1687 }
1688 
1689 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1690   const Type *T = isSingleElementStruct(Ty, getContext());
1691   if (!T)
1692     T = Ty.getTypePtr();
1693 
1694   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1695     BuiltinType::Kind K = BT->getKind();
1696     if (K == BuiltinType::Float || K == BuiltinType::Double)
1697       return Float;
1698   }
1699   return Integer;
1700 }
1701 
1702 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1703   if (!IsSoftFloatABI) {
1704     Class C = classify(Ty);
1705     if (C == Float)
1706       return false;
1707   }
1708 
1709   unsigned Size = getContext().getTypeSize(Ty);
1710   unsigned SizeInRegs = (Size + 31) / 32;
1711 
1712   if (SizeInRegs == 0)
1713     return false;
1714 
1715   if (!IsMCUABI) {
1716     if (SizeInRegs > State.FreeRegs) {
1717       State.FreeRegs = 0;
1718       return false;
1719     }
1720   } else {
1721     // The MCU psABI allows passing parameters in-reg even if there are
1722     // earlier parameters that are passed on the stack. Also,
1723     // it does not allow passing >8-byte structs in-register,
1724     // even if there are 3 free registers available.
1725     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1726       return false;
1727   }
1728 
1729   State.FreeRegs -= SizeInRegs;
1730   return true;
1731 }
1732 
1733 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1734                                              bool &InReg,
1735                                              bool &NeedsPadding) const {
1736   // On Windows, aggregates other than HFAs are never passed in registers, and
1737   // they do not consume register slots. Homogenous floating-point aggregates
1738   // (HFAs) have already been dealt with at this point.
1739   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1740     return false;
1741 
1742   NeedsPadding = false;
1743   InReg = !IsMCUABI;
1744 
1745   if (!updateFreeRegs(Ty, State))
1746     return false;
1747 
1748   if (IsMCUABI)
1749     return true;
1750 
1751   if (State.CC == llvm::CallingConv::X86_FastCall ||
1752       State.CC == llvm::CallingConv::X86_VectorCall ||
1753       State.CC == llvm::CallingConv::X86_RegCall) {
1754     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1755       NeedsPadding = true;
1756 
1757     return false;
1758   }
1759 
1760   return true;
1761 }
1762 
1763 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1764   if (!updateFreeRegs(Ty, State))
1765     return false;
1766 
1767   if (IsMCUABI)
1768     return false;
1769 
1770   if (State.CC == llvm::CallingConv::X86_FastCall ||
1771       State.CC == llvm::CallingConv::X86_VectorCall ||
1772       State.CC == llvm::CallingConv::X86_RegCall) {
1773     if (getContext().getTypeSize(Ty) > 32)
1774       return false;
1775 
1776     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1777         Ty->isReferenceType());
1778   }
1779 
1780   return true;
1781 }
1782 
1783 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1784   // Vectorcall x86 works subtly different than in x64, so the format is
1785   // a bit different than the x64 version.  First, all vector types (not HVAs)
1786   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1787   // This differs from the x64 implementation, where the first 6 by INDEX get
1788   // registers.
1789   // In the second pass over the arguments, HVAs are passed in the remaining
1790   // vector registers if possible, or indirectly by address. The address will be
1791   // passed in ECX/EDX if available. Any other arguments are passed according to
1792   // the usual fastcall rules.
1793   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1794   for (int I = 0, E = Args.size(); I < E; ++I) {
1795     const Type *Base = nullptr;
1796     uint64_t NumElts = 0;
1797     const QualType &Ty = Args[I].type;
1798     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1799         isHomogeneousAggregate(Ty, Base, NumElts)) {
1800       if (State.FreeSSERegs >= NumElts) {
1801         State.FreeSSERegs -= NumElts;
1802         Args[I].info = ABIArgInfo::getDirectInReg();
1803         State.IsPreassigned.set(I);
1804       }
1805     }
1806   }
1807 }
1808 
1809 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1810                                                CCState &State) const {
1811   // FIXME: Set alignment on indirect arguments.
1812   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1813   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1814   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1815 
1816   Ty = useFirstFieldIfTransparentUnion(Ty);
1817   TypeInfo TI = getContext().getTypeInfo(Ty);
1818 
1819   // Check with the C++ ABI first.
1820   const RecordType *RT = Ty->getAs<RecordType>();
1821   if (RT) {
1822     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1823     if (RAA == CGCXXABI::RAA_Indirect) {
1824       return getIndirectResult(Ty, false, State);
1825     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1826       // The field index doesn't matter, we'll fix it up later.
1827       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1828     }
1829   }
1830 
1831   // Regcall uses the concept of a homogenous vector aggregate, similar
1832   // to other targets.
1833   const Type *Base = nullptr;
1834   uint64_t NumElts = 0;
1835   if ((IsRegCall || IsVectorCall) &&
1836       isHomogeneousAggregate(Ty, Base, NumElts)) {
1837     if (State.FreeSSERegs >= NumElts) {
1838       State.FreeSSERegs -= NumElts;
1839 
1840       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1841       // does.
1842       if (IsVectorCall)
1843         return getDirectX86Hva();
1844 
1845       if (Ty->isBuiltinType() || Ty->isVectorType())
1846         return ABIArgInfo::getDirect();
1847       return ABIArgInfo::getExpand();
1848     }
1849     return getIndirectResult(Ty, /*ByVal=*/false, State);
1850   }
1851 
1852   if (isAggregateTypeForABI(Ty)) {
1853     // Structures with flexible arrays are always indirect.
1854     // FIXME: This should not be byval!
1855     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1856       return getIndirectResult(Ty, true, State);
1857 
1858     // Ignore empty structs/unions on non-Windows.
1859     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1860       return ABIArgInfo::getIgnore();
1861 
1862     llvm::LLVMContext &LLVMContext = getVMContext();
1863     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1864     bool NeedsPadding = false;
1865     bool InReg;
1866     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1867       unsigned SizeInRegs = (TI.Width + 31) / 32;
1868       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1869       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1870       if (InReg)
1871         return ABIArgInfo::getDirectInReg(Result);
1872       else
1873         return ABIArgInfo::getDirect(Result);
1874     }
1875     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1876 
1877     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1878     // added in MSVC 2015.
1879     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1880       return getIndirectResult(Ty, /*ByVal=*/false, State);
1881 
1882     // Expand small (<= 128-bit) record types when we know that the stack layout
1883     // of those arguments will match the struct. This is important because the
1884     // LLVM backend isn't smart enough to remove byval, which inhibits many
1885     // optimizations.
1886     // Don't do this for the MCU if there are still free integer registers
1887     // (see X86_64 ABI for full explanation).
1888     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1889         canExpandIndirectArgument(Ty))
1890       return ABIArgInfo::getExpandWithPadding(
1891           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1892 
1893     return getIndirectResult(Ty, true, State);
1894   }
1895 
1896   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1897     // On Windows, vectors are passed directly if registers are available, or
1898     // indirectly if not. This avoids the need to align argument memory. Pass
1899     // user-defined vector types larger than 512 bits indirectly for simplicity.
1900     if (IsWin32StructABI) {
1901       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1902         --State.FreeSSERegs;
1903         return ABIArgInfo::getDirectInReg();
1904       }
1905       return getIndirectResult(Ty, /*ByVal=*/false, State);
1906     }
1907 
1908     // On Darwin, some vectors are passed in memory, we handle this by passing
1909     // it as an i8/i16/i32/i64.
1910     if (IsDarwinVectorABI) {
1911       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1912           (TI.Width == 64 && VT->getNumElements() == 1))
1913         return ABIArgInfo::getDirect(
1914             llvm::IntegerType::get(getVMContext(), TI.Width));
1915     }
1916 
1917     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1918       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1919 
1920     return ABIArgInfo::getDirect();
1921   }
1922 
1923 
1924   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1925     Ty = EnumTy->getDecl()->getIntegerType();
1926 
1927   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1928 
1929   if (isPromotableIntegerTypeForABI(Ty)) {
1930     if (InReg)
1931       return ABIArgInfo::getExtendInReg(Ty);
1932     return ABIArgInfo::getExtend(Ty);
1933   }
1934 
1935   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1936     if (EIT->getNumBits() <= 64) {
1937       if (InReg)
1938         return ABIArgInfo::getDirectInReg();
1939       return ABIArgInfo::getDirect();
1940     }
1941     return getIndirectResult(Ty, /*ByVal=*/false, State);
1942   }
1943 
1944   if (InReg)
1945     return ABIArgInfo::getDirectInReg();
1946   return ABIArgInfo::getDirect();
1947 }
1948 
1949 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1950   CCState State(FI);
1951   if (IsMCUABI)
1952     State.FreeRegs = 3;
1953   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1954     State.FreeRegs = 2;
1955     State.FreeSSERegs = 3;
1956   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1957     State.FreeRegs = 2;
1958     State.FreeSSERegs = 6;
1959   } else if (FI.getHasRegParm())
1960     State.FreeRegs = FI.getRegParm();
1961   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1962     State.FreeRegs = 5;
1963     State.FreeSSERegs = 8;
1964   } else if (IsWin32StructABI) {
1965     // Since MSVC 2015, the first three SSE vectors have been passed in
1966     // registers. The rest are passed indirectly.
1967     State.FreeRegs = DefaultNumRegisterParameters;
1968     State.FreeSSERegs = 3;
1969   } else
1970     State.FreeRegs = DefaultNumRegisterParameters;
1971 
1972   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1973     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1974   } else if (FI.getReturnInfo().isIndirect()) {
1975     // The C++ ABI is not aware of register usage, so we have to check if the
1976     // return value was sret and put it in a register ourselves if appropriate.
1977     if (State.FreeRegs) {
1978       --State.FreeRegs;  // The sret parameter consumes a register.
1979       if (!IsMCUABI)
1980         FI.getReturnInfo().setInReg(true);
1981     }
1982   }
1983 
1984   // The chain argument effectively gives us another free register.
1985   if (FI.isChainCall())
1986     ++State.FreeRegs;
1987 
1988   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1989   // arguments to XMM registers as available.
1990   if (State.CC == llvm::CallingConv::X86_VectorCall)
1991     runVectorCallFirstPass(FI, State);
1992 
1993   bool UsedInAlloca = false;
1994   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1995   for (int I = 0, E = Args.size(); I < E; ++I) {
1996     // Skip arguments that have already been assigned.
1997     if (State.IsPreassigned.test(I))
1998       continue;
1999 
2000     Args[I].info = classifyArgumentType(Args[I].type, State);
2001     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
2002   }
2003 
2004   // If we needed to use inalloca for any argument, do a second pass and rewrite
2005   // all the memory arguments to use inalloca.
2006   if (UsedInAlloca)
2007     rewriteWithInAlloca(FI);
2008 }
2009 
2010 void
2011 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2012                                    CharUnits &StackOffset, ABIArgInfo &Info,
2013                                    QualType Type) const {
2014   // Arguments are always 4-byte-aligned.
2015   CharUnits WordSize = CharUnits::fromQuantity(4);
2016   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2017 
2018   // sret pointers and indirect things will require an extra pointer
2019   // indirection, unless they are byval. Most things are byval, and will not
2020   // require this indirection.
2021   bool IsIndirect = false;
2022   if (Info.isIndirect() && !Info.getIndirectByVal())
2023     IsIndirect = true;
2024   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2025   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2026   if (IsIndirect)
2027     LLTy = LLTy->getPointerTo(0);
2028   FrameFields.push_back(LLTy);
2029   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2030 
2031   // Insert padding bytes to respect alignment.
2032   CharUnits FieldEnd = StackOffset;
2033   StackOffset = FieldEnd.alignTo(WordSize);
2034   if (StackOffset != FieldEnd) {
2035     CharUnits NumBytes = StackOffset - FieldEnd;
2036     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2037     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2038     FrameFields.push_back(Ty);
2039   }
2040 }
2041 
2042 static bool isArgInAlloca(const ABIArgInfo &Info) {
2043   // Leave ignored and inreg arguments alone.
2044   switch (Info.getKind()) {
2045   case ABIArgInfo::InAlloca:
2046     return true;
2047   case ABIArgInfo::Ignore:
2048   case ABIArgInfo::IndirectAliased:
2049     return false;
2050   case ABIArgInfo::Indirect:
2051   case ABIArgInfo::Direct:
2052   case ABIArgInfo::Extend:
2053     return !Info.getInReg();
2054   case ABIArgInfo::Expand:
2055   case ABIArgInfo::CoerceAndExpand:
2056     // These are aggregate types which are never passed in registers when
2057     // inalloca is involved.
2058     return true;
2059   }
2060   llvm_unreachable("invalid enum");
2061 }
2062 
2063 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2064   assert(IsWin32StructABI && "inalloca only supported on win32");
2065 
2066   // Build a packed struct type for all of the arguments in memory.
2067   SmallVector<llvm::Type *, 6> FrameFields;
2068 
2069   // The stack alignment is always 4.
2070   CharUnits StackAlign = CharUnits::fromQuantity(4);
2071 
2072   CharUnits StackOffset;
2073   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2074 
2075   // Put 'this' into the struct before 'sret', if necessary.
2076   bool IsThisCall =
2077       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2078   ABIArgInfo &Ret = FI.getReturnInfo();
2079   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2080       isArgInAlloca(I->info)) {
2081     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2082     ++I;
2083   }
2084 
2085   // Put the sret parameter into the inalloca struct if it's in memory.
2086   if (Ret.isIndirect() && !Ret.getInReg()) {
2087     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2088     // On Windows, the hidden sret parameter is always returned in eax.
2089     Ret.setInAllocaSRet(IsWin32StructABI);
2090   }
2091 
2092   // Skip the 'this' parameter in ecx.
2093   if (IsThisCall)
2094     ++I;
2095 
2096   // Put arguments passed in memory into the struct.
2097   for (; I != E; ++I) {
2098     if (isArgInAlloca(I->info))
2099       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2100   }
2101 
2102   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2103                                         /*isPacked=*/true),
2104                   StackAlign);
2105 }
2106 
2107 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2108                                  Address VAListAddr, QualType Ty) const {
2109 
2110   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2111 
2112   // x86-32 changes the alignment of certain arguments on the stack.
2113   //
2114   // Just messing with TypeInfo like this works because we never pass
2115   // anything indirectly.
2116   TypeInfo.Align = CharUnits::fromQuantity(
2117                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2118 
2119   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2120                           TypeInfo, CharUnits::fromQuantity(4),
2121                           /*AllowHigherAlign*/ true);
2122 }
2123 
2124 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2125     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2126   assert(Triple.getArch() == llvm::Triple::x86);
2127 
2128   switch (Opts.getStructReturnConvention()) {
2129   case CodeGenOptions::SRCK_Default:
2130     break;
2131   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2132     return false;
2133   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2134     return true;
2135   }
2136 
2137   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2138     return true;
2139 
2140   switch (Triple.getOS()) {
2141   case llvm::Triple::DragonFly:
2142   case llvm::Triple::FreeBSD:
2143   case llvm::Triple::OpenBSD:
2144   case llvm::Triple::Win32:
2145     return true;
2146   default:
2147     return false;
2148   }
2149 }
2150 
2151 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2152                                  CodeGen::CodeGenModule &CGM) {
2153   if (!FD->hasAttr<AnyX86InterruptAttr>())
2154     return;
2155 
2156   llvm::Function *Fn = cast<llvm::Function>(GV);
2157   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2158   if (FD->getNumParams() == 0)
2159     return;
2160 
2161   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2162   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2163   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2164     Fn->getContext(), ByValTy);
2165   Fn->addParamAttr(0, NewAttr);
2166 }
2167 
2168 void X86_32TargetCodeGenInfo::setTargetAttributes(
2169     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2170   if (GV->isDeclaration())
2171     return;
2172   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2173     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2174       llvm::Function *Fn = cast<llvm::Function>(GV);
2175       Fn->addFnAttr("stackrealign");
2176     }
2177 
2178     addX86InterruptAttrs(FD, GV, CGM);
2179   }
2180 }
2181 
2182 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2183                                                CodeGen::CodeGenFunction &CGF,
2184                                                llvm::Value *Address) const {
2185   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2186 
2187   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2188 
2189   // 0-7 are the eight integer registers;  the order is different
2190   //   on Darwin (for EH), but the range is the same.
2191   // 8 is %eip.
2192   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2193 
2194   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2195     // 12-16 are st(0..4).  Not sure why we stop at 4.
2196     // These have size 16, which is sizeof(long double) on
2197     // platforms with 8-byte alignment for that type.
2198     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2199     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2200 
2201   } else {
2202     // 9 is %eflags, which doesn't get a size on Darwin for some
2203     // reason.
2204     Builder.CreateAlignedStore(
2205         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2206                                CharUnits::One());
2207 
2208     // 11-16 are st(0..5).  Not sure why we stop at 5.
2209     // These have size 12, which is sizeof(long double) on
2210     // platforms with 4-byte alignment for that type.
2211     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2212     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2213   }
2214 
2215   return false;
2216 }
2217 
2218 //===----------------------------------------------------------------------===//
2219 // X86-64 ABI Implementation
2220 //===----------------------------------------------------------------------===//
2221 
2222 
2223 namespace {
2224 /// The AVX ABI level for X86 targets.
2225 enum class X86AVXABILevel {
2226   None,
2227   AVX,
2228   AVX512
2229 };
2230 
2231 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2232 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2233   switch (AVXLevel) {
2234   case X86AVXABILevel::AVX512:
2235     return 512;
2236   case X86AVXABILevel::AVX:
2237     return 256;
2238   case X86AVXABILevel::None:
2239     return 128;
2240   }
2241   llvm_unreachable("Unknown AVXLevel");
2242 }
2243 
2244 /// X86_64ABIInfo - The X86_64 ABI information.
2245 class X86_64ABIInfo : public SwiftABIInfo {
2246   enum Class {
2247     Integer = 0,
2248     SSE,
2249     SSEUp,
2250     X87,
2251     X87Up,
2252     ComplexX87,
2253     NoClass,
2254     Memory
2255   };
2256 
2257   /// merge - Implement the X86_64 ABI merging algorithm.
2258   ///
2259   /// Merge an accumulating classification \arg Accum with a field
2260   /// classification \arg Field.
2261   ///
2262   /// \param Accum - The accumulating classification. This should
2263   /// always be either NoClass or the result of a previous merge
2264   /// call. In addition, this should never be Memory (the caller
2265   /// should just return Memory for the aggregate).
2266   static Class merge(Class Accum, Class Field);
2267 
2268   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2269   ///
2270   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2271   /// final MEMORY or SSE classes when necessary.
2272   ///
2273   /// \param AggregateSize - The size of the current aggregate in
2274   /// the classification process.
2275   ///
2276   /// \param Lo - The classification for the parts of the type
2277   /// residing in the low word of the containing object.
2278   ///
2279   /// \param Hi - The classification for the parts of the type
2280   /// residing in the higher words of the containing object.
2281   ///
2282   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2283 
2284   /// classify - Determine the x86_64 register classes in which the
2285   /// given type T should be passed.
2286   ///
2287   /// \param Lo - The classification for the parts of the type
2288   /// residing in the low word of the containing object.
2289   ///
2290   /// \param Hi - The classification for the parts of the type
2291   /// residing in the high word of the containing object.
2292   ///
2293   /// \param OffsetBase - The bit offset of this type in the
2294   /// containing object.  Some parameters are classified different
2295   /// depending on whether they straddle an eightbyte boundary.
2296   ///
2297   /// \param isNamedArg - Whether the argument in question is a "named"
2298   /// argument, as used in AMD64-ABI 3.5.7.
2299   ///
2300   /// If a word is unused its result will be NoClass; if a type should
2301   /// be passed in Memory then at least the classification of \arg Lo
2302   /// will be Memory.
2303   ///
2304   /// The \arg Lo class will be NoClass iff the argument is ignored.
2305   ///
2306   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2307   /// also be ComplexX87.
2308   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2309                 bool isNamedArg) const;
2310 
2311   llvm::Type *GetByteVectorType(QualType Ty) const;
2312   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2313                                  unsigned IROffset, QualType SourceTy,
2314                                  unsigned SourceOffset) const;
2315   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2316                                      unsigned IROffset, QualType SourceTy,
2317                                      unsigned SourceOffset) const;
2318 
2319   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2320   /// such that the argument will be returned in memory.
2321   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2322 
2323   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2324   /// such that the argument will be passed in memory.
2325   ///
2326   /// \param freeIntRegs - The number of free integer registers remaining
2327   /// available.
2328   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2329 
2330   ABIArgInfo classifyReturnType(QualType RetTy) const;
2331 
2332   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2333                                   unsigned &neededInt, unsigned &neededSSE,
2334                                   bool isNamedArg) const;
2335 
2336   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2337                                        unsigned &NeededSSE) const;
2338 
2339   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2340                                            unsigned &NeededSSE) const;
2341 
2342   bool IsIllegalVectorType(QualType Ty) const;
2343 
2344   /// The 0.98 ABI revision clarified a lot of ambiguities,
2345   /// unfortunately in ways that were not always consistent with
2346   /// certain previous compilers.  In particular, platforms which
2347   /// required strict binary compatibility with older versions of GCC
2348   /// may need to exempt themselves.
2349   bool honorsRevision0_98() const {
2350     return !getTarget().getTriple().isOSDarwin();
2351   }
2352 
2353   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2354   /// classify it as INTEGER (for compatibility with older clang compilers).
2355   bool classifyIntegerMMXAsSSE() const {
2356     // Clang <= 3.8 did not do this.
2357     if (getContext().getLangOpts().getClangABICompat() <=
2358         LangOptions::ClangABI::Ver3_8)
2359       return false;
2360 
2361     const llvm::Triple &Triple = getTarget().getTriple();
2362     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2363       return false;
2364     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2365       return false;
2366     return true;
2367   }
2368 
2369   // GCC classifies vectors of __int128 as memory.
2370   bool passInt128VectorsInMem() const {
2371     // Clang <= 9.0 did not do this.
2372     if (getContext().getLangOpts().getClangABICompat() <=
2373         LangOptions::ClangABI::Ver9)
2374       return false;
2375 
2376     const llvm::Triple &T = getTarget().getTriple();
2377     return T.isOSLinux() || T.isOSNetBSD();
2378   }
2379 
2380   X86AVXABILevel AVXLevel;
2381   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2382   // 64-bit hardware.
2383   bool Has64BitPointers;
2384 
2385 public:
2386   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2387       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2388       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2389   }
2390 
2391   bool isPassedUsingAVXType(QualType type) const {
2392     unsigned neededInt, neededSSE;
2393     // The freeIntRegs argument doesn't matter here.
2394     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2395                                            /*isNamedArg*/true);
2396     if (info.isDirect()) {
2397       llvm::Type *ty = info.getCoerceToType();
2398       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2399         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2400     }
2401     return false;
2402   }
2403 
2404   void computeInfo(CGFunctionInfo &FI) const override;
2405 
2406   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2407                     QualType Ty) const override;
2408   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2409                       QualType Ty) const override;
2410 
2411   bool has64BitPointers() const {
2412     return Has64BitPointers;
2413   }
2414 
2415   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2416                                     bool asReturnValue) const override {
2417     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2418   }
2419   bool isSwiftErrorInRegister() const override {
2420     return true;
2421   }
2422 };
2423 
2424 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2425 class WinX86_64ABIInfo : public SwiftABIInfo {
2426 public:
2427   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2428       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2429         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2430 
2431   void computeInfo(CGFunctionInfo &FI) const override;
2432 
2433   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2434                     QualType Ty) const override;
2435 
2436   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2437     // FIXME: Assumes vectorcall is in use.
2438     return isX86VectorTypeForVectorCall(getContext(), Ty);
2439   }
2440 
2441   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2442                                          uint64_t NumMembers) const override {
2443     // FIXME: Assumes vectorcall is in use.
2444     return isX86VectorCallAggregateSmallEnough(NumMembers);
2445   }
2446 
2447   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2448                                     bool asReturnValue) const override {
2449     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2450   }
2451 
2452   bool isSwiftErrorInRegister() const override {
2453     return true;
2454   }
2455 
2456 private:
2457   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2458                       bool IsVectorCall, bool IsRegCall) const;
2459   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2460                                            const ABIArgInfo &current) const;
2461 
2462   X86AVXABILevel AVXLevel;
2463 
2464   bool IsMingw64;
2465 };
2466 
2467 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2468 public:
2469   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2470       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2471 
2472   const X86_64ABIInfo &getABIInfo() const {
2473     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2474   }
2475 
2476   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2477   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2478   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2479 
2480   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2481     return 7;
2482   }
2483 
2484   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2485                                llvm::Value *Address) const override {
2486     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2487 
2488     // 0-15 are the 16 integer registers.
2489     // 16 is %rip.
2490     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2491     return false;
2492   }
2493 
2494   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2495                                   StringRef Constraint,
2496                                   llvm::Type* Ty) const override {
2497     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2498   }
2499 
2500   bool isNoProtoCallVariadic(const CallArgList &args,
2501                              const FunctionNoProtoType *fnType) const override {
2502     // The default CC on x86-64 sets %al to the number of SSA
2503     // registers used, and GCC sets this when calling an unprototyped
2504     // function, so we override the default behavior.  However, don't do
2505     // that when AVX types are involved: the ABI explicitly states it is
2506     // undefined, and it doesn't work in practice because of how the ABI
2507     // defines varargs anyway.
2508     if (fnType->getCallConv() == CC_C) {
2509       bool HasAVXType = false;
2510       for (CallArgList::const_iterator
2511              it = args.begin(), ie = args.end(); it != ie; ++it) {
2512         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2513           HasAVXType = true;
2514           break;
2515         }
2516       }
2517 
2518       if (!HasAVXType)
2519         return true;
2520     }
2521 
2522     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2523   }
2524 
2525   llvm::Constant *
2526   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2527     unsigned Sig = (0xeb << 0) | // jmp rel8
2528                    (0x06 << 8) | //           .+0x08
2529                    ('v' << 16) |
2530                    ('2' << 24);
2531     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2532   }
2533 
2534   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2535                            CodeGen::CodeGenModule &CGM) const override {
2536     if (GV->isDeclaration())
2537       return;
2538     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2539       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2540         llvm::Function *Fn = cast<llvm::Function>(GV);
2541         Fn->addFnAttr("stackrealign");
2542       }
2543 
2544       addX86InterruptAttrs(FD, GV, CGM);
2545     }
2546   }
2547 
2548   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2549                             const FunctionDecl *Caller,
2550                             const FunctionDecl *Callee,
2551                             const CallArgList &Args) const override;
2552 };
2553 
2554 static void initFeatureMaps(const ASTContext &Ctx,
2555                             llvm::StringMap<bool> &CallerMap,
2556                             const FunctionDecl *Caller,
2557                             llvm::StringMap<bool> &CalleeMap,
2558                             const FunctionDecl *Callee) {
2559   if (CalleeMap.empty() && CallerMap.empty()) {
2560     // The caller is potentially nullptr in the case where the call isn't in a
2561     // function.  In this case, the getFunctionFeatureMap ensures we just get
2562     // the TU level setting (since it cannot be modified by 'target'..
2563     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2564     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2565   }
2566 }
2567 
2568 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2569                                  SourceLocation CallLoc,
2570                                  const llvm::StringMap<bool> &CallerMap,
2571                                  const llvm::StringMap<bool> &CalleeMap,
2572                                  QualType Ty, StringRef Feature,
2573                                  bool IsArgument) {
2574   bool CallerHasFeat = CallerMap.lookup(Feature);
2575   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2576   if (!CallerHasFeat && !CalleeHasFeat)
2577     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2578            << IsArgument << Ty << Feature;
2579 
2580   // Mixing calling conventions here is very clearly an error.
2581   if (!CallerHasFeat || !CalleeHasFeat)
2582     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2583            << IsArgument << Ty << Feature;
2584 
2585   // Else, both caller and callee have the required feature, so there is no need
2586   // to diagnose.
2587   return false;
2588 }
2589 
2590 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2591                           SourceLocation CallLoc,
2592                           const llvm::StringMap<bool> &CallerMap,
2593                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2594                           bool IsArgument) {
2595   uint64_t Size = Ctx.getTypeSize(Ty);
2596   if (Size > 256)
2597     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2598                                 "avx512f", IsArgument);
2599 
2600   if (Size > 128)
2601     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2602                                 IsArgument);
2603 
2604   return false;
2605 }
2606 
2607 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2608     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2609     const FunctionDecl *Callee, const CallArgList &Args) const {
2610   llvm::StringMap<bool> CallerMap;
2611   llvm::StringMap<bool> CalleeMap;
2612   unsigned ArgIndex = 0;
2613 
2614   // We need to loop through the actual call arguments rather than the the
2615   // function's parameters, in case this variadic.
2616   for (const CallArg &Arg : Args) {
2617     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2618     // additionally changes how vectors >256 in size are passed. Like GCC, we
2619     // warn when a function is called with an argument where this will change.
2620     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2621     // the caller and callee features are mismatched.
2622     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2623     // change its ABI with attribute-target after this call.
2624     if (Arg.getType()->isVectorType() &&
2625         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2626       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2627       QualType Ty = Arg.getType();
2628       // The CallArg seems to have desugared the type already, so for clearer
2629       // diagnostics, replace it with the type in the FunctionDecl if possible.
2630       if (ArgIndex < Callee->getNumParams())
2631         Ty = Callee->getParamDecl(ArgIndex)->getType();
2632 
2633       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2634                         CalleeMap, Ty, /*IsArgument*/ true))
2635         return;
2636     }
2637     ++ArgIndex;
2638   }
2639 
2640   // Check return always, as we don't have a good way of knowing in codegen
2641   // whether this value is used, tail-called, etc.
2642   if (Callee->getReturnType()->isVectorType() &&
2643       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2644     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2645     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2646                   CalleeMap, Callee->getReturnType(),
2647                   /*IsArgument*/ false);
2648   }
2649 }
2650 
2651 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2652   // If the argument does not end in .lib, automatically add the suffix.
2653   // If the argument contains a space, enclose it in quotes.
2654   // This matches the behavior of MSVC.
2655   bool Quote = Lib.contains(' ');
2656   std::string ArgStr = Quote ? "\"" : "";
2657   ArgStr += Lib;
2658   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2659     ArgStr += ".lib";
2660   ArgStr += Quote ? "\"" : "";
2661   return ArgStr;
2662 }
2663 
2664 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2665 public:
2666   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2667         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2668         unsigned NumRegisterParameters)
2669     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2670         Win32StructABI, NumRegisterParameters, false) {}
2671 
2672   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2673                            CodeGen::CodeGenModule &CGM) const override;
2674 
2675   void getDependentLibraryOption(llvm::StringRef Lib,
2676                                  llvm::SmallString<24> &Opt) const override {
2677     Opt = "/DEFAULTLIB:";
2678     Opt += qualifyWindowsLibrary(Lib);
2679   }
2680 
2681   void getDetectMismatchOption(llvm::StringRef Name,
2682                                llvm::StringRef Value,
2683                                llvm::SmallString<32> &Opt) const override {
2684     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2685   }
2686 };
2687 
2688 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2689                                           CodeGen::CodeGenModule &CGM) {
2690   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2691 
2692     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2693       Fn->addFnAttr("stack-probe-size",
2694                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2695     if (CGM.getCodeGenOpts().NoStackArgProbe)
2696       Fn->addFnAttr("no-stack-arg-probe");
2697   }
2698 }
2699 
2700 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2701     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2702   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2703   if (GV->isDeclaration())
2704     return;
2705   addStackProbeTargetAttributes(D, GV, CGM);
2706 }
2707 
2708 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2709 public:
2710   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2711                              X86AVXABILevel AVXLevel)
2712       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2713 
2714   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2715                            CodeGen::CodeGenModule &CGM) const override;
2716 
2717   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2718     return 7;
2719   }
2720 
2721   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2722                                llvm::Value *Address) const override {
2723     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2724 
2725     // 0-15 are the 16 integer registers.
2726     // 16 is %rip.
2727     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2728     return false;
2729   }
2730 
2731   void getDependentLibraryOption(llvm::StringRef Lib,
2732                                  llvm::SmallString<24> &Opt) const override {
2733     Opt = "/DEFAULTLIB:";
2734     Opt += qualifyWindowsLibrary(Lib);
2735   }
2736 
2737   void getDetectMismatchOption(llvm::StringRef Name,
2738                                llvm::StringRef Value,
2739                                llvm::SmallString<32> &Opt) const override {
2740     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2741   }
2742 };
2743 
2744 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2745     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2746   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2747   if (GV->isDeclaration())
2748     return;
2749   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2750     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2751       llvm::Function *Fn = cast<llvm::Function>(GV);
2752       Fn->addFnAttr("stackrealign");
2753     }
2754 
2755     addX86InterruptAttrs(FD, GV, CGM);
2756   }
2757 
2758   addStackProbeTargetAttributes(D, GV, CGM);
2759 }
2760 }
2761 
2762 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2763                               Class &Hi) const {
2764   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2765   //
2766   // (a) If one of the classes is Memory, the whole argument is passed in
2767   //     memory.
2768   //
2769   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2770   //     memory.
2771   //
2772   // (c) If the size of the aggregate exceeds two eightbytes and the first
2773   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2774   //     argument is passed in memory. NOTE: This is necessary to keep the
2775   //     ABI working for processors that don't support the __m256 type.
2776   //
2777   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2778   //
2779   // Some of these are enforced by the merging logic.  Others can arise
2780   // only with unions; for example:
2781   //   union { _Complex double; unsigned; }
2782   //
2783   // Note that clauses (b) and (c) were added in 0.98.
2784   //
2785   if (Hi == Memory)
2786     Lo = Memory;
2787   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2788     Lo = Memory;
2789   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2790     Lo = Memory;
2791   if (Hi == SSEUp && Lo != SSE)
2792     Hi = SSE;
2793 }
2794 
2795 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2796   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2797   // classified recursively so that always two fields are
2798   // considered. The resulting class is calculated according to
2799   // the classes of the fields in the eightbyte:
2800   //
2801   // (a) If both classes are equal, this is the resulting class.
2802   //
2803   // (b) If one of the classes is NO_CLASS, the resulting class is
2804   // the other class.
2805   //
2806   // (c) If one of the classes is MEMORY, the result is the MEMORY
2807   // class.
2808   //
2809   // (d) If one of the classes is INTEGER, the result is the
2810   // INTEGER.
2811   //
2812   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2813   // MEMORY is used as class.
2814   //
2815   // (f) Otherwise class SSE is used.
2816 
2817   // Accum should never be memory (we should have returned) or
2818   // ComplexX87 (because this cannot be passed in a structure).
2819   assert((Accum != Memory && Accum != ComplexX87) &&
2820          "Invalid accumulated classification during merge.");
2821   if (Accum == Field || Field == NoClass)
2822     return Accum;
2823   if (Field == Memory)
2824     return Memory;
2825   if (Accum == NoClass)
2826     return Field;
2827   if (Accum == Integer || Field == Integer)
2828     return Integer;
2829   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2830       Accum == X87 || Accum == X87Up)
2831     return Memory;
2832   return SSE;
2833 }
2834 
2835 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2836                              Class &Lo, Class &Hi, bool isNamedArg) const {
2837   // FIXME: This code can be simplified by introducing a simple value class for
2838   // Class pairs with appropriate constructor methods for the various
2839   // situations.
2840 
2841   // FIXME: Some of the split computations are wrong; unaligned vectors
2842   // shouldn't be passed in registers for example, so there is no chance they
2843   // can straddle an eightbyte. Verify & simplify.
2844 
2845   Lo = Hi = NoClass;
2846 
2847   Class &Current = OffsetBase < 64 ? Lo : Hi;
2848   Current = Memory;
2849 
2850   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2851     BuiltinType::Kind k = BT->getKind();
2852 
2853     if (k == BuiltinType::Void) {
2854       Current = NoClass;
2855     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2856       Lo = Integer;
2857       Hi = Integer;
2858     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2859       Current = Integer;
2860     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2861                k == BuiltinType::Float16) {
2862       Current = SSE;
2863     } else if (k == BuiltinType::LongDouble) {
2864       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2865       if (LDF == &llvm::APFloat::IEEEquad()) {
2866         Lo = SSE;
2867         Hi = SSEUp;
2868       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2869         Lo = X87;
2870         Hi = X87Up;
2871       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2872         Current = SSE;
2873       } else
2874         llvm_unreachable("unexpected long double representation!");
2875     }
2876     // FIXME: _Decimal32 and _Decimal64 are SSE.
2877     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2878     return;
2879   }
2880 
2881   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2882     // Classify the underlying integer type.
2883     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2884     return;
2885   }
2886 
2887   if (Ty->hasPointerRepresentation()) {
2888     Current = Integer;
2889     return;
2890   }
2891 
2892   if (Ty->isMemberPointerType()) {
2893     if (Ty->isMemberFunctionPointerType()) {
2894       if (Has64BitPointers) {
2895         // If Has64BitPointers, this is an {i64, i64}, so classify both
2896         // Lo and Hi now.
2897         Lo = Hi = Integer;
2898       } else {
2899         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2900         // straddles an eightbyte boundary, Hi should be classified as well.
2901         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2902         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2903         if (EB_FuncPtr != EB_ThisAdj) {
2904           Lo = Hi = Integer;
2905         } else {
2906           Current = Integer;
2907         }
2908       }
2909     } else {
2910       Current = Integer;
2911     }
2912     return;
2913   }
2914 
2915   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2916     uint64_t Size = getContext().getTypeSize(VT);
2917     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2918       // gcc passes the following as integer:
2919       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2920       // 2 bytes - <2 x char>, <1 x short>
2921       // 1 byte  - <1 x char>
2922       Current = Integer;
2923 
2924       // If this type crosses an eightbyte boundary, it should be
2925       // split.
2926       uint64_t EB_Lo = (OffsetBase) / 64;
2927       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2928       if (EB_Lo != EB_Hi)
2929         Hi = Lo;
2930     } else if (Size == 64) {
2931       QualType ElementType = VT->getElementType();
2932 
2933       // gcc passes <1 x double> in memory. :(
2934       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2935         return;
2936 
2937       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2938       // pass them as integer.  For platforms where clang is the de facto
2939       // platform compiler, we must continue to use integer.
2940       if (!classifyIntegerMMXAsSSE() &&
2941           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2942            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2943            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2944            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2945         Current = Integer;
2946       else
2947         Current = SSE;
2948 
2949       // If this type crosses an eightbyte boundary, it should be
2950       // split.
2951       if (OffsetBase && OffsetBase != 64)
2952         Hi = Lo;
2953     } else if (Size == 128 ||
2954                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2955       QualType ElementType = VT->getElementType();
2956 
2957       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2958       if (passInt128VectorsInMem() && Size != 128 &&
2959           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2960            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2961         return;
2962 
2963       // Arguments of 256-bits are split into four eightbyte chunks. The
2964       // least significant one belongs to class SSE and all the others to class
2965       // SSEUP. The original Lo and Hi design considers that types can't be
2966       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2967       // This design isn't correct for 256-bits, but since there're no cases
2968       // where the upper parts would need to be inspected, avoid adding
2969       // complexity and just consider Hi to match the 64-256 part.
2970       //
2971       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2972       // registers if they are "named", i.e. not part of the "..." of a
2973       // variadic function.
2974       //
2975       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2976       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2977       Lo = SSE;
2978       Hi = SSEUp;
2979     }
2980     return;
2981   }
2982 
2983   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2984     QualType ET = getContext().getCanonicalType(CT->getElementType());
2985 
2986     uint64_t Size = getContext().getTypeSize(Ty);
2987     if (ET->isIntegralOrEnumerationType()) {
2988       if (Size <= 64)
2989         Current = Integer;
2990       else if (Size <= 128)
2991         Lo = Hi = Integer;
2992     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2993       Current = SSE;
2994     } else if (ET == getContext().DoubleTy) {
2995       Lo = Hi = SSE;
2996     } else if (ET == getContext().LongDoubleTy) {
2997       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2998       if (LDF == &llvm::APFloat::IEEEquad())
2999         Current = Memory;
3000       else if (LDF == &llvm::APFloat::x87DoubleExtended())
3001         Current = ComplexX87;
3002       else if (LDF == &llvm::APFloat::IEEEdouble())
3003         Lo = Hi = SSE;
3004       else
3005         llvm_unreachable("unexpected long double representation!");
3006     }
3007 
3008     // If this complex type crosses an eightbyte boundary then it
3009     // should be split.
3010     uint64_t EB_Real = (OffsetBase) / 64;
3011     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3012     if (Hi == NoClass && EB_Real != EB_Imag)
3013       Hi = Lo;
3014 
3015     return;
3016   }
3017 
3018   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3019     if (EITy->getNumBits() <= 64)
3020       Current = Integer;
3021     else if (EITy->getNumBits() <= 128)
3022       Lo = Hi = Integer;
3023     // Larger values need to get passed in memory.
3024     return;
3025   }
3026 
3027   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3028     // Arrays are treated like structures.
3029 
3030     uint64_t Size = getContext().getTypeSize(Ty);
3031 
3032     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3033     // than eight eightbytes, ..., it has class MEMORY.
3034     if (Size > 512)
3035       return;
3036 
3037     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3038     // fields, it has class MEMORY.
3039     //
3040     // Only need to check alignment of array base.
3041     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3042       return;
3043 
3044     // Otherwise implement simplified merge. We could be smarter about
3045     // this, but it isn't worth it and would be harder to verify.
3046     Current = NoClass;
3047     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3048     uint64_t ArraySize = AT->getSize().getZExtValue();
3049 
3050     // The only case a 256-bit wide vector could be used is when the array
3051     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3052     // to work for sizes wider than 128, early check and fallback to memory.
3053     //
3054     if (Size > 128 &&
3055         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3056       return;
3057 
3058     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3059       Class FieldLo, FieldHi;
3060       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3061       Lo = merge(Lo, FieldLo);
3062       Hi = merge(Hi, FieldHi);
3063       if (Lo == Memory || Hi == Memory)
3064         break;
3065     }
3066 
3067     postMerge(Size, Lo, Hi);
3068     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3069     return;
3070   }
3071 
3072   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3073     uint64_t Size = getContext().getTypeSize(Ty);
3074 
3075     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3076     // than eight eightbytes, ..., it has class MEMORY.
3077     if (Size > 512)
3078       return;
3079 
3080     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3081     // copy constructor or a non-trivial destructor, it is passed by invisible
3082     // reference.
3083     if (getRecordArgABI(RT, getCXXABI()))
3084       return;
3085 
3086     const RecordDecl *RD = RT->getDecl();
3087 
3088     // Assume variable sized types are passed in memory.
3089     if (RD->hasFlexibleArrayMember())
3090       return;
3091 
3092     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3093 
3094     // Reset Lo class, this will be recomputed.
3095     Current = NoClass;
3096 
3097     // If this is a C++ record, classify the bases first.
3098     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3099       for (const auto &I : CXXRD->bases()) {
3100         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3101                "Unexpected base class!");
3102         const auto *Base =
3103             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3104 
3105         // Classify this field.
3106         //
3107         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3108         // single eightbyte, each is classified separately. Each eightbyte gets
3109         // initialized to class NO_CLASS.
3110         Class FieldLo, FieldHi;
3111         uint64_t Offset =
3112           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3113         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3114         Lo = merge(Lo, FieldLo);
3115         Hi = merge(Hi, FieldHi);
3116         if (Lo == Memory || Hi == Memory) {
3117           postMerge(Size, Lo, Hi);
3118           return;
3119         }
3120       }
3121     }
3122 
3123     // Classify the fields one at a time, merging the results.
3124     unsigned idx = 0;
3125     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3126                                 LangOptions::ClangABI::Ver11 ||
3127                             getContext().getTargetInfo().getTriple().isPS4();
3128     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3129 
3130     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3131            i != e; ++i, ++idx) {
3132       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3133       bool BitField = i->isBitField();
3134 
3135       // Ignore padding bit-fields.
3136       if (BitField && i->isUnnamedBitfield())
3137         continue;
3138 
3139       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3140       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3141       //
3142       // The only case a 256-bit or a 512-bit wide vector could be used is when
3143       // the struct contains a single 256-bit or 512-bit element. Early check
3144       // and fallback to memory.
3145       //
3146       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3147       // than 128.
3148       if (Size > 128 &&
3149           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3150            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3151         Lo = Memory;
3152         postMerge(Size, Lo, Hi);
3153         return;
3154       }
3155       // Note, skip this test for bit-fields, see below.
3156       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3157         Lo = Memory;
3158         postMerge(Size, Lo, Hi);
3159         return;
3160       }
3161 
3162       // Classify this field.
3163       //
3164       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3165       // exceeds a single eightbyte, each is classified
3166       // separately. Each eightbyte gets initialized to class
3167       // NO_CLASS.
3168       Class FieldLo, FieldHi;
3169 
3170       // Bit-fields require special handling, they do not force the
3171       // structure to be passed in memory even if unaligned, and
3172       // therefore they can straddle an eightbyte.
3173       if (BitField) {
3174         assert(!i->isUnnamedBitfield());
3175         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3176         uint64_t Size = i->getBitWidthValue(getContext());
3177 
3178         uint64_t EB_Lo = Offset / 64;
3179         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3180 
3181         if (EB_Lo) {
3182           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3183           FieldLo = NoClass;
3184           FieldHi = Integer;
3185         } else {
3186           FieldLo = Integer;
3187           FieldHi = EB_Hi ? Integer : NoClass;
3188         }
3189       } else
3190         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3191       Lo = merge(Lo, FieldLo);
3192       Hi = merge(Hi, FieldHi);
3193       if (Lo == Memory || Hi == Memory)
3194         break;
3195     }
3196 
3197     postMerge(Size, Lo, Hi);
3198   }
3199 }
3200 
3201 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3202   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3203   // place naturally.
3204   if (!isAggregateTypeForABI(Ty)) {
3205     // Treat an enum type as its underlying type.
3206     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3207       Ty = EnumTy->getDecl()->getIntegerType();
3208 
3209     if (Ty->isBitIntType())
3210       return getNaturalAlignIndirect(Ty);
3211 
3212     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3213                                               : ABIArgInfo::getDirect());
3214   }
3215 
3216   return getNaturalAlignIndirect(Ty);
3217 }
3218 
3219 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3220   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3221     uint64_t Size = getContext().getTypeSize(VecTy);
3222     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3223     if (Size <= 64 || Size > LargestVector)
3224       return true;
3225     QualType EltTy = VecTy->getElementType();
3226     if (passInt128VectorsInMem() &&
3227         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3228          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3229       return true;
3230   }
3231 
3232   return false;
3233 }
3234 
3235 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3236                                             unsigned freeIntRegs) const {
3237   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3238   // place naturally.
3239   //
3240   // This assumption is optimistic, as there could be free registers available
3241   // when we need to pass this argument in memory, and LLVM could try to pass
3242   // the argument in the free register. This does not seem to happen currently,
3243   // but this code would be much safer if we could mark the argument with
3244   // 'onstack'. See PR12193.
3245   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3246       !Ty->isBitIntType()) {
3247     // Treat an enum type as its underlying type.
3248     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3249       Ty = EnumTy->getDecl()->getIntegerType();
3250 
3251     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3252                                               : ABIArgInfo::getDirect());
3253   }
3254 
3255   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3256     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3257 
3258   // Compute the byval alignment. We specify the alignment of the byval in all
3259   // cases so that the mid-level optimizer knows the alignment of the byval.
3260   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3261 
3262   // Attempt to avoid passing indirect results using byval when possible. This
3263   // is important for good codegen.
3264   //
3265   // We do this by coercing the value into a scalar type which the backend can
3266   // handle naturally (i.e., without using byval).
3267   //
3268   // For simplicity, we currently only do this when we have exhausted all of the
3269   // free integer registers. Doing this when there are free integer registers
3270   // would require more care, as we would have to ensure that the coerced value
3271   // did not claim the unused register. That would require either reording the
3272   // arguments to the function (so that any subsequent inreg values came first),
3273   // or only doing this optimization when there were no following arguments that
3274   // might be inreg.
3275   //
3276   // We currently expect it to be rare (particularly in well written code) for
3277   // arguments to be passed on the stack when there are still free integer
3278   // registers available (this would typically imply large structs being passed
3279   // by value), so this seems like a fair tradeoff for now.
3280   //
3281   // We can revisit this if the backend grows support for 'onstack' parameter
3282   // attributes. See PR12193.
3283   if (freeIntRegs == 0) {
3284     uint64_t Size = getContext().getTypeSize(Ty);
3285 
3286     // If this type fits in an eightbyte, coerce it into the matching integral
3287     // type, which will end up on the stack (with alignment 8).
3288     if (Align == 8 && Size <= 64)
3289       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3290                                                           Size));
3291   }
3292 
3293   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3294 }
3295 
3296 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3297 /// register. Pick an LLVM IR type that will be passed as a vector register.
3298 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3299   // Wrapper structs/arrays that only contain vectors are passed just like
3300   // vectors; strip them off if present.
3301   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3302     Ty = QualType(InnerTy, 0);
3303 
3304   llvm::Type *IRType = CGT.ConvertType(Ty);
3305   if (isa<llvm::VectorType>(IRType)) {
3306     // Don't pass vXi128 vectors in their native type, the backend can't
3307     // legalize them.
3308     if (passInt128VectorsInMem() &&
3309         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3310       // Use a vXi64 vector.
3311       uint64_t Size = getContext().getTypeSize(Ty);
3312       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3313                                         Size / 64);
3314     }
3315 
3316     return IRType;
3317   }
3318 
3319   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3320     return IRType;
3321 
3322   // We couldn't find the preferred IR vector type for 'Ty'.
3323   uint64_t Size = getContext().getTypeSize(Ty);
3324   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3325 
3326 
3327   // Return a LLVM IR vector type based on the size of 'Ty'.
3328   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3329                                     Size / 64);
3330 }
3331 
3332 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3333 /// is known to either be off the end of the specified type or being in
3334 /// alignment padding.  The user type specified is known to be at most 128 bits
3335 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3336 /// classification that put one of the two halves in the INTEGER class.
3337 ///
3338 /// It is conservatively correct to return false.
3339 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3340                                   unsigned EndBit, ASTContext &Context) {
3341   // If the bytes being queried are off the end of the type, there is no user
3342   // data hiding here.  This handles analysis of builtins, vectors and other
3343   // types that don't contain interesting padding.
3344   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3345   if (TySize <= StartBit)
3346     return true;
3347 
3348   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3349     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3350     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3351 
3352     // Check each element to see if the element overlaps with the queried range.
3353     for (unsigned i = 0; i != NumElts; ++i) {
3354       // If the element is after the span we care about, then we're done..
3355       unsigned EltOffset = i*EltSize;
3356       if (EltOffset >= EndBit) break;
3357 
3358       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3359       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3360                                  EndBit-EltOffset, Context))
3361         return false;
3362     }
3363     // If it overlaps no elements, then it is safe to process as padding.
3364     return true;
3365   }
3366 
3367   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3368     const RecordDecl *RD = RT->getDecl();
3369     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3370 
3371     // If this is a C++ record, check the bases first.
3372     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3373       for (const auto &I : CXXRD->bases()) {
3374         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3375                "Unexpected base class!");
3376         const auto *Base =
3377             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3378 
3379         // If the base is after the span we care about, ignore it.
3380         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3381         if (BaseOffset >= EndBit) continue;
3382 
3383         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3384         if (!BitsContainNoUserData(I.getType(), BaseStart,
3385                                    EndBit-BaseOffset, Context))
3386           return false;
3387       }
3388     }
3389 
3390     // Verify that no field has data that overlaps the region of interest.  Yes
3391     // this could be sped up a lot by being smarter about queried fields,
3392     // however we're only looking at structs up to 16 bytes, so we don't care
3393     // much.
3394     unsigned idx = 0;
3395     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3396          i != e; ++i, ++idx) {
3397       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3398 
3399       // If we found a field after the region we care about, then we're done.
3400       if (FieldOffset >= EndBit) break;
3401 
3402       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3403       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3404                                  Context))
3405         return false;
3406     }
3407 
3408     // If nothing in this record overlapped the area of interest, then we're
3409     // clean.
3410     return true;
3411   }
3412 
3413   return false;
3414 }
3415 
3416 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3417 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3418                                      const llvm::DataLayout &TD) {
3419   if (IROffset == 0 && IRType->isFloatingPointTy())
3420     return IRType;
3421 
3422   // If this is a struct, recurse into the field at the specified offset.
3423   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3424     if (!STy->getNumContainedTypes())
3425       return nullptr;
3426 
3427     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3428     unsigned Elt = SL->getElementContainingOffset(IROffset);
3429     IROffset -= SL->getElementOffset(Elt);
3430     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3431   }
3432 
3433   // If this is an array, recurse into the field at the specified offset.
3434   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3435     llvm::Type *EltTy = ATy->getElementType();
3436     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3437     IROffset -= IROffset / EltSize * EltSize;
3438     return getFPTypeAtOffset(EltTy, IROffset, TD);
3439   }
3440 
3441   return nullptr;
3442 }
3443 
3444 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3445 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3446 llvm::Type *X86_64ABIInfo::
3447 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3448                    QualType SourceTy, unsigned SourceOffset) const {
3449   const llvm::DataLayout &TD = getDataLayout();
3450   unsigned SourceSize =
3451       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3452   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3453   if (!T0 || T0->isDoubleTy())
3454     return llvm::Type::getDoubleTy(getVMContext());
3455 
3456   // Get the adjacent FP type.
3457   llvm::Type *T1 = nullptr;
3458   unsigned T0Size = TD.getTypeAllocSize(T0);
3459   if (SourceSize > T0Size)
3460       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3461   if (T1 == nullptr) {
3462     // Check if IRType is a half + float. float type will be in IROffset+4 due
3463     // to its alignment.
3464     if (T0->isHalfTy() && SourceSize > 4)
3465       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3466     // If we can't get a second FP type, return a simple half or float.
3467     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3468     // {float, i8} too.
3469     if (T1 == nullptr)
3470       return T0;
3471   }
3472 
3473   if (T0->isFloatTy() && T1->isFloatTy())
3474     return llvm::FixedVectorType::get(T0, 2);
3475 
3476   if (T0->isHalfTy() && T1->isHalfTy()) {
3477     llvm::Type *T2 = nullptr;
3478     if (SourceSize > 4)
3479       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3480     if (T2 == nullptr)
3481       return llvm::FixedVectorType::get(T0, 2);
3482     return llvm::FixedVectorType::get(T0, 4);
3483   }
3484 
3485   if (T0->isHalfTy() || T1->isHalfTy())
3486     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3487 
3488   return llvm::Type::getDoubleTy(getVMContext());
3489 }
3490 
3491 
3492 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3493 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3494 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3495 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3496 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3497 /// etc).
3498 ///
3499 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3500 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3501 /// the 8-byte value references.  PrefType may be null.
3502 ///
3503 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3504 /// an offset into this that we're processing (which is always either 0 or 8).
3505 ///
3506 llvm::Type *X86_64ABIInfo::
3507 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3508                        QualType SourceTy, unsigned SourceOffset) const {
3509   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3510   // returning an 8-byte unit starting with it.  See if we can safely use it.
3511   if (IROffset == 0) {
3512     // Pointers and int64's always fill the 8-byte unit.
3513     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3514         IRType->isIntegerTy(64))
3515       return IRType;
3516 
3517     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3518     // goodness in the source type is just tail padding.  This is allowed to
3519     // kick in for struct {double,int} on the int, but not on
3520     // struct{double,int,int} because we wouldn't return the second int.  We
3521     // have to do this analysis on the source type because we can't depend on
3522     // unions being lowered a specific way etc.
3523     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3524         IRType->isIntegerTy(32) ||
3525         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3526       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3527           cast<llvm::IntegerType>(IRType)->getBitWidth();
3528 
3529       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3530                                 SourceOffset*8+64, getContext()))
3531         return IRType;
3532     }
3533   }
3534 
3535   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3536     // If this is a struct, recurse into the field at the specified offset.
3537     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3538     if (IROffset < SL->getSizeInBytes()) {
3539       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3540       IROffset -= SL->getElementOffset(FieldIdx);
3541 
3542       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3543                                     SourceTy, SourceOffset);
3544     }
3545   }
3546 
3547   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3548     llvm::Type *EltTy = ATy->getElementType();
3549     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3550     unsigned EltOffset = IROffset/EltSize*EltSize;
3551     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3552                                   SourceOffset);
3553   }
3554 
3555   // Okay, we don't have any better idea of what to pass, so we pass this in an
3556   // integer register that isn't too big to fit the rest of the struct.
3557   unsigned TySizeInBytes =
3558     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3559 
3560   assert(TySizeInBytes != SourceOffset && "Empty field?");
3561 
3562   // It is always safe to classify this as an integer type up to i64 that
3563   // isn't larger than the structure.
3564   return llvm::IntegerType::get(getVMContext(),
3565                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3566 }
3567 
3568 
3569 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3570 /// be used as elements of a two register pair to pass or return, return a
3571 /// first class aggregate to represent them.  For example, if the low part of
3572 /// a by-value argument should be passed as i32* and the high part as float,
3573 /// return {i32*, float}.
3574 static llvm::Type *
3575 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3576                            const llvm::DataLayout &TD) {
3577   // In order to correctly satisfy the ABI, we need to the high part to start
3578   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3579   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3580   // the second element at offset 8.  Check for this:
3581   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3582   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3583   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3584   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3585 
3586   // To handle this, we have to increase the size of the low part so that the
3587   // second element will start at an 8 byte offset.  We can't increase the size
3588   // of the second element because it might make us access off the end of the
3589   // struct.
3590   if (HiStart != 8) {
3591     // There are usually two sorts of types the ABI generation code can produce
3592     // for the low part of a pair that aren't 8 bytes in size: half, float or
3593     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3594     // NaCl).
3595     // Promote these to a larger type.
3596     if (Lo->isHalfTy() || Lo->isFloatTy())
3597       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3598     else {
3599       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3600              && "Invalid/unknown lo type");
3601       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3602     }
3603   }
3604 
3605   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3606 
3607   // Verify that the second element is at an 8-byte offset.
3608   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3609          "Invalid x86-64 argument pair!");
3610   return Result;
3611 }
3612 
3613 ABIArgInfo X86_64ABIInfo::
3614 classifyReturnType(QualType RetTy) const {
3615   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3616   // classification algorithm.
3617   X86_64ABIInfo::Class Lo, Hi;
3618   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3619 
3620   // Check some invariants.
3621   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3622   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3623 
3624   llvm::Type *ResType = nullptr;
3625   switch (Lo) {
3626   case NoClass:
3627     if (Hi == NoClass)
3628       return ABIArgInfo::getIgnore();
3629     // If the low part is just padding, it takes no register, leave ResType
3630     // null.
3631     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3632            "Unknown missing lo part");
3633     break;
3634 
3635   case SSEUp:
3636   case X87Up:
3637     llvm_unreachable("Invalid classification for lo word.");
3638 
3639     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3640     // hidden argument.
3641   case Memory:
3642     return getIndirectReturnResult(RetTy);
3643 
3644     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3645     // available register of the sequence %rax, %rdx is used.
3646   case Integer:
3647     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3648 
3649     // If we have a sign or zero extended integer, make sure to return Extend
3650     // so that the parameter gets the right LLVM IR attributes.
3651     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3652       // Treat an enum type as its underlying type.
3653       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3654         RetTy = EnumTy->getDecl()->getIntegerType();
3655 
3656       if (RetTy->isIntegralOrEnumerationType() &&
3657           isPromotableIntegerTypeForABI(RetTy))
3658         return ABIArgInfo::getExtend(RetTy);
3659     }
3660     break;
3661 
3662     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3663     // available SSE register of the sequence %xmm0, %xmm1 is used.
3664   case SSE:
3665     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3666     break;
3667 
3668     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3669     // returned on the X87 stack in %st0 as 80-bit x87 number.
3670   case X87:
3671     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3672     break;
3673 
3674     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3675     // part of the value is returned in %st0 and the imaginary part in
3676     // %st1.
3677   case ComplexX87:
3678     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3679     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3680                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3681     break;
3682   }
3683 
3684   llvm::Type *HighPart = nullptr;
3685   switch (Hi) {
3686     // Memory was handled previously and X87 should
3687     // never occur as a hi class.
3688   case Memory:
3689   case X87:
3690     llvm_unreachable("Invalid classification for hi word.");
3691 
3692   case ComplexX87: // Previously handled.
3693   case NoClass:
3694     break;
3695 
3696   case Integer:
3697     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3698     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3699       return ABIArgInfo::getDirect(HighPart, 8);
3700     break;
3701   case SSE:
3702     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3703     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3704       return ABIArgInfo::getDirect(HighPart, 8);
3705     break;
3706 
3707     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3708     // is passed in the next available eightbyte chunk if the last used
3709     // vector register.
3710     //
3711     // SSEUP should always be preceded by SSE, just widen.
3712   case SSEUp:
3713     assert(Lo == SSE && "Unexpected SSEUp classification.");
3714     ResType = GetByteVectorType(RetTy);
3715     break;
3716 
3717     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3718     // returned together with the previous X87 value in %st0.
3719   case X87Up:
3720     // If X87Up is preceded by X87, we don't need to do
3721     // anything. However, in some cases with unions it may not be
3722     // preceded by X87. In such situations we follow gcc and pass the
3723     // extra bits in an SSE reg.
3724     if (Lo != X87) {
3725       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3726       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3727         return ABIArgInfo::getDirect(HighPart, 8);
3728     }
3729     break;
3730   }
3731 
3732   // If a high part was specified, merge it together with the low part.  It is
3733   // known to pass in the high eightbyte of the result.  We do this by forming a
3734   // first class struct aggregate with the high and low part: {low, high}
3735   if (HighPart)
3736     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3737 
3738   return ABIArgInfo::getDirect(ResType);
3739 }
3740 
3741 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3742   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3743   bool isNamedArg)
3744   const
3745 {
3746   Ty = useFirstFieldIfTransparentUnion(Ty);
3747 
3748   X86_64ABIInfo::Class Lo, Hi;
3749   classify(Ty, 0, Lo, Hi, isNamedArg);
3750 
3751   // Check some invariants.
3752   // FIXME: Enforce these by construction.
3753   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3754   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3755 
3756   neededInt = 0;
3757   neededSSE = 0;
3758   llvm::Type *ResType = nullptr;
3759   switch (Lo) {
3760   case NoClass:
3761     if (Hi == NoClass)
3762       return ABIArgInfo::getIgnore();
3763     // If the low part is just padding, it takes no register, leave ResType
3764     // null.
3765     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3766            "Unknown missing lo part");
3767     break;
3768 
3769     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3770     // on the stack.
3771   case Memory:
3772 
3773     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3774     // COMPLEX_X87, it is passed in memory.
3775   case X87:
3776   case ComplexX87:
3777     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3778       ++neededInt;
3779     return getIndirectResult(Ty, freeIntRegs);
3780 
3781   case SSEUp:
3782   case X87Up:
3783     llvm_unreachable("Invalid classification for lo word.");
3784 
3785     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3786     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3787     // and %r9 is used.
3788   case Integer:
3789     ++neededInt;
3790 
3791     // Pick an 8-byte type based on the preferred type.
3792     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3793 
3794     // If we have a sign or zero extended integer, make sure to return Extend
3795     // so that the parameter gets the right LLVM IR attributes.
3796     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3797       // Treat an enum type as its underlying type.
3798       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3799         Ty = EnumTy->getDecl()->getIntegerType();
3800 
3801       if (Ty->isIntegralOrEnumerationType() &&
3802           isPromotableIntegerTypeForABI(Ty))
3803         return ABIArgInfo::getExtend(Ty);
3804     }
3805 
3806     break;
3807 
3808     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3809     // available SSE register is used, the registers are taken in the
3810     // order from %xmm0 to %xmm7.
3811   case SSE: {
3812     llvm::Type *IRType = CGT.ConvertType(Ty);
3813     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3814     ++neededSSE;
3815     break;
3816   }
3817   }
3818 
3819   llvm::Type *HighPart = nullptr;
3820   switch (Hi) {
3821     // Memory was handled previously, ComplexX87 and X87 should
3822     // never occur as hi classes, and X87Up must be preceded by X87,
3823     // which is passed in memory.
3824   case Memory:
3825   case X87:
3826   case ComplexX87:
3827     llvm_unreachable("Invalid classification for hi word.");
3828 
3829   case NoClass: break;
3830 
3831   case Integer:
3832     ++neededInt;
3833     // Pick an 8-byte type based on the preferred type.
3834     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3835 
3836     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3837       return ABIArgInfo::getDirect(HighPart, 8);
3838     break;
3839 
3840     // X87Up generally doesn't occur here (long double is passed in
3841     // memory), except in situations involving unions.
3842   case X87Up:
3843   case SSE:
3844     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3845 
3846     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3847       return ABIArgInfo::getDirect(HighPart, 8);
3848 
3849     ++neededSSE;
3850     break;
3851 
3852     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3853     // eightbyte is passed in the upper half of the last used SSE
3854     // register.  This only happens when 128-bit vectors are passed.
3855   case SSEUp:
3856     assert(Lo == SSE && "Unexpected SSEUp classification");
3857     ResType = GetByteVectorType(Ty);
3858     break;
3859   }
3860 
3861   // If a high part was specified, merge it together with the low part.  It is
3862   // known to pass in the high eightbyte of the result.  We do this by forming a
3863   // first class struct aggregate with the high and low part: {low, high}
3864   if (HighPart)
3865     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3866 
3867   return ABIArgInfo::getDirect(ResType);
3868 }
3869 
3870 ABIArgInfo
3871 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3872                                              unsigned &NeededSSE) const {
3873   auto RT = Ty->getAs<RecordType>();
3874   assert(RT && "classifyRegCallStructType only valid with struct types");
3875 
3876   if (RT->getDecl()->hasFlexibleArrayMember())
3877     return getIndirectReturnResult(Ty);
3878 
3879   // Sum up bases
3880   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3881     if (CXXRD->isDynamicClass()) {
3882       NeededInt = NeededSSE = 0;
3883       return getIndirectReturnResult(Ty);
3884     }
3885 
3886     for (const auto &I : CXXRD->bases())
3887       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3888               .isIndirect()) {
3889         NeededInt = NeededSSE = 0;
3890         return getIndirectReturnResult(Ty);
3891       }
3892   }
3893 
3894   // Sum up members
3895   for (const auto *FD : RT->getDecl()->fields()) {
3896     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3897       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3898               .isIndirect()) {
3899         NeededInt = NeededSSE = 0;
3900         return getIndirectReturnResult(Ty);
3901       }
3902     } else {
3903       unsigned LocalNeededInt, LocalNeededSSE;
3904       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3905                                LocalNeededSSE, true)
3906               .isIndirect()) {
3907         NeededInt = NeededSSE = 0;
3908         return getIndirectReturnResult(Ty);
3909       }
3910       NeededInt += LocalNeededInt;
3911       NeededSSE += LocalNeededSSE;
3912     }
3913   }
3914 
3915   return ABIArgInfo::getDirect();
3916 }
3917 
3918 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3919                                                     unsigned &NeededInt,
3920                                                     unsigned &NeededSSE) const {
3921 
3922   NeededInt = 0;
3923   NeededSSE = 0;
3924 
3925   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3926 }
3927 
3928 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3929 
3930   const unsigned CallingConv = FI.getCallingConvention();
3931   // It is possible to force Win64 calling convention on any x86_64 target by
3932   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3933   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3934   if (CallingConv == llvm::CallingConv::Win64) {
3935     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3936     Win64ABIInfo.computeInfo(FI);
3937     return;
3938   }
3939 
3940   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3941 
3942   // Keep track of the number of assigned registers.
3943   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3944   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3945   unsigned NeededInt, NeededSSE;
3946 
3947   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3948     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3949         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3950       FI.getReturnInfo() =
3951           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3952       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3953         FreeIntRegs -= NeededInt;
3954         FreeSSERegs -= NeededSSE;
3955       } else {
3956         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3957       }
3958     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3959                getContext().getCanonicalType(FI.getReturnType()
3960                                                  ->getAs<ComplexType>()
3961                                                  ->getElementType()) ==
3962                    getContext().LongDoubleTy)
3963       // Complex Long Double Type is passed in Memory when Regcall
3964       // calling convention is used.
3965       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3966     else
3967       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3968   }
3969 
3970   // If the return value is indirect, then the hidden argument is consuming one
3971   // integer register.
3972   if (FI.getReturnInfo().isIndirect())
3973     --FreeIntRegs;
3974 
3975   // The chain argument effectively gives us another free register.
3976   if (FI.isChainCall())
3977     ++FreeIntRegs;
3978 
3979   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3980   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3981   // get assigned (in left-to-right order) for passing as follows...
3982   unsigned ArgNo = 0;
3983   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3984        it != ie; ++it, ++ArgNo) {
3985     bool IsNamedArg = ArgNo < NumRequiredArgs;
3986 
3987     if (IsRegCall && it->type->isStructureOrClassType())
3988       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3989     else
3990       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3991                                       NeededSSE, IsNamedArg);
3992 
3993     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3994     // eightbyte of an argument, the whole argument is passed on the
3995     // stack. If registers have already been assigned for some
3996     // eightbytes of such an argument, the assignments get reverted.
3997     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3998       FreeIntRegs -= NeededInt;
3999       FreeSSERegs -= NeededSSE;
4000     } else {
4001       it->info = getIndirectResult(it->type, FreeIntRegs);
4002     }
4003   }
4004 }
4005 
4006 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4007                                          Address VAListAddr, QualType Ty) {
4008   Address overflow_arg_area_p =
4009       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4010   llvm::Value *overflow_arg_area =
4011     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4012 
4013   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4014   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4015   // It isn't stated explicitly in the standard, but in practice we use
4016   // alignment greater than 16 where necessary.
4017   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4018   if (Align > CharUnits::fromQuantity(8)) {
4019     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4020                                                       Align);
4021   }
4022 
4023   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4024   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4025   llvm::Value *Res =
4026     CGF.Builder.CreateBitCast(overflow_arg_area,
4027                               llvm::PointerType::getUnqual(LTy));
4028 
4029   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4030   // l->overflow_arg_area + sizeof(type).
4031   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4032   // an 8 byte boundary.
4033 
4034   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4035   llvm::Value *Offset =
4036       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4037   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4038                                             Offset, "overflow_arg_area.next");
4039   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4040 
4041   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4042   return Address(Res, LTy, Align);
4043 }
4044 
4045 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4046                                  QualType Ty) const {
4047   // Assume that va_list type is correct; should be pointer to LLVM type:
4048   // struct {
4049   //   i32 gp_offset;
4050   //   i32 fp_offset;
4051   //   i8* overflow_arg_area;
4052   //   i8* reg_save_area;
4053   // };
4054   unsigned neededInt, neededSSE;
4055 
4056   Ty = getContext().getCanonicalType(Ty);
4057   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4058                                        /*isNamedArg*/false);
4059 
4060   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4061   // in the registers. If not go to step 7.
4062   if (!neededInt && !neededSSE)
4063     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4064 
4065   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4066   // general purpose registers needed to pass type and num_fp to hold
4067   // the number of floating point registers needed.
4068 
4069   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4070   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4071   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4072   //
4073   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4074   // register save space).
4075 
4076   llvm::Value *InRegs = nullptr;
4077   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4078   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4079   if (neededInt) {
4080     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4081     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4082     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4083     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4084   }
4085 
4086   if (neededSSE) {
4087     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4088     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4089     llvm::Value *FitsInFP =
4090       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4091     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4092     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4093   }
4094 
4095   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4096   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4097   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4098   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4099 
4100   // Emit code to load the value if it was passed in registers.
4101 
4102   CGF.EmitBlock(InRegBlock);
4103 
4104   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4105   // an offset of l->gp_offset and/or l->fp_offset. This may require
4106   // copying to a temporary location in case the parameter is passed
4107   // in different register classes or requires an alignment greater
4108   // than 8 for general purpose registers and 16 for XMM registers.
4109   //
4110   // FIXME: This really results in shameful code when we end up needing to
4111   // collect arguments from different places; often what should result in a
4112   // simple assembling of a structure from scattered addresses has many more
4113   // loads than necessary. Can we clean this up?
4114   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4115   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4116       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4117 
4118   Address RegAddr = Address::invalid();
4119   if (neededInt && neededSSE) {
4120     // FIXME: Cleanup.
4121     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4122     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4123     Address Tmp = CGF.CreateMemTemp(Ty);
4124     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4125     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4126     llvm::Type *TyLo = ST->getElementType(0);
4127     llvm::Type *TyHi = ST->getElementType(1);
4128     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4129            "Unexpected ABI info for mixed regs");
4130     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4131     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4132     llvm::Value *GPAddr =
4133         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4134     llvm::Value *FPAddr =
4135         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4136     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4137     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4138 
4139     // Copy the first element.
4140     // FIXME: Our choice of alignment here and below is probably pessimistic.
4141     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4142         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4143         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4144     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4145 
4146     // Copy the second element.
4147     V = CGF.Builder.CreateAlignedLoad(
4148         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4149         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4150     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4151 
4152     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4153   } else if (neededInt) {
4154     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4155                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4156     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4157 
4158     // Copy to a temporary if necessary to ensure the appropriate alignment.
4159     auto TInfo = getContext().getTypeInfoInChars(Ty);
4160     uint64_t TySize = TInfo.Width.getQuantity();
4161     CharUnits TyAlign = TInfo.Align;
4162 
4163     // Copy into a temporary if the type is more aligned than the
4164     // register save area.
4165     if (TyAlign.getQuantity() > 8) {
4166       Address Tmp = CGF.CreateMemTemp(Ty);
4167       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4168       RegAddr = Tmp;
4169     }
4170 
4171   } else if (neededSSE == 1) {
4172     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4173                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4174     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4175   } else {
4176     assert(neededSSE == 2 && "Invalid number of needed registers!");
4177     // SSE registers are spaced 16 bytes apart in the register save
4178     // area, we need to collect the two eightbytes together.
4179     // The ABI isn't explicit about this, but it seems reasonable
4180     // to assume that the slots are 16-byte aligned, since the stack is
4181     // naturally 16-byte aligned and the prologue is expected to store
4182     // all the SSE registers to the RSA.
4183     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4184                                                       fp_offset),
4185                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4186     Address RegAddrHi =
4187       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4188                                              CharUnits::fromQuantity(16));
4189     llvm::Type *ST = AI.canHaveCoerceToType()
4190                          ? AI.getCoerceToType()
4191                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4192     llvm::Value *V;
4193     Address Tmp = CGF.CreateMemTemp(Ty);
4194     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4195     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4196         RegAddrLo, ST->getStructElementType(0)));
4197     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4198     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4199         RegAddrHi, ST->getStructElementType(1)));
4200     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4201 
4202     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4203   }
4204 
4205   // AMD64-ABI 3.5.7p5: Step 5. Set:
4206   // l->gp_offset = l->gp_offset + num_gp * 8
4207   // l->fp_offset = l->fp_offset + num_fp * 16.
4208   if (neededInt) {
4209     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4210     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4211                             gp_offset_p);
4212   }
4213   if (neededSSE) {
4214     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4215     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4216                             fp_offset_p);
4217   }
4218   CGF.EmitBranch(ContBlock);
4219 
4220   // Emit code to load the value if it was passed in memory.
4221 
4222   CGF.EmitBlock(InMemBlock);
4223   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4224 
4225   // Return the appropriate result.
4226 
4227   CGF.EmitBlock(ContBlock);
4228   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4229                                  "vaarg.addr");
4230   return ResAddr;
4231 }
4232 
4233 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4234                                    QualType Ty) const {
4235   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4236   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4237   uint64_t Width = getContext().getTypeSize(Ty);
4238   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4239 
4240   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4241                           CGF.getContext().getTypeInfoInChars(Ty),
4242                           CharUnits::fromQuantity(8),
4243                           /*allowHigherAlign*/ false);
4244 }
4245 
4246 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4247     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4248   const Type *Base = nullptr;
4249   uint64_t NumElts = 0;
4250 
4251   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4252       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4253     FreeSSERegs -= NumElts;
4254     return getDirectX86Hva();
4255   }
4256   return current;
4257 }
4258 
4259 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4260                                       bool IsReturnType, bool IsVectorCall,
4261                                       bool IsRegCall) const {
4262 
4263   if (Ty->isVoidType())
4264     return ABIArgInfo::getIgnore();
4265 
4266   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4267     Ty = EnumTy->getDecl()->getIntegerType();
4268 
4269   TypeInfo Info = getContext().getTypeInfo(Ty);
4270   uint64_t Width = Info.Width;
4271   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4272 
4273   const RecordType *RT = Ty->getAs<RecordType>();
4274   if (RT) {
4275     if (!IsReturnType) {
4276       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4277         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4278     }
4279 
4280     if (RT->getDecl()->hasFlexibleArrayMember())
4281       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4282 
4283   }
4284 
4285   const Type *Base = nullptr;
4286   uint64_t NumElts = 0;
4287   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4288   // other targets.
4289   if ((IsVectorCall || IsRegCall) &&
4290       isHomogeneousAggregate(Ty, Base, NumElts)) {
4291     if (IsRegCall) {
4292       if (FreeSSERegs >= NumElts) {
4293         FreeSSERegs -= NumElts;
4294         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4295           return ABIArgInfo::getDirect();
4296         return ABIArgInfo::getExpand();
4297       }
4298       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4299     } else if (IsVectorCall) {
4300       if (FreeSSERegs >= NumElts &&
4301           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4302         FreeSSERegs -= NumElts;
4303         return ABIArgInfo::getDirect();
4304       } else if (IsReturnType) {
4305         return ABIArgInfo::getExpand();
4306       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4307         // HVAs are delayed and reclassified in the 2nd step.
4308         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4309       }
4310     }
4311   }
4312 
4313   if (Ty->isMemberPointerType()) {
4314     // If the member pointer is represented by an LLVM int or ptr, pass it
4315     // directly.
4316     llvm::Type *LLTy = CGT.ConvertType(Ty);
4317     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4318       return ABIArgInfo::getDirect();
4319   }
4320 
4321   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4322     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4323     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4324     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4325       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4326 
4327     // Otherwise, coerce it to a small integer.
4328     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4329   }
4330 
4331   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4332     switch (BT->getKind()) {
4333     case BuiltinType::Bool:
4334       // Bool type is always extended to the ABI, other builtin types are not
4335       // extended.
4336       return ABIArgInfo::getExtend(Ty);
4337 
4338     case BuiltinType::LongDouble:
4339       // Mingw64 GCC uses the old 80 bit extended precision floating point
4340       // unit. It passes them indirectly through memory.
4341       if (IsMingw64) {
4342         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4343         if (LDF == &llvm::APFloat::x87DoubleExtended())
4344           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4345       }
4346       break;
4347 
4348     case BuiltinType::Int128:
4349     case BuiltinType::UInt128:
4350       // If it's a parameter type, the normal ABI rule is that arguments larger
4351       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4352       // even though it isn't particularly efficient.
4353       if (!IsReturnType)
4354         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4355 
4356       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4357       // Clang matches them for compatibility.
4358       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4359           llvm::Type::getInt64Ty(getVMContext()), 2));
4360 
4361     default:
4362       break;
4363     }
4364   }
4365 
4366   if (Ty->isBitIntType()) {
4367     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4368     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4369     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4370     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4371     // the power of 2.
4372     if (Width <= 64)
4373       return ABIArgInfo::getDirect();
4374     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4375   }
4376 
4377   return ABIArgInfo::getDirect();
4378 }
4379 
4380 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4381   const unsigned CC = FI.getCallingConvention();
4382   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4383   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4384 
4385   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4386   // classification rules.
4387   if (CC == llvm::CallingConv::X86_64_SysV) {
4388     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4389     SysVABIInfo.computeInfo(FI);
4390     return;
4391   }
4392 
4393   unsigned FreeSSERegs = 0;
4394   if (IsVectorCall) {
4395     // We can use up to 4 SSE return registers with vectorcall.
4396     FreeSSERegs = 4;
4397   } else if (IsRegCall) {
4398     // RegCall gives us 16 SSE registers.
4399     FreeSSERegs = 16;
4400   }
4401 
4402   if (!getCXXABI().classifyReturnType(FI))
4403     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4404                                   IsVectorCall, IsRegCall);
4405 
4406   if (IsVectorCall) {
4407     // We can use up to 6 SSE register parameters with vectorcall.
4408     FreeSSERegs = 6;
4409   } else if (IsRegCall) {
4410     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4411     FreeSSERegs = 16;
4412   }
4413 
4414   unsigned ArgNum = 0;
4415   unsigned ZeroSSERegs = 0;
4416   for (auto &I : FI.arguments()) {
4417     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4418     // XMM/YMM registers. After the sixth argument, pretend no vector
4419     // registers are left.
4420     unsigned *MaybeFreeSSERegs =
4421         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4422     I.info =
4423         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4424     ++ArgNum;
4425   }
4426 
4427   if (IsVectorCall) {
4428     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4429     // second pass.
4430     for (auto &I : FI.arguments())
4431       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4432   }
4433 }
4434 
4435 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4436                                     QualType Ty) const {
4437   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4438   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4439   uint64_t Width = getContext().getTypeSize(Ty);
4440   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4441 
4442   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4443                           CGF.getContext().getTypeInfoInChars(Ty),
4444                           CharUnits::fromQuantity(8),
4445                           /*allowHigherAlign*/ false);
4446 }
4447 
4448 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4449                                         llvm::Value *Address, bool Is64Bit,
4450                                         bool IsAIX) {
4451   // This is calculated from the LLVM and GCC tables and verified
4452   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4453 
4454   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4455 
4456   llvm::IntegerType *i8 = CGF.Int8Ty;
4457   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4458   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4459   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4460 
4461   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4462   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4463 
4464   // 32-63: fp0-31, the 8-byte floating-point registers
4465   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4466 
4467   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4468   // 64: mq
4469   // 65: lr
4470   // 66: ctr
4471   // 67: ap
4472   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4473 
4474   // 68-76 are various 4-byte special-purpose registers:
4475   // 68-75 cr0-7
4476   // 76: xer
4477   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4478 
4479   // 77-108: v0-31, the 16-byte vector registers
4480   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4481 
4482   // 109: vrsave
4483   // 110: vscr
4484   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4485 
4486   // AIX does not utilize the rest of the registers.
4487   if (IsAIX)
4488     return false;
4489 
4490   // 111: spe_acc
4491   // 112: spefscr
4492   // 113: sfp
4493   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4494 
4495   if (!Is64Bit)
4496     return false;
4497 
4498   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4499   // or above CPU.
4500   // 64-bit only registers:
4501   // 114: tfhar
4502   // 115: tfiar
4503   // 116: texasr
4504   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4505 
4506   return false;
4507 }
4508 
4509 // AIX
4510 namespace {
4511 /// AIXABIInfo - The AIX XCOFF ABI information.
4512 class AIXABIInfo : public ABIInfo {
4513   const bool Is64Bit;
4514   const unsigned PtrByteSize;
4515   CharUnits getParamTypeAlignment(QualType Ty) const;
4516 
4517 public:
4518   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4519       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4520 
4521   bool isPromotableTypeForABI(QualType Ty) const;
4522 
4523   ABIArgInfo classifyReturnType(QualType RetTy) const;
4524   ABIArgInfo classifyArgumentType(QualType Ty) const;
4525 
4526   void computeInfo(CGFunctionInfo &FI) const override {
4527     if (!getCXXABI().classifyReturnType(FI))
4528       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4529 
4530     for (auto &I : FI.arguments())
4531       I.info = classifyArgumentType(I.type);
4532   }
4533 
4534   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4535                     QualType Ty) const override;
4536 };
4537 
4538 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4539   const bool Is64Bit;
4540 
4541 public:
4542   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4543       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4544         Is64Bit(Is64Bit) {}
4545   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4546     return 1; // r1 is the dedicated stack pointer
4547   }
4548 
4549   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4550                                llvm::Value *Address) const override;
4551 };
4552 } // namespace
4553 
4554 // Return true if the ABI requires Ty to be passed sign- or zero-
4555 // extended to 32/64 bits.
4556 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4557   // Treat an enum type as its underlying type.
4558   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4559     Ty = EnumTy->getDecl()->getIntegerType();
4560 
4561   // Promotable integer types are required to be promoted by the ABI.
4562   if (Ty->isPromotableIntegerType())
4563     return true;
4564 
4565   if (!Is64Bit)
4566     return false;
4567 
4568   // For 64 bit mode, in addition to the usual promotable integer types, we also
4569   // need to extend all 32-bit types, since the ABI requires promotion to 64
4570   // bits.
4571   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4572     switch (BT->getKind()) {
4573     case BuiltinType::Int:
4574     case BuiltinType::UInt:
4575       return true;
4576     default:
4577       break;
4578     }
4579 
4580   return false;
4581 }
4582 
4583 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4584   if (RetTy->isAnyComplexType())
4585     return ABIArgInfo::getDirect();
4586 
4587   if (RetTy->isVectorType())
4588     return ABIArgInfo::getDirect();
4589 
4590   if (RetTy->isVoidType())
4591     return ABIArgInfo::getIgnore();
4592 
4593   if (isAggregateTypeForABI(RetTy))
4594     return getNaturalAlignIndirect(RetTy);
4595 
4596   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4597                                         : ABIArgInfo::getDirect());
4598 }
4599 
4600 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4601   Ty = useFirstFieldIfTransparentUnion(Ty);
4602 
4603   if (Ty->isAnyComplexType())
4604     return ABIArgInfo::getDirect();
4605 
4606   if (Ty->isVectorType())
4607     return ABIArgInfo::getDirect();
4608 
4609   if (isAggregateTypeForABI(Ty)) {
4610     // Records with non-trivial destructors/copy-constructors should not be
4611     // passed by value.
4612     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4613       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4614 
4615     CharUnits CCAlign = getParamTypeAlignment(Ty);
4616     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4617 
4618     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4619                                    /*Realign*/ TyAlign > CCAlign);
4620   }
4621 
4622   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4623                                      : ABIArgInfo::getDirect());
4624 }
4625 
4626 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4627   // Complex types are passed just like their elements.
4628   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4629     Ty = CTy->getElementType();
4630 
4631   if (Ty->isVectorType())
4632     return CharUnits::fromQuantity(16);
4633 
4634   // If the structure contains a vector type, the alignment is 16.
4635   if (isRecordWithSIMDVectorType(getContext(), Ty))
4636     return CharUnits::fromQuantity(16);
4637 
4638   return CharUnits::fromQuantity(PtrByteSize);
4639 }
4640 
4641 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4642                               QualType Ty) const {
4643 
4644   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4645   TypeInfo.Align = getParamTypeAlignment(Ty);
4646 
4647   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4648 
4649   // If we have a complex type and the base type is smaller than the register
4650   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4651   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4652   // Clang expects us to produce a pointer to a structure with the two parts
4653   // packed tightly. So generate loads of the real and imaginary parts relative
4654   // to the va_list pointer, and store them to a temporary structure. We do the
4655   // same as the PPC64ABI here.
4656   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4657     CharUnits EltSize = TypeInfo.Width / 2;
4658     if (EltSize < SlotSize)
4659       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4660   }
4661 
4662   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4663                           SlotSize, /*AllowHigher*/ true);
4664 }
4665 
4666 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4667     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4668   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4669 }
4670 
4671 // PowerPC-32
4672 namespace {
4673 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4674 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4675   bool IsSoftFloatABI;
4676   bool IsRetSmallStructInRegABI;
4677 
4678   CharUnits getParamTypeAlignment(QualType Ty) const;
4679 
4680 public:
4681   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4682                      bool RetSmallStructInRegABI)
4683       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4684         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4685 
4686   ABIArgInfo classifyReturnType(QualType RetTy) const;
4687 
4688   void computeInfo(CGFunctionInfo &FI) const override {
4689     if (!getCXXABI().classifyReturnType(FI))
4690       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4691     for (auto &I : FI.arguments())
4692       I.info = classifyArgumentType(I.type);
4693   }
4694 
4695   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4696                     QualType Ty) const override;
4697 };
4698 
4699 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4700 public:
4701   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4702                          bool RetSmallStructInRegABI)
4703       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4704             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4705 
4706   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4707                                      const CodeGenOptions &Opts);
4708 
4709   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4710     // This is recovered from gcc output.
4711     return 1; // r1 is the dedicated stack pointer
4712   }
4713 
4714   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4715                                llvm::Value *Address) const override;
4716 };
4717 }
4718 
4719 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4720   // Complex types are passed just like their elements.
4721   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4722     Ty = CTy->getElementType();
4723 
4724   if (Ty->isVectorType())
4725     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4726                                                                        : 4);
4727 
4728   // For single-element float/vector structs, we consider the whole type
4729   // to have the same alignment requirements as its single element.
4730   const Type *AlignTy = nullptr;
4731   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4732     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4733     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4734         (BT && BT->isFloatingPoint()))
4735       AlignTy = EltType;
4736   }
4737 
4738   if (AlignTy)
4739     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4740   return CharUnits::fromQuantity(4);
4741 }
4742 
4743 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4744   uint64_t Size;
4745 
4746   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4747   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4748       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4749     // System V ABI (1995), page 3-22, specified:
4750     // > A structure or union whose size is less than or equal to 8 bytes
4751     // > shall be returned in r3 and r4, as if it were first stored in the
4752     // > 8-byte aligned memory area and then the low addressed word were
4753     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4754     // > the last member of the structure or union are not defined.
4755     //
4756     // GCC for big-endian PPC32 inserts the pad before the first member,
4757     // not "beyond the last member" of the struct.  To stay compatible
4758     // with GCC, we coerce the struct to an integer of the same size.
4759     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4760     if (Size == 0)
4761       return ABIArgInfo::getIgnore();
4762     else {
4763       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4764       return ABIArgInfo::getDirect(CoerceTy);
4765     }
4766   }
4767 
4768   return DefaultABIInfo::classifyReturnType(RetTy);
4769 }
4770 
4771 // TODO: this implementation is now likely redundant with
4772 // DefaultABIInfo::EmitVAArg.
4773 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4774                                       QualType Ty) const {
4775   if (getTarget().getTriple().isOSDarwin()) {
4776     auto TI = getContext().getTypeInfoInChars(Ty);
4777     TI.Align = getParamTypeAlignment(Ty);
4778 
4779     CharUnits SlotSize = CharUnits::fromQuantity(4);
4780     return emitVoidPtrVAArg(CGF, VAList, Ty,
4781                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4782                             /*AllowHigherAlign=*/true);
4783   }
4784 
4785   const unsigned OverflowLimit = 8;
4786   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4787     // TODO: Implement this. For now ignore.
4788     (void)CTy;
4789     return Address::invalid(); // FIXME?
4790   }
4791 
4792   // struct __va_list_tag {
4793   //   unsigned char gpr;
4794   //   unsigned char fpr;
4795   //   unsigned short reserved;
4796   //   void *overflow_arg_area;
4797   //   void *reg_save_area;
4798   // };
4799 
4800   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4801   bool isInt = !Ty->isFloatingType();
4802   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4803 
4804   // All aggregates are passed indirectly?  That doesn't seem consistent
4805   // with the argument-lowering code.
4806   bool isIndirect = isAggregateTypeForABI(Ty);
4807 
4808   CGBuilderTy &Builder = CGF.Builder;
4809 
4810   // The calling convention either uses 1-2 GPRs or 1 FPR.
4811   Address NumRegsAddr = Address::invalid();
4812   if (isInt || IsSoftFloatABI) {
4813     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4814   } else {
4815     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4816   }
4817 
4818   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4819 
4820   // "Align" the register count when TY is i64.
4821   if (isI64 || (isF64 && IsSoftFloatABI)) {
4822     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4823     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4824   }
4825 
4826   llvm::Value *CC =
4827       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4828 
4829   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4830   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4831   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4832 
4833   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4834 
4835   llvm::Type *DirectTy = CGF.ConvertType(Ty), *ElementTy = DirectTy;
4836   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4837 
4838   // Case 1: consume registers.
4839   Address RegAddr = Address::invalid();
4840   {
4841     CGF.EmitBlock(UsingRegs);
4842 
4843     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4844     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CGF.Int8Ty,
4845                       CharUnits::fromQuantity(8));
4846     assert(RegAddr.getElementType() == CGF.Int8Ty);
4847 
4848     // Floating-point registers start after the general-purpose registers.
4849     if (!(isInt || IsSoftFloatABI)) {
4850       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4851                                                    CharUnits::fromQuantity(32));
4852     }
4853 
4854     // Get the address of the saved value by scaling the number of
4855     // registers we've used by the number of
4856     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4857     llvm::Value *RegOffset =
4858         Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4859     RegAddr = Address(
4860         Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
4861         CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4862     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4863 
4864     // Increase the used-register count.
4865     NumRegs =
4866       Builder.CreateAdd(NumRegs,
4867                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4868     Builder.CreateStore(NumRegs, NumRegsAddr);
4869 
4870     CGF.EmitBranch(Cont);
4871   }
4872 
4873   // Case 2: consume space in the overflow area.
4874   Address MemAddr = Address::invalid();
4875   {
4876     CGF.EmitBlock(UsingOverflow);
4877 
4878     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4879 
4880     // Everything in the overflow area is rounded up to a size of at least 4.
4881     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4882 
4883     CharUnits Size;
4884     if (!isIndirect) {
4885       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4886       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4887     } else {
4888       Size = CGF.getPointerSize();
4889     }
4890 
4891     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4892     Address OverflowArea =
4893         Address(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), CGF.Int8Ty,
4894                 OverflowAreaAlign);
4895     // Round up address of argument to alignment
4896     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4897     if (Align > OverflowAreaAlign) {
4898       llvm::Value *Ptr = OverflowArea.getPointer();
4899       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4900                              OverflowArea.getElementType(), Align);
4901     }
4902 
4903     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4904 
4905     // Increase the overflow area.
4906     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4907     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4908     CGF.EmitBranch(Cont);
4909   }
4910 
4911   CGF.EmitBlock(Cont);
4912 
4913   // Merge the cases with a phi.
4914   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4915                                 "vaarg.addr");
4916 
4917   // Load the pointer if the argument was passed indirectly.
4918   if (isIndirect) {
4919     Result = Address(Builder.CreateLoad(Result, "aggr"), ElementTy,
4920                      getContext().getTypeAlignInChars(Ty));
4921   }
4922 
4923   return Result;
4924 }
4925 
4926 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4927     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4928   assert(Triple.isPPC32());
4929 
4930   switch (Opts.getStructReturnConvention()) {
4931   case CodeGenOptions::SRCK_Default:
4932     break;
4933   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4934     return false;
4935   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4936     return true;
4937   }
4938 
4939   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4940     return true;
4941 
4942   return false;
4943 }
4944 
4945 bool
4946 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4947                                                 llvm::Value *Address) const {
4948   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4949                                      /*IsAIX*/ false);
4950 }
4951 
4952 // PowerPC-64
4953 
4954 namespace {
4955 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4956 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4957 public:
4958   enum ABIKind {
4959     ELFv1 = 0,
4960     ELFv2
4961   };
4962 
4963 private:
4964   static const unsigned GPRBits = 64;
4965   ABIKind Kind;
4966   bool IsSoftFloatABI;
4967 
4968 public:
4969   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4970                      bool SoftFloatABI)
4971       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4972 
4973   bool isPromotableTypeForABI(QualType Ty) const;
4974   CharUnits getParamTypeAlignment(QualType Ty) const;
4975 
4976   ABIArgInfo classifyReturnType(QualType RetTy) const;
4977   ABIArgInfo classifyArgumentType(QualType Ty) const;
4978 
4979   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4980   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4981                                          uint64_t Members) const override;
4982 
4983   // TODO: We can add more logic to computeInfo to improve performance.
4984   // Example: For aggregate arguments that fit in a register, we could
4985   // use getDirectInReg (as is done below for structs containing a single
4986   // floating-point value) to avoid pushing them to memory on function
4987   // entry.  This would require changing the logic in PPCISelLowering
4988   // when lowering the parameters in the caller and args in the callee.
4989   void computeInfo(CGFunctionInfo &FI) const override {
4990     if (!getCXXABI().classifyReturnType(FI))
4991       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4992     for (auto &I : FI.arguments()) {
4993       // We rely on the default argument classification for the most part.
4994       // One exception:  An aggregate containing a single floating-point
4995       // or vector item must be passed in a register if one is available.
4996       const Type *T = isSingleElementStruct(I.type, getContext());
4997       if (T) {
4998         const BuiltinType *BT = T->getAs<BuiltinType>();
4999         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
5000             (BT && BT->isFloatingPoint())) {
5001           QualType QT(T, 0);
5002           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
5003           continue;
5004         }
5005       }
5006       I.info = classifyArgumentType(I.type);
5007     }
5008   }
5009 
5010   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5011                     QualType Ty) const override;
5012 
5013   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5014                                     bool asReturnValue) const override {
5015     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5016   }
5017 
5018   bool isSwiftErrorInRegister() const override {
5019     return false;
5020   }
5021 };
5022 
5023 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5024 
5025 public:
5026   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5027                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5028                                bool SoftFloatABI)
5029       : TargetCodeGenInfo(
5030             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5031 
5032   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5033     // This is recovered from gcc output.
5034     return 1; // r1 is the dedicated stack pointer
5035   }
5036 
5037   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5038                                llvm::Value *Address) const override;
5039 };
5040 
5041 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5042 public:
5043   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5044 
5045   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5046     // This is recovered from gcc output.
5047     return 1; // r1 is the dedicated stack pointer
5048   }
5049 
5050   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5051                                llvm::Value *Address) const override;
5052 };
5053 
5054 }
5055 
5056 // Return true if the ABI requires Ty to be passed sign- or zero-
5057 // extended to 64 bits.
5058 bool
5059 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5060   // Treat an enum type as its underlying type.
5061   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5062     Ty = EnumTy->getDecl()->getIntegerType();
5063 
5064   // Promotable integer types are required to be promoted by the ABI.
5065   if (isPromotableIntegerTypeForABI(Ty))
5066     return true;
5067 
5068   // In addition to the usual promotable integer types, we also need to
5069   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5070   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5071     switch (BT->getKind()) {
5072     case BuiltinType::Int:
5073     case BuiltinType::UInt:
5074       return true;
5075     default:
5076       break;
5077     }
5078 
5079   if (const auto *EIT = Ty->getAs<BitIntType>())
5080     if (EIT->getNumBits() < 64)
5081       return true;
5082 
5083   return false;
5084 }
5085 
5086 /// isAlignedParamType - Determine whether a type requires 16-byte or
5087 /// higher alignment in the parameter area.  Always returns at least 8.
5088 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5089   // Complex types are passed just like their elements.
5090   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5091     Ty = CTy->getElementType();
5092 
5093   auto FloatUsesVector = [this](QualType Ty){
5094     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5095                                            Ty) == &llvm::APFloat::IEEEquad();
5096   };
5097 
5098   // Only vector types of size 16 bytes need alignment (larger types are
5099   // passed via reference, smaller types are not aligned).
5100   if (Ty->isVectorType()) {
5101     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5102   } else if (FloatUsesVector(Ty)) {
5103     // According to ABI document section 'Optional Save Areas': If extended
5104     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5105     // format are supported, map them to a single quadword, quadword aligned.
5106     return CharUnits::fromQuantity(16);
5107   }
5108 
5109   // For single-element float/vector structs, we consider the whole type
5110   // to have the same alignment requirements as its single element.
5111   const Type *AlignAsType = nullptr;
5112   const Type *EltType = isSingleElementStruct(Ty, getContext());
5113   if (EltType) {
5114     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5115     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5116         (BT && BT->isFloatingPoint()))
5117       AlignAsType = EltType;
5118   }
5119 
5120   // Likewise for ELFv2 homogeneous aggregates.
5121   const Type *Base = nullptr;
5122   uint64_t Members = 0;
5123   if (!AlignAsType && Kind == ELFv2 &&
5124       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5125     AlignAsType = Base;
5126 
5127   // With special case aggregates, only vector base types need alignment.
5128   if (AlignAsType) {
5129     bool UsesVector = AlignAsType->isVectorType() ||
5130                       FloatUsesVector(QualType(AlignAsType, 0));
5131     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5132   }
5133 
5134   // Otherwise, we only need alignment for any aggregate type that
5135   // has an alignment requirement of >= 16 bytes.
5136   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5137     return CharUnits::fromQuantity(16);
5138   }
5139 
5140   return CharUnits::fromQuantity(8);
5141 }
5142 
5143 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5144 /// aggregate.  Base is set to the base element type, and Members is set
5145 /// to the number of base elements.
5146 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5147                                      uint64_t &Members) const {
5148   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5149     uint64_t NElements = AT->getSize().getZExtValue();
5150     if (NElements == 0)
5151       return false;
5152     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5153       return false;
5154     Members *= NElements;
5155   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5156     const RecordDecl *RD = RT->getDecl();
5157     if (RD->hasFlexibleArrayMember())
5158       return false;
5159 
5160     Members = 0;
5161 
5162     // If this is a C++ record, check the properties of the record such as
5163     // bases and ABI specific restrictions
5164     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5165       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5166         return false;
5167 
5168       for (const auto &I : CXXRD->bases()) {
5169         // Ignore empty records.
5170         if (isEmptyRecord(getContext(), I.getType(), true))
5171           continue;
5172 
5173         uint64_t FldMembers;
5174         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5175           return false;
5176 
5177         Members += FldMembers;
5178       }
5179     }
5180 
5181     for (const auto *FD : RD->fields()) {
5182       // Ignore (non-zero arrays of) empty records.
5183       QualType FT = FD->getType();
5184       while (const ConstantArrayType *AT =
5185              getContext().getAsConstantArrayType(FT)) {
5186         if (AT->getSize().getZExtValue() == 0)
5187           return false;
5188         FT = AT->getElementType();
5189       }
5190       if (isEmptyRecord(getContext(), FT, true))
5191         continue;
5192 
5193       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5194       if (getContext().getLangOpts().CPlusPlus &&
5195           FD->isZeroLengthBitField(getContext()))
5196         continue;
5197 
5198       uint64_t FldMembers;
5199       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5200         return false;
5201 
5202       Members = (RD->isUnion() ?
5203                  std::max(Members, FldMembers) : Members + FldMembers);
5204     }
5205 
5206     if (!Base)
5207       return false;
5208 
5209     // Ensure there is no padding.
5210     if (getContext().getTypeSize(Base) * Members !=
5211         getContext().getTypeSize(Ty))
5212       return false;
5213   } else {
5214     Members = 1;
5215     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5216       Members = 2;
5217       Ty = CT->getElementType();
5218     }
5219 
5220     // Most ABIs only support float, double, and some vector type widths.
5221     if (!isHomogeneousAggregateBaseType(Ty))
5222       return false;
5223 
5224     // The base type must be the same for all members.  Types that
5225     // agree in both total size and mode (float vs. vector) are
5226     // treated as being equivalent here.
5227     const Type *TyPtr = Ty.getTypePtr();
5228     if (!Base) {
5229       Base = TyPtr;
5230       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5231       // so make sure to widen it explicitly.
5232       if (const VectorType *VT = Base->getAs<VectorType>()) {
5233         QualType EltTy = VT->getElementType();
5234         unsigned NumElements =
5235             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5236         Base = getContext()
5237                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5238                    .getTypePtr();
5239       }
5240     }
5241 
5242     if (Base->isVectorType() != TyPtr->isVectorType() ||
5243         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5244       return false;
5245   }
5246   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5247 }
5248 
5249 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5250   // Homogeneous aggregates for ELFv2 must have base types of float,
5251   // double, long double, or 128-bit vectors.
5252   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5253     if (BT->getKind() == BuiltinType::Float ||
5254         BT->getKind() == BuiltinType::Double ||
5255         BT->getKind() == BuiltinType::LongDouble ||
5256         BT->getKind() == BuiltinType::Ibm128 ||
5257         (getContext().getTargetInfo().hasFloat128Type() &&
5258          (BT->getKind() == BuiltinType::Float128))) {
5259       if (IsSoftFloatABI)
5260         return false;
5261       return true;
5262     }
5263   }
5264   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5265     if (getContext().getTypeSize(VT) == 128)
5266       return true;
5267   }
5268   return false;
5269 }
5270 
5271 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5272     const Type *Base, uint64_t Members) const {
5273   // Vector and fp128 types require one register, other floating point types
5274   // require one or two registers depending on their size.
5275   uint32_t NumRegs =
5276       ((getContext().getTargetInfo().hasFloat128Type() &&
5277           Base->isFloat128Type()) ||
5278         Base->isVectorType()) ? 1
5279                               : (getContext().getTypeSize(Base) + 63) / 64;
5280 
5281   // Homogeneous Aggregates may occupy at most 8 registers.
5282   return Members * NumRegs <= 8;
5283 }
5284 
5285 ABIArgInfo
5286 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5287   Ty = useFirstFieldIfTransparentUnion(Ty);
5288 
5289   if (Ty->isAnyComplexType())
5290     return ABIArgInfo::getDirect();
5291 
5292   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5293   // or via reference (larger than 16 bytes).
5294   if (Ty->isVectorType()) {
5295     uint64_t Size = getContext().getTypeSize(Ty);
5296     if (Size > 128)
5297       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5298     else if (Size < 128) {
5299       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5300       return ABIArgInfo::getDirect(CoerceTy);
5301     }
5302   }
5303 
5304   if (const auto *EIT = Ty->getAs<BitIntType>())
5305     if (EIT->getNumBits() > 128)
5306       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5307 
5308   if (isAggregateTypeForABI(Ty)) {
5309     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5310       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5311 
5312     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5313     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5314 
5315     // ELFv2 homogeneous aggregates are passed as array types.
5316     const Type *Base = nullptr;
5317     uint64_t Members = 0;
5318     if (Kind == ELFv2 &&
5319         isHomogeneousAggregate(Ty, Base, Members)) {
5320       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5321       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5322       return ABIArgInfo::getDirect(CoerceTy);
5323     }
5324 
5325     // If an aggregate may end up fully in registers, we do not
5326     // use the ByVal method, but pass the aggregate as array.
5327     // This is usually beneficial since we avoid forcing the
5328     // back-end to store the argument to memory.
5329     uint64_t Bits = getContext().getTypeSize(Ty);
5330     if (Bits > 0 && Bits <= 8 * GPRBits) {
5331       llvm::Type *CoerceTy;
5332 
5333       // Types up to 8 bytes are passed as integer type (which will be
5334       // properly aligned in the argument save area doubleword).
5335       if (Bits <= GPRBits)
5336         CoerceTy =
5337             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5338       // Larger types are passed as arrays, with the base type selected
5339       // according to the required alignment in the save area.
5340       else {
5341         uint64_t RegBits = ABIAlign * 8;
5342         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5343         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5344         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5345       }
5346 
5347       return ABIArgInfo::getDirect(CoerceTy);
5348     }
5349 
5350     // All other aggregates are passed ByVal.
5351     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5352                                    /*ByVal=*/true,
5353                                    /*Realign=*/TyAlign > ABIAlign);
5354   }
5355 
5356   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5357                                      : ABIArgInfo::getDirect());
5358 }
5359 
5360 ABIArgInfo
5361 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5362   if (RetTy->isVoidType())
5363     return ABIArgInfo::getIgnore();
5364 
5365   if (RetTy->isAnyComplexType())
5366     return ABIArgInfo::getDirect();
5367 
5368   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5369   // or via reference (larger than 16 bytes).
5370   if (RetTy->isVectorType()) {
5371     uint64_t Size = getContext().getTypeSize(RetTy);
5372     if (Size > 128)
5373       return getNaturalAlignIndirect(RetTy);
5374     else if (Size < 128) {
5375       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5376       return ABIArgInfo::getDirect(CoerceTy);
5377     }
5378   }
5379 
5380   if (const auto *EIT = RetTy->getAs<BitIntType>())
5381     if (EIT->getNumBits() > 128)
5382       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5383 
5384   if (isAggregateTypeForABI(RetTy)) {
5385     // ELFv2 homogeneous aggregates are returned as array types.
5386     const Type *Base = nullptr;
5387     uint64_t Members = 0;
5388     if (Kind == ELFv2 &&
5389         isHomogeneousAggregate(RetTy, Base, Members)) {
5390       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5391       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5392       return ABIArgInfo::getDirect(CoerceTy);
5393     }
5394 
5395     // ELFv2 small aggregates are returned in up to two registers.
5396     uint64_t Bits = getContext().getTypeSize(RetTy);
5397     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5398       if (Bits == 0)
5399         return ABIArgInfo::getIgnore();
5400 
5401       llvm::Type *CoerceTy;
5402       if (Bits > GPRBits) {
5403         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5404         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5405       } else
5406         CoerceTy =
5407             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5408       return ABIArgInfo::getDirect(CoerceTy);
5409     }
5410 
5411     // All other aggregates are returned indirectly.
5412     return getNaturalAlignIndirect(RetTy);
5413   }
5414 
5415   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5416                                         : ABIArgInfo::getDirect());
5417 }
5418 
5419 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5420 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5421                                       QualType Ty) const {
5422   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5423   TypeInfo.Align = getParamTypeAlignment(Ty);
5424 
5425   CharUnits SlotSize = CharUnits::fromQuantity(8);
5426 
5427   // If we have a complex type and the base type is smaller than 8 bytes,
5428   // the ABI calls for the real and imaginary parts to be right-adjusted
5429   // in separate doublewords.  However, Clang expects us to produce a
5430   // pointer to a structure with the two parts packed tightly.  So generate
5431   // loads of the real and imaginary parts relative to the va_list pointer,
5432   // and store them to a temporary structure.
5433   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5434     CharUnits EltSize = TypeInfo.Width / 2;
5435     if (EltSize < SlotSize)
5436       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5437   }
5438 
5439   // Otherwise, just use the general rule.
5440   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5441                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5442 }
5443 
5444 bool
5445 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5446   CodeGen::CodeGenFunction &CGF,
5447   llvm::Value *Address) const {
5448   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5449                                      /*IsAIX*/ false);
5450 }
5451 
5452 bool
5453 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5454                                                 llvm::Value *Address) const {
5455   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5456                                      /*IsAIX*/ false);
5457 }
5458 
5459 //===----------------------------------------------------------------------===//
5460 // AArch64 ABI Implementation
5461 //===----------------------------------------------------------------------===//
5462 
5463 namespace {
5464 
5465 class AArch64ABIInfo : public SwiftABIInfo {
5466 public:
5467   enum ABIKind {
5468     AAPCS = 0,
5469     DarwinPCS,
5470     Win64
5471   };
5472 
5473 private:
5474   ABIKind Kind;
5475 
5476 public:
5477   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5478     : SwiftABIInfo(CGT), Kind(Kind) {}
5479 
5480 private:
5481   ABIKind getABIKind() const { return Kind; }
5482   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5483 
5484   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5485   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5486                                   unsigned CallingConvention) const;
5487   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5488   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5489   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5490                                          uint64_t Members) const override;
5491 
5492   bool isIllegalVectorType(QualType Ty) const;
5493 
5494   void computeInfo(CGFunctionInfo &FI) const override {
5495     if (!::classifyReturnType(getCXXABI(), FI, *this))
5496       FI.getReturnInfo() =
5497           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5498 
5499     for (auto &it : FI.arguments())
5500       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5501                                      FI.getCallingConvention());
5502   }
5503 
5504   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5505                           CodeGenFunction &CGF) const;
5506 
5507   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5508                          CodeGenFunction &CGF) const;
5509 
5510   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5511                     QualType Ty) const override {
5512     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5513     if (isa<llvm::ScalableVectorType>(BaseTy))
5514       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5515                                "currently not supported");
5516 
5517     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5518                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5519                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5520   }
5521 
5522   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5523                       QualType Ty) const override;
5524 
5525   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5526                                     bool asReturnValue) const override {
5527     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5528   }
5529   bool isSwiftErrorInRegister() const override {
5530     return true;
5531   }
5532 
5533   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5534                                  unsigned elts) const override;
5535 
5536   bool allowBFloatArgsAndRet() const override {
5537     return getTarget().hasBFloat16Type();
5538   }
5539 };
5540 
5541 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5542 public:
5543   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5544       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5545 
5546   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5547     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5548   }
5549 
5550   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5551     return 31;
5552   }
5553 
5554   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5555 
5556   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5557                            CodeGen::CodeGenModule &CGM) const override {
5558     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5559     if (!FD)
5560       return;
5561 
5562     const auto *TA = FD->getAttr<TargetAttr>();
5563     if (TA == nullptr)
5564       return;
5565 
5566     ParsedTargetAttr Attr = TA->parse();
5567     if (Attr.BranchProtection.empty())
5568       return;
5569 
5570     TargetInfo::BranchProtectionInfo BPI;
5571     StringRef Error;
5572     (void)CGM.getTarget().validateBranchProtection(
5573         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5574     assert(Error.empty());
5575 
5576     auto *Fn = cast<llvm::Function>(GV);
5577     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5578     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5579 
5580     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5581       Fn->addFnAttr("sign-return-address-key",
5582                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5583                         ? "a_key"
5584                         : "b_key");
5585     }
5586 
5587     Fn->addFnAttr("branch-target-enforcement",
5588                   BPI.BranchTargetEnforcement ? "true" : "false");
5589   }
5590 
5591   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5592                                 llvm::Type *Ty) const override {
5593     if (CGF.getTarget().hasFeature("ls64")) {
5594       auto *ST = dyn_cast<llvm::StructType>(Ty);
5595       if (ST && ST->getNumElements() == 1) {
5596         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5597         if (AT && AT->getNumElements() == 8 &&
5598             AT->getElementType()->isIntegerTy(64))
5599           return true;
5600       }
5601     }
5602     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5603   }
5604 };
5605 
5606 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5607 public:
5608   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5609       : AArch64TargetCodeGenInfo(CGT, K) {}
5610 
5611   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5612                            CodeGen::CodeGenModule &CGM) const override;
5613 
5614   void getDependentLibraryOption(llvm::StringRef Lib,
5615                                  llvm::SmallString<24> &Opt) const override {
5616     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5617   }
5618 
5619   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5620                                llvm::SmallString<32> &Opt) const override {
5621     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5622   }
5623 };
5624 
5625 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5626     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5627   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5628   if (GV->isDeclaration())
5629     return;
5630   addStackProbeTargetAttributes(D, GV, CGM);
5631 }
5632 }
5633 
5634 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5635   assert(Ty->isVectorType() && "expected vector type!");
5636 
5637   const auto *VT = Ty->castAs<VectorType>();
5638   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5639     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5640     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5641                BuiltinType::UChar &&
5642            "unexpected builtin type for SVE predicate!");
5643     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5644         llvm::Type::getInt1Ty(getVMContext()), 16));
5645   }
5646 
5647   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5648     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5649 
5650     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5651     llvm::ScalableVectorType *ResType = nullptr;
5652     switch (BT->getKind()) {
5653     default:
5654       llvm_unreachable("unexpected builtin type for SVE vector!");
5655     case BuiltinType::SChar:
5656     case BuiltinType::UChar:
5657       ResType = llvm::ScalableVectorType::get(
5658           llvm::Type::getInt8Ty(getVMContext()), 16);
5659       break;
5660     case BuiltinType::Short:
5661     case BuiltinType::UShort:
5662       ResType = llvm::ScalableVectorType::get(
5663           llvm::Type::getInt16Ty(getVMContext()), 8);
5664       break;
5665     case BuiltinType::Int:
5666     case BuiltinType::UInt:
5667       ResType = llvm::ScalableVectorType::get(
5668           llvm::Type::getInt32Ty(getVMContext()), 4);
5669       break;
5670     case BuiltinType::Long:
5671     case BuiltinType::ULong:
5672       ResType = llvm::ScalableVectorType::get(
5673           llvm::Type::getInt64Ty(getVMContext()), 2);
5674       break;
5675     case BuiltinType::Half:
5676       ResType = llvm::ScalableVectorType::get(
5677           llvm::Type::getHalfTy(getVMContext()), 8);
5678       break;
5679     case BuiltinType::Float:
5680       ResType = llvm::ScalableVectorType::get(
5681           llvm::Type::getFloatTy(getVMContext()), 4);
5682       break;
5683     case BuiltinType::Double:
5684       ResType = llvm::ScalableVectorType::get(
5685           llvm::Type::getDoubleTy(getVMContext()), 2);
5686       break;
5687     case BuiltinType::BFloat16:
5688       ResType = llvm::ScalableVectorType::get(
5689           llvm::Type::getBFloatTy(getVMContext()), 8);
5690       break;
5691     }
5692     return ABIArgInfo::getDirect(ResType);
5693   }
5694 
5695   uint64_t Size = getContext().getTypeSize(Ty);
5696   // Android promotes <2 x i8> to i16, not i32
5697   if (isAndroid() && (Size <= 16)) {
5698     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5699     return ABIArgInfo::getDirect(ResType);
5700   }
5701   if (Size <= 32) {
5702     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5703     return ABIArgInfo::getDirect(ResType);
5704   }
5705   if (Size == 64) {
5706     auto *ResType =
5707         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5708     return ABIArgInfo::getDirect(ResType);
5709   }
5710   if (Size == 128) {
5711     auto *ResType =
5712         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5713     return ABIArgInfo::getDirect(ResType);
5714   }
5715   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5716 }
5717 
5718 ABIArgInfo
5719 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5720                                      unsigned CallingConvention) const {
5721   Ty = useFirstFieldIfTransparentUnion(Ty);
5722 
5723   // Handle illegal vector types here.
5724   if (isIllegalVectorType(Ty))
5725     return coerceIllegalVector(Ty);
5726 
5727   if (!isAggregateTypeForABI(Ty)) {
5728     // Treat an enum type as its underlying type.
5729     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5730       Ty = EnumTy->getDecl()->getIntegerType();
5731 
5732     if (const auto *EIT = Ty->getAs<BitIntType>())
5733       if (EIT->getNumBits() > 128)
5734         return getNaturalAlignIndirect(Ty);
5735 
5736     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5737                 ? ABIArgInfo::getExtend(Ty)
5738                 : ABIArgInfo::getDirect());
5739   }
5740 
5741   // Structures with either a non-trivial destructor or a non-trivial
5742   // copy constructor are always indirect.
5743   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5744     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5745                                      CGCXXABI::RAA_DirectInMemory);
5746   }
5747 
5748   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5749   // elsewhere for GNU compatibility.
5750   uint64_t Size = getContext().getTypeSize(Ty);
5751   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5752   if (IsEmpty || Size == 0) {
5753     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5754       return ABIArgInfo::getIgnore();
5755 
5756     // GNU C mode. The only argument that gets ignored is an empty one with size
5757     // 0.
5758     if (IsEmpty && Size == 0)
5759       return ABIArgInfo::getIgnore();
5760     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5761   }
5762 
5763   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5764   const Type *Base = nullptr;
5765   uint64_t Members = 0;
5766   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5767   bool IsWinVariadic = IsWin64 && IsVariadic;
5768   // In variadic functions on Windows, all composite types are treated alike,
5769   // no special handling of HFAs/HVAs.
5770   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5771     if (Kind != AArch64ABIInfo::AAPCS)
5772       return ABIArgInfo::getDirect(
5773           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5774 
5775     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5776     // default otherwise.
5777     unsigned Align =
5778         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5779     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5780     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5781     return ABIArgInfo::getDirect(
5782         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5783         nullptr, true, Align);
5784   }
5785 
5786   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5787   if (Size <= 128) {
5788     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5789     // same size and alignment.
5790     if (getTarget().isRenderScriptTarget()) {
5791       return coerceToIntArray(Ty, getContext(), getVMContext());
5792     }
5793     unsigned Alignment;
5794     if (Kind == AArch64ABIInfo::AAPCS) {
5795       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5796       Alignment = Alignment < 128 ? 64 : 128;
5797     } else {
5798       Alignment = std::max(getContext().getTypeAlign(Ty),
5799                            (unsigned)getTarget().getPointerWidth(0));
5800     }
5801     Size = llvm::alignTo(Size, Alignment);
5802 
5803     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5804     // For aggregates with 16-byte alignment, we use i128.
5805     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5806     return ABIArgInfo::getDirect(
5807         Size == Alignment ? BaseTy
5808                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5809   }
5810 
5811   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5812 }
5813 
5814 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5815                                               bool IsVariadic) const {
5816   if (RetTy->isVoidType())
5817     return ABIArgInfo::getIgnore();
5818 
5819   if (const auto *VT = RetTy->getAs<VectorType>()) {
5820     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5821         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5822       return coerceIllegalVector(RetTy);
5823   }
5824 
5825   // Large vector types should be returned via memory.
5826   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5827     return getNaturalAlignIndirect(RetTy);
5828 
5829   if (!isAggregateTypeForABI(RetTy)) {
5830     // Treat an enum type as its underlying type.
5831     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5832       RetTy = EnumTy->getDecl()->getIntegerType();
5833 
5834     if (const auto *EIT = RetTy->getAs<BitIntType>())
5835       if (EIT->getNumBits() > 128)
5836         return getNaturalAlignIndirect(RetTy);
5837 
5838     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5839                 ? ABIArgInfo::getExtend(RetTy)
5840                 : ABIArgInfo::getDirect());
5841   }
5842 
5843   uint64_t Size = getContext().getTypeSize(RetTy);
5844   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5845     return ABIArgInfo::getIgnore();
5846 
5847   const Type *Base = nullptr;
5848   uint64_t Members = 0;
5849   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5850       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5851         IsVariadic))
5852     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5853     return ABIArgInfo::getDirect();
5854 
5855   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5856   if (Size <= 128) {
5857     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5858     // same size and alignment.
5859     if (getTarget().isRenderScriptTarget()) {
5860       return coerceToIntArray(RetTy, getContext(), getVMContext());
5861     }
5862 
5863     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5864       // Composite types are returned in lower bits of a 64-bit register for LE,
5865       // and in higher bits for BE. However, integer types are always returned
5866       // in lower bits for both LE and BE, and they are not rounded up to
5867       // 64-bits. We can skip rounding up of composite types for LE, but not for
5868       // BE, otherwise composite types will be indistinguishable from integer
5869       // types.
5870       return ABIArgInfo::getDirect(
5871           llvm::IntegerType::get(getVMContext(), Size));
5872     }
5873 
5874     unsigned Alignment = getContext().getTypeAlign(RetTy);
5875     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5876 
5877     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5878     // For aggregates with 16-byte alignment, we use i128.
5879     if (Alignment < 128 && Size == 128) {
5880       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5881       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5882     }
5883     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5884   }
5885 
5886   return getNaturalAlignIndirect(RetTy);
5887 }
5888 
5889 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5890 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5891   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5892     // Check whether VT is a fixed-length SVE vector. These types are
5893     // represented as scalable vectors in function args/return and must be
5894     // coerced from fixed vectors.
5895     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5896         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5897       return true;
5898 
5899     // Check whether VT is legal.
5900     unsigned NumElements = VT->getNumElements();
5901     uint64_t Size = getContext().getTypeSize(VT);
5902     // NumElements should be power of 2.
5903     if (!llvm::isPowerOf2_32(NumElements))
5904       return true;
5905 
5906     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5907     // vectors for some reason.
5908     llvm::Triple Triple = getTarget().getTriple();
5909     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5910         Triple.isOSBinFormatMachO())
5911       return Size <= 32;
5912 
5913     return Size != 64 && (Size != 128 || NumElements == 1);
5914   }
5915   return false;
5916 }
5917 
5918 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5919                                                llvm::Type *eltTy,
5920                                                unsigned elts) const {
5921   if (!llvm::isPowerOf2_32(elts))
5922     return false;
5923   if (totalSize.getQuantity() != 8 &&
5924       (totalSize.getQuantity() != 16 || elts == 1))
5925     return false;
5926   return true;
5927 }
5928 
5929 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5930   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5931   // point type or a short-vector type. This is the same as the 32-bit ABI,
5932   // but with the difference that any floating-point type is allowed,
5933   // including __fp16.
5934   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5935     if (BT->isFloatingPoint())
5936       return true;
5937   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5938     unsigned VecSize = getContext().getTypeSize(VT);
5939     if (VecSize == 64 || VecSize == 128)
5940       return true;
5941   }
5942   return false;
5943 }
5944 
5945 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5946                                                        uint64_t Members) const {
5947   return Members <= 4;
5948 }
5949 
5950 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5951                                        CodeGenFunction &CGF) const {
5952   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5953                                        CGF.CurFnInfo->getCallingConvention());
5954   bool IsIndirect = AI.isIndirect();
5955 
5956   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5957   if (IsIndirect)
5958     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5959   else if (AI.getCoerceToType())
5960     BaseTy = AI.getCoerceToType();
5961 
5962   unsigned NumRegs = 1;
5963   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5964     BaseTy = ArrTy->getElementType();
5965     NumRegs = ArrTy->getNumElements();
5966   }
5967   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5968 
5969   // The AArch64 va_list type and handling is specified in the Procedure Call
5970   // Standard, section B.4:
5971   //
5972   // struct {
5973   //   void *__stack;
5974   //   void *__gr_top;
5975   //   void *__vr_top;
5976   //   int __gr_offs;
5977   //   int __vr_offs;
5978   // };
5979 
5980   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5981   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5982   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5983   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5984 
5985   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5986   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5987 
5988   Address reg_offs_p = Address::invalid();
5989   llvm::Value *reg_offs = nullptr;
5990   int reg_top_index;
5991   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5992   if (!IsFPR) {
5993     // 3 is the field number of __gr_offs
5994     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5995     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5996     reg_top_index = 1; // field number for __gr_top
5997     RegSize = llvm::alignTo(RegSize, 8);
5998   } else {
5999     // 4 is the field number of __vr_offs.
6000     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
6001     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
6002     reg_top_index = 2; // field number for __vr_top
6003     RegSize = 16 * NumRegs;
6004   }
6005 
6006   //=======================================
6007   // Find out where argument was passed
6008   //=======================================
6009 
6010   // If reg_offs >= 0 we're already using the stack for this type of
6011   // argument. We don't want to keep updating reg_offs (in case it overflows,
6012   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6013   // whatever they get).
6014   llvm::Value *UsingStack = nullptr;
6015   UsingStack = CGF.Builder.CreateICmpSGE(
6016       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6017 
6018   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6019 
6020   // Otherwise, at least some kind of argument could go in these registers, the
6021   // question is whether this particular type is too big.
6022   CGF.EmitBlock(MaybeRegBlock);
6023 
6024   // Integer arguments may need to correct register alignment (for example a
6025   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6026   // align __gr_offs to calculate the potential address.
6027   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6028     int Align = TyAlign.getQuantity();
6029 
6030     reg_offs = CGF.Builder.CreateAdd(
6031         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6032         "align_regoffs");
6033     reg_offs = CGF.Builder.CreateAnd(
6034         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6035         "aligned_regoffs");
6036   }
6037 
6038   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6039   // The fact that this is done unconditionally reflects the fact that
6040   // allocating an argument to the stack also uses up all the remaining
6041   // registers of the appropriate kind.
6042   llvm::Value *NewOffset = nullptr;
6043   NewOffset = CGF.Builder.CreateAdd(
6044       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6045   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6046 
6047   // Now we're in a position to decide whether this argument really was in
6048   // registers or not.
6049   llvm::Value *InRegs = nullptr;
6050   InRegs = CGF.Builder.CreateICmpSLE(
6051       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6052 
6053   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6054 
6055   //=======================================
6056   // Argument was in registers
6057   //=======================================
6058 
6059   // Now we emit the code for if the argument was originally passed in
6060   // registers. First start the appropriate block:
6061   CGF.EmitBlock(InRegBlock);
6062 
6063   llvm::Value *reg_top = nullptr;
6064   Address reg_top_p =
6065       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6066   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6067   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6068                    CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
6069   Address RegAddr = Address::invalid();
6070   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy;
6071 
6072   if (IsIndirect) {
6073     // If it's been passed indirectly (actually a struct), whatever we find from
6074     // stored registers or on the stack will actually be a struct **.
6075     MemTy = llvm::PointerType::getUnqual(MemTy);
6076   }
6077 
6078   const Type *Base = nullptr;
6079   uint64_t NumMembers = 0;
6080   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6081   if (IsHFA && NumMembers > 1) {
6082     // Homogeneous aggregates passed in registers will have their elements split
6083     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6084     // qN+1, ...). We reload and store into a temporary local variable
6085     // contiguously.
6086     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6087     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6088     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6089     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6090     Address Tmp = CGF.CreateTempAlloca(HFATy,
6091                                        std::max(TyAlign, BaseTyInfo.Align));
6092 
6093     // On big-endian platforms, the value will be right-aligned in its slot.
6094     int Offset = 0;
6095     if (CGF.CGM.getDataLayout().isBigEndian() &&
6096         BaseTyInfo.Width.getQuantity() < 16)
6097       Offset = 16 - BaseTyInfo.Width.getQuantity();
6098 
6099     for (unsigned i = 0; i < NumMembers; ++i) {
6100       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6101       Address LoadAddr =
6102         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6103       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6104 
6105       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6106 
6107       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6108       CGF.Builder.CreateStore(Elem, StoreAddr);
6109     }
6110 
6111     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6112   } else {
6113     // Otherwise the object is contiguous in memory.
6114 
6115     // It might be right-aligned in its slot.
6116     CharUnits SlotSize = BaseAddr.getAlignment();
6117     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6118         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6119         TySize < SlotSize) {
6120       CharUnits Offset = SlotSize - TySize;
6121       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6122     }
6123 
6124     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6125   }
6126 
6127   CGF.EmitBranch(ContBlock);
6128 
6129   //=======================================
6130   // Argument was on the stack
6131   //=======================================
6132   CGF.EmitBlock(OnStackBlock);
6133 
6134   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6135   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6136 
6137   // Again, stack arguments may need realignment. In this case both integer and
6138   // floating-point ones might be affected.
6139   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6140     int Align = TyAlign.getQuantity();
6141 
6142     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6143 
6144     OnStackPtr = CGF.Builder.CreateAdd(
6145         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6146         "align_stack");
6147     OnStackPtr = CGF.Builder.CreateAnd(
6148         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6149         "align_stack");
6150 
6151     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6152   }
6153   Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty,
6154                                 std::max(CharUnits::fromQuantity(8), TyAlign));
6155 
6156   // All stack slots are multiples of 8 bytes.
6157   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6158   CharUnits StackSize;
6159   if (IsIndirect)
6160     StackSize = StackSlotSize;
6161   else
6162     StackSize = TySize.alignTo(StackSlotSize);
6163 
6164   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6165   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6166       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6167 
6168   // Write the new value of __stack for the next call to va_arg
6169   CGF.Builder.CreateStore(NewStack, stack_p);
6170 
6171   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6172       TySize < StackSlotSize) {
6173     CharUnits Offset = StackSlotSize - TySize;
6174     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6175   }
6176 
6177   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6178 
6179   CGF.EmitBranch(ContBlock);
6180 
6181   //=======================================
6182   // Tidy up
6183   //=======================================
6184   CGF.EmitBlock(ContBlock);
6185 
6186   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
6187                                  OnStackBlock, "vaargs.addr");
6188 
6189   if (IsIndirect)
6190     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy,
6191                    TyAlign);
6192 
6193   return ResAddr;
6194 }
6195 
6196 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6197                                         CodeGenFunction &CGF) const {
6198   // The backend's lowering doesn't support va_arg for aggregates or
6199   // illegal vector types.  Lower VAArg here for these cases and use
6200   // the LLVM va_arg instruction for everything else.
6201   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6202     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6203 
6204   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6205   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6206 
6207   // Empty records are ignored for parameter passing purposes.
6208   if (isEmptyRecord(getContext(), Ty, true)) {
6209     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"),
6210                            getVAListElementType(CGF), SlotSize);
6211     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6212     return Addr;
6213   }
6214 
6215   // The size of the actual thing passed, which might end up just
6216   // being a pointer for indirect types.
6217   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6218 
6219   // Arguments bigger than 16 bytes which aren't homogeneous
6220   // aggregates should be passed indirectly.
6221   bool IsIndirect = false;
6222   if (TyInfo.Width.getQuantity() > 16) {
6223     const Type *Base = nullptr;
6224     uint64_t Members = 0;
6225     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6226   }
6227 
6228   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6229                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6230 }
6231 
6232 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6233                                     QualType Ty) const {
6234   bool IsIndirect = false;
6235 
6236   // Composites larger than 16 bytes are passed by reference.
6237   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6238     IsIndirect = true;
6239 
6240   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6241                           CGF.getContext().getTypeInfoInChars(Ty),
6242                           CharUnits::fromQuantity(8),
6243                           /*allowHigherAlign*/ false);
6244 }
6245 
6246 //===----------------------------------------------------------------------===//
6247 // ARM ABI Implementation
6248 //===----------------------------------------------------------------------===//
6249 
6250 namespace {
6251 
6252 class ARMABIInfo : public SwiftABIInfo {
6253 public:
6254   enum ABIKind {
6255     APCS = 0,
6256     AAPCS = 1,
6257     AAPCS_VFP = 2,
6258     AAPCS16_VFP = 3,
6259   };
6260 
6261 private:
6262   ABIKind Kind;
6263   bool IsFloatABISoftFP;
6264 
6265 public:
6266   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6267       : SwiftABIInfo(CGT), Kind(_Kind) {
6268     setCCs();
6269     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6270         CGT.getCodeGenOpts().FloatABI == ""; // default
6271   }
6272 
6273   bool isEABI() const {
6274     switch (getTarget().getTriple().getEnvironment()) {
6275     case llvm::Triple::Android:
6276     case llvm::Triple::EABI:
6277     case llvm::Triple::EABIHF:
6278     case llvm::Triple::GNUEABI:
6279     case llvm::Triple::GNUEABIHF:
6280     case llvm::Triple::MuslEABI:
6281     case llvm::Triple::MuslEABIHF:
6282       return true;
6283     default:
6284       return false;
6285     }
6286   }
6287 
6288   bool isEABIHF() const {
6289     switch (getTarget().getTriple().getEnvironment()) {
6290     case llvm::Triple::EABIHF:
6291     case llvm::Triple::GNUEABIHF:
6292     case llvm::Triple::MuslEABIHF:
6293       return true;
6294     default:
6295       return false;
6296     }
6297   }
6298 
6299   ABIKind getABIKind() const { return Kind; }
6300 
6301   bool allowBFloatArgsAndRet() const override {
6302     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6303   }
6304 
6305 private:
6306   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6307                                 unsigned functionCallConv) const;
6308   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6309                                   unsigned functionCallConv) const;
6310   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6311                                           uint64_t Members) const;
6312   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6313   bool isIllegalVectorType(QualType Ty) const;
6314   bool containsAnyFP16Vectors(QualType Ty) const;
6315 
6316   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6317   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6318                                          uint64_t Members) const override;
6319 
6320   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6321 
6322   void computeInfo(CGFunctionInfo &FI) const override;
6323 
6324   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6325                     QualType Ty) const override;
6326 
6327   llvm::CallingConv::ID getLLVMDefaultCC() const;
6328   llvm::CallingConv::ID getABIDefaultCC() const;
6329   void setCCs();
6330 
6331   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6332                                     bool asReturnValue) const override {
6333     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6334   }
6335   bool isSwiftErrorInRegister() const override {
6336     return true;
6337   }
6338   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6339                                  unsigned elts) const override;
6340 };
6341 
6342 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6343 public:
6344   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6345       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6346 
6347   const ARMABIInfo &getABIInfo() const {
6348     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6349   }
6350 
6351   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6352     return 13;
6353   }
6354 
6355   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6356     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6357   }
6358 
6359   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6360                                llvm::Value *Address) const override {
6361     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6362 
6363     // 0-15 are the 16 integer registers.
6364     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6365     return false;
6366   }
6367 
6368   unsigned getSizeOfUnwindException() const override {
6369     if (getABIInfo().isEABI()) return 88;
6370     return TargetCodeGenInfo::getSizeOfUnwindException();
6371   }
6372 
6373   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6374                            CodeGen::CodeGenModule &CGM) const override {
6375     if (GV->isDeclaration())
6376       return;
6377     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6378     if (!FD)
6379       return;
6380     auto *Fn = cast<llvm::Function>(GV);
6381 
6382     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6383       ParsedTargetAttr Attr = TA->parse();
6384       if (!Attr.BranchProtection.empty()) {
6385         TargetInfo::BranchProtectionInfo BPI;
6386         StringRef DiagMsg;
6387         StringRef Arch = Attr.Architecture.empty()
6388                              ? CGM.getTarget().getTargetOpts().CPU
6389                              : Attr.Architecture;
6390         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6391                                                       Arch, BPI, DiagMsg)) {
6392           CGM.getDiags().Report(
6393               D->getLocation(),
6394               diag::warn_target_unsupported_branch_protection_attribute)
6395               << Arch;
6396         } else {
6397           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6398           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6399                  "Unexpected SignReturnAddressScopeKind");
6400           Fn->addFnAttr(
6401               "sign-return-address",
6402               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6403 
6404           Fn->addFnAttr("branch-target-enforcement",
6405                         BPI.BranchTargetEnforcement ? "true" : "false");
6406         }
6407       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6408                  CGM.getLangOpts().hasSignReturnAddress()) {
6409         // If the Branch Protection attribute is missing, validate the target
6410         // Architecture attribute against Branch Protection command line
6411         // settings.
6412         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6413           CGM.getDiags().Report(
6414               D->getLocation(),
6415               diag::warn_target_unsupported_branch_protection_attribute)
6416               << Attr.Architecture;
6417       }
6418     }
6419 
6420     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6421     if (!Attr)
6422       return;
6423 
6424     const char *Kind;
6425     switch (Attr->getInterrupt()) {
6426     case ARMInterruptAttr::Generic: Kind = ""; break;
6427     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6428     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6429     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6430     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6431     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6432     }
6433 
6434     Fn->addFnAttr("interrupt", Kind);
6435 
6436     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6437     if (ABI == ARMABIInfo::APCS)
6438       return;
6439 
6440     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6441     // however this is not necessarily true on taking any interrupt. Instruct
6442     // the backend to perform a realignment as part of the function prologue.
6443     llvm::AttrBuilder B(Fn->getContext());
6444     B.addStackAlignmentAttr(8);
6445     Fn->addFnAttrs(B);
6446   }
6447 };
6448 
6449 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6450 public:
6451   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6452       : ARMTargetCodeGenInfo(CGT, K) {}
6453 
6454   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6455                            CodeGen::CodeGenModule &CGM) const override;
6456 
6457   void getDependentLibraryOption(llvm::StringRef Lib,
6458                                  llvm::SmallString<24> &Opt) const override {
6459     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6460   }
6461 
6462   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6463                                llvm::SmallString<32> &Opt) const override {
6464     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6465   }
6466 };
6467 
6468 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6469     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6470   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6471   if (GV->isDeclaration())
6472     return;
6473   addStackProbeTargetAttributes(D, GV, CGM);
6474 }
6475 }
6476 
6477 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6478   if (!::classifyReturnType(getCXXABI(), FI, *this))
6479     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6480                                             FI.getCallingConvention());
6481 
6482   for (auto &I : FI.arguments())
6483     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6484                                   FI.getCallingConvention());
6485 
6486 
6487   // Always honor user-specified calling convention.
6488   if (FI.getCallingConvention() != llvm::CallingConv::C)
6489     return;
6490 
6491   llvm::CallingConv::ID cc = getRuntimeCC();
6492   if (cc != llvm::CallingConv::C)
6493     FI.setEffectiveCallingConvention(cc);
6494 }
6495 
6496 /// Return the default calling convention that LLVM will use.
6497 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6498   // The default calling convention that LLVM will infer.
6499   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6500     return llvm::CallingConv::ARM_AAPCS_VFP;
6501   else if (isEABI())
6502     return llvm::CallingConv::ARM_AAPCS;
6503   else
6504     return llvm::CallingConv::ARM_APCS;
6505 }
6506 
6507 /// Return the calling convention that our ABI would like us to use
6508 /// as the C calling convention.
6509 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6510   switch (getABIKind()) {
6511   case APCS: return llvm::CallingConv::ARM_APCS;
6512   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6513   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6514   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6515   }
6516   llvm_unreachable("bad ABI kind");
6517 }
6518 
6519 void ARMABIInfo::setCCs() {
6520   assert(getRuntimeCC() == llvm::CallingConv::C);
6521 
6522   // Don't muddy up the IR with a ton of explicit annotations if
6523   // they'd just match what LLVM will infer from the triple.
6524   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6525   if (abiCC != getLLVMDefaultCC())
6526     RuntimeCC = abiCC;
6527 }
6528 
6529 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6530   uint64_t Size = getContext().getTypeSize(Ty);
6531   if (Size <= 32) {
6532     llvm::Type *ResType =
6533         llvm::Type::getInt32Ty(getVMContext());
6534     return ABIArgInfo::getDirect(ResType);
6535   }
6536   if (Size == 64 || Size == 128) {
6537     auto *ResType = llvm::FixedVectorType::get(
6538         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6539     return ABIArgInfo::getDirect(ResType);
6540   }
6541   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6542 }
6543 
6544 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6545                                                     const Type *Base,
6546                                                     uint64_t Members) const {
6547   assert(Base && "Base class should be set for homogeneous aggregate");
6548   // Base can be a floating-point or a vector.
6549   if (const VectorType *VT = Base->getAs<VectorType>()) {
6550     // FP16 vectors should be converted to integer vectors
6551     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6552       uint64_t Size = getContext().getTypeSize(VT);
6553       auto *NewVecTy = llvm::FixedVectorType::get(
6554           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6555       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6556       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6557     }
6558   }
6559   unsigned Align = 0;
6560   if (getABIKind() == ARMABIInfo::AAPCS ||
6561       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6562     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6563     // default otherwise.
6564     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6565     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6566     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6567   }
6568   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6569 }
6570 
6571 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6572                                             unsigned functionCallConv) const {
6573   // 6.1.2.1 The following argument types are VFP CPRCs:
6574   //   A single-precision floating-point type (including promoted
6575   //   half-precision types); A double-precision floating-point type;
6576   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6577   //   with a Base Type of a single- or double-precision floating-point type,
6578   //   64-bit containerized vectors or 128-bit containerized vectors with one
6579   //   to four Elements.
6580   // Variadic functions should always marshal to the base standard.
6581   bool IsAAPCS_VFP =
6582       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6583 
6584   Ty = useFirstFieldIfTransparentUnion(Ty);
6585 
6586   // Handle illegal vector types here.
6587   if (isIllegalVectorType(Ty))
6588     return coerceIllegalVector(Ty);
6589 
6590   if (!isAggregateTypeForABI(Ty)) {
6591     // Treat an enum type as its underlying type.
6592     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6593       Ty = EnumTy->getDecl()->getIntegerType();
6594     }
6595 
6596     if (const auto *EIT = Ty->getAs<BitIntType>())
6597       if (EIT->getNumBits() > 64)
6598         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6599 
6600     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6601                                               : ABIArgInfo::getDirect());
6602   }
6603 
6604   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6605     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6606   }
6607 
6608   // Ignore empty records.
6609   if (isEmptyRecord(getContext(), Ty, true))
6610     return ABIArgInfo::getIgnore();
6611 
6612   if (IsAAPCS_VFP) {
6613     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6614     // into VFP registers.
6615     const Type *Base = nullptr;
6616     uint64_t Members = 0;
6617     if (isHomogeneousAggregate(Ty, Base, Members))
6618       return classifyHomogeneousAggregate(Ty, Base, Members);
6619   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6620     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6621     // this convention even for a variadic function: the backend will use GPRs
6622     // if needed.
6623     const Type *Base = nullptr;
6624     uint64_t Members = 0;
6625     if (isHomogeneousAggregate(Ty, Base, Members)) {
6626       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6627       llvm::Type *Ty =
6628         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6629       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6630     }
6631   }
6632 
6633   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6634       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6635     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6636     // bigger than 128-bits, they get placed in space allocated by the caller,
6637     // and a pointer is passed.
6638     return ABIArgInfo::getIndirect(
6639         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6640   }
6641 
6642   // Support byval for ARM.
6643   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6644   // most 8-byte. We realign the indirect argument if type alignment is bigger
6645   // than ABI alignment.
6646   uint64_t ABIAlign = 4;
6647   uint64_t TyAlign;
6648   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6649       getABIKind() == ARMABIInfo::AAPCS) {
6650     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6651     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6652   } else {
6653     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6654   }
6655   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6656     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6657     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6658                                    /*ByVal=*/true,
6659                                    /*Realign=*/TyAlign > ABIAlign);
6660   }
6661 
6662   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6663   // same size and alignment.
6664   if (getTarget().isRenderScriptTarget()) {
6665     return coerceToIntArray(Ty, getContext(), getVMContext());
6666   }
6667 
6668   // Otherwise, pass by coercing to a structure of the appropriate size.
6669   llvm::Type* ElemTy;
6670   unsigned SizeRegs;
6671   // FIXME: Try to match the types of the arguments more accurately where
6672   // we can.
6673   if (TyAlign <= 4) {
6674     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6675     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6676   } else {
6677     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6678     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6679   }
6680 
6681   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6682 }
6683 
6684 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6685                               llvm::LLVMContext &VMContext) {
6686   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6687   // is called integer-like if its size is less than or equal to one word, and
6688   // the offset of each of its addressable sub-fields is zero.
6689 
6690   uint64_t Size = Context.getTypeSize(Ty);
6691 
6692   // Check that the type fits in a word.
6693   if (Size > 32)
6694     return false;
6695 
6696   // FIXME: Handle vector types!
6697   if (Ty->isVectorType())
6698     return false;
6699 
6700   // Float types are never treated as "integer like".
6701   if (Ty->isRealFloatingType())
6702     return false;
6703 
6704   // If this is a builtin or pointer type then it is ok.
6705   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6706     return true;
6707 
6708   // Small complex integer types are "integer like".
6709   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6710     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6711 
6712   // Single element and zero sized arrays should be allowed, by the definition
6713   // above, but they are not.
6714 
6715   // Otherwise, it must be a record type.
6716   const RecordType *RT = Ty->getAs<RecordType>();
6717   if (!RT) return false;
6718 
6719   // Ignore records with flexible arrays.
6720   const RecordDecl *RD = RT->getDecl();
6721   if (RD->hasFlexibleArrayMember())
6722     return false;
6723 
6724   // Check that all sub-fields are at offset 0, and are themselves "integer
6725   // like".
6726   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6727 
6728   bool HadField = false;
6729   unsigned idx = 0;
6730   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6731        i != e; ++i, ++idx) {
6732     const FieldDecl *FD = *i;
6733 
6734     // Bit-fields are not addressable, we only need to verify they are "integer
6735     // like". We still have to disallow a subsequent non-bitfield, for example:
6736     //   struct { int : 0; int x }
6737     // is non-integer like according to gcc.
6738     if (FD->isBitField()) {
6739       if (!RD->isUnion())
6740         HadField = true;
6741 
6742       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6743         return false;
6744 
6745       continue;
6746     }
6747 
6748     // Check if this field is at offset 0.
6749     if (Layout.getFieldOffset(idx) != 0)
6750       return false;
6751 
6752     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6753       return false;
6754 
6755     // Only allow at most one field in a structure. This doesn't match the
6756     // wording above, but follows gcc in situations with a field following an
6757     // empty structure.
6758     if (!RD->isUnion()) {
6759       if (HadField)
6760         return false;
6761 
6762       HadField = true;
6763     }
6764   }
6765 
6766   return true;
6767 }
6768 
6769 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6770                                           unsigned functionCallConv) const {
6771 
6772   // Variadic functions should always marshal to the base standard.
6773   bool IsAAPCS_VFP =
6774       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6775 
6776   if (RetTy->isVoidType())
6777     return ABIArgInfo::getIgnore();
6778 
6779   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6780     // Large vector types should be returned via memory.
6781     if (getContext().getTypeSize(RetTy) > 128)
6782       return getNaturalAlignIndirect(RetTy);
6783     // TODO: FP16/BF16 vectors should be converted to integer vectors
6784     // This check is similar  to isIllegalVectorType - refactor?
6785     if ((!getTarget().hasLegalHalfType() &&
6786         (VT->getElementType()->isFloat16Type() ||
6787          VT->getElementType()->isHalfType())) ||
6788         (IsFloatABISoftFP &&
6789          VT->getElementType()->isBFloat16Type()))
6790       return coerceIllegalVector(RetTy);
6791   }
6792 
6793   if (!isAggregateTypeForABI(RetTy)) {
6794     // Treat an enum type as its underlying type.
6795     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6796       RetTy = EnumTy->getDecl()->getIntegerType();
6797 
6798     if (const auto *EIT = RetTy->getAs<BitIntType>())
6799       if (EIT->getNumBits() > 64)
6800         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6801 
6802     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6803                                                 : ABIArgInfo::getDirect();
6804   }
6805 
6806   // Are we following APCS?
6807   if (getABIKind() == APCS) {
6808     if (isEmptyRecord(getContext(), RetTy, false))
6809       return ABIArgInfo::getIgnore();
6810 
6811     // Complex types are all returned as packed integers.
6812     //
6813     // FIXME: Consider using 2 x vector types if the back end handles them
6814     // correctly.
6815     if (RetTy->isAnyComplexType())
6816       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6817           getVMContext(), getContext().getTypeSize(RetTy)));
6818 
6819     // Integer like structures are returned in r0.
6820     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6821       // Return in the smallest viable integer type.
6822       uint64_t Size = getContext().getTypeSize(RetTy);
6823       if (Size <= 8)
6824         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6825       if (Size <= 16)
6826         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6827       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6828     }
6829 
6830     // Otherwise return in memory.
6831     return getNaturalAlignIndirect(RetTy);
6832   }
6833 
6834   // Otherwise this is an AAPCS variant.
6835 
6836   if (isEmptyRecord(getContext(), RetTy, true))
6837     return ABIArgInfo::getIgnore();
6838 
6839   // Check for homogeneous aggregates with AAPCS-VFP.
6840   if (IsAAPCS_VFP) {
6841     const Type *Base = nullptr;
6842     uint64_t Members = 0;
6843     if (isHomogeneousAggregate(RetTy, Base, Members))
6844       return classifyHomogeneousAggregate(RetTy, Base, Members);
6845   }
6846 
6847   // Aggregates <= 4 bytes are returned in r0; other aggregates
6848   // are returned indirectly.
6849   uint64_t Size = getContext().getTypeSize(RetTy);
6850   if (Size <= 32) {
6851     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6852     // same size and alignment.
6853     if (getTarget().isRenderScriptTarget()) {
6854       return coerceToIntArray(RetTy, getContext(), getVMContext());
6855     }
6856     if (getDataLayout().isBigEndian())
6857       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6858       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6859 
6860     // Return in the smallest viable integer type.
6861     if (Size <= 8)
6862       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6863     if (Size <= 16)
6864       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6865     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6866   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6867     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6868     llvm::Type *CoerceTy =
6869         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6870     return ABIArgInfo::getDirect(CoerceTy);
6871   }
6872 
6873   return getNaturalAlignIndirect(RetTy);
6874 }
6875 
6876 /// isIllegalVector - check whether Ty is an illegal vector type.
6877 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6878   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6879     // On targets that don't support half, fp16 or bfloat, they are expanded
6880     // into float, and we don't want the ABI to depend on whether or not they
6881     // are supported in hardware. Thus return false to coerce vectors of these
6882     // types into integer vectors.
6883     // We do not depend on hasLegalHalfType for bfloat as it is a
6884     // separate IR type.
6885     if ((!getTarget().hasLegalHalfType() &&
6886         (VT->getElementType()->isFloat16Type() ||
6887          VT->getElementType()->isHalfType())) ||
6888         (IsFloatABISoftFP &&
6889          VT->getElementType()->isBFloat16Type()))
6890       return true;
6891     if (isAndroid()) {
6892       // Android shipped using Clang 3.1, which supported a slightly different
6893       // vector ABI. The primary differences were that 3-element vector types
6894       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6895       // accepts that legacy behavior for Android only.
6896       // Check whether VT is legal.
6897       unsigned NumElements = VT->getNumElements();
6898       // NumElements should be power of 2 or equal to 3.
6899       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6900         return true;
6901     } else {
6902       // Check whether VT is legal.
6903       unsigned NumElements = VT->getNumElements();
6904       uint64_t Size = getContext().getTypeSize(VT);
6905       // NumElements should be power of 2.
6906       if (!llvm::isPowerOf2_32(NumElements))
6907         return true;
6908       // Size should be greater than 32 bits.
6909       return Size <= 32;
6910     }
6911   }
6912   return false;
6913 }
6914 
6915 /// Return true if a type contains any 16-bit floating point vectors
6916 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6917   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6918     uint64_t NElements = AT->getSize().getZExtValue();
6919     if (NElements == 0)
6920       return false;
6921     return containsAnyFP16Vectors(AT->getElementType());
6922   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6923     const RecordDecl *RD = RT->getDecl();
6924 
6925     // If this is a C++ record, check the bases first.
6926     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6927       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6928             return containsAnyFP16Vectors(B.getType());
6929           }))
6930         return true;
6931 
6932     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6933           return FD && containsAnyFP16Vectors(FD->getType());
6934         }))
6935       return true;
6936 
6937     return false;
6938   } else {
6939     if (const VectorType *VT = Ty->getAs<VectorType>())
6940       return (VT->getElementType()->isFloat16Type() ||
6941               VT->getElementType()->isBFloat16Type() ||
6942               VT->getElementType()->isHalfType());
6943     return false;
6944   }
6945 }
6946 
6947 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6948                                            llvm::Type *eltTy,
6949                                            unsigned numElts) const {
6950   if (!llvm::isPowerOf2_32(numElts))
6951     return false;
6952   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6953   if (size > 64)
6954     return false;
6955   if (vectorSize.getQuantity() != 8 &&
6956       (vectorSize.getQuantity() != 16 || numElts == 1))
6957     return false;
6958   return true;
6959 }
6960 
6961 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6962   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6963   // double, or 64-bit or 128-bit vectors.
6964   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6965     if (BT->getKind() == BuiltinType::Float ||
6966         BT->getKind() == BuiltinType::Double ||
6967         BT->getKind() == BuiltinType::LongDouble)
6968       return true;
6969   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6970     unsigned VecSize = getContext().getTypeSize(VT);
6971     if (VecSize == 64 || VecSize == 128)
6972       return true;
6973   }
6974   return false;
6975 }
6976 
6977 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6978                                                    uint64_t Members) const {
6979   return Members <= 4;
6980 }
6981 
6982 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6983                                         bool acceptHalf) const {
6984   // Give precedence to user-specified calling conventions.
6985   if (callConvention != llvm::CallingConv::C)
6986     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6987   else
6988     return (getABIKind() == AAPCS_VFP) ||
6989            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6990 }
6991 
6992 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6993                               QualType Ty) const {
6994   CharUnits SlotSize = CharUnits::fromQuantity(4);
6995 
6996   // Empty records are ignored for parameter passing purposes.
6997   if (isEmptyRecord(getContext(), Ty, true)) {
6998     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
6999                            getVAListElementType(CGF), SlotSize);
7000     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
7001     return Addr;
7002   }
7003 
7004   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
7005   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
7006 
7007   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7008   bool IsIndirect = false;
7009   const Type *Base = nullptr;
7010   uint64_t Members = 0;
7011   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7012     IsIndirect = true;
7013 
7014   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7015   // allocated by the caller.
7016   } else if (TySize > CharUnits::fromQuantity(16) &&
7017              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7018              !isHomogeneousAggregate(Ty, Base, Members)) {
7019     IsIndirect = true;
7020 
7021   // Otherwise, bound the type's ABI alignment.
7022   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7023   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7024   // Our callers should be prepared to handle an under-aligned address.
7025   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7026              getABIKind() == ARMABIInfo::AAPCS) {
7027     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7028     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7029   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7030     // ARMv7k allows type alignment up to 16 bytes.
7031     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7032     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7033   } else {
7034     TyAlignForABI = CharUnits::fromQuantity(4);
7035   }
7036 
7037   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7038   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7039                           SlotSize, /*AllowHigherAlign*/ true);
7040 }
7041 
7042 //===----------------------------------------------------------------------===//
7043 // NVPTX ABI Implementation
7044 //===----------------------------------------------------------------------===//
7045 
7046 namespace {
7047 
7048 class NVPTXTargetCodeGenInfo;
7049 
7050 class NVPTXABIInfo : public ABIInfo {
7051   NVPTXTargetCodeGenInfo &CGInfo;
7052 
7053 public:
7054   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7055       : ABIInfo(CGT), CGInfo(Info) {}
7056 
7057   ABIArgInfo classifyReturnType(QualType RetTy) const;
7058   ABIArgInfo classifyArgumentType(QualType Ty) const;
7059 
7060   void computeInfo(CGFunctionInfo &FI) const override;
7061   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7062                     QualType Ty) const override;
7063   bool isUnsupportedType(QualType T) const;
7064   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7065 };
7066 
7067 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7068 public:
7069   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7070       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7071 
7072   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7073                            CodeGen::CodeGenModule &M) const override;
7074   bool shouldEmitStaticExternCAliases() const override;
7075 
7076   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7077     // On the device side, surface reference is represented as an object handle
7078     // in 64-bit integer.
7079     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7080   }
7081 
7082   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7083     // On the device side, texture reference is represented as an object handle
7084     // in 64-bit integer.
7085     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7086   }
7087 
7088   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7089                                               LValue Src) const override {
7090     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7091     return true;
7092   }
7093 
7094   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7095                                               LValue Src) const override {
7096     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7097     return true;
7098   }
7099 
7100 private:
7101   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7102   // resulting MDNode to the nvvm.annotations MDNode.
7103   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7104                               int Operand);
7105 
7106   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7107                                            LValue Src) {
7108     llvm::Value *Handle = nullptr;
7109     llvm::Constant *C =
7110         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7111     // Lookup `addrspacecast` through the constant pointer if any.
7112     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7113       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7114     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7115       // Load the handle from the specific global variable using
7116       // `nvvm.texsurf.handle.internal` intrinsic.
7117       Handle = CGF.EmitRuntimeCall(
7118           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7119                                {GV->getType()}),
7120           {GV}, "texsurf_handle");
7121     } else
7122       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7123     CGF.EmitStoreOfScalar(Handle, Dst);
7124   }
7125 };
7126 
7127 /// Checks if the type is unsupported directly by the current target.
7128 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7129   ASTContext &Context = getContext();
7130   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7131     return true;
7132   if (!Context.getTargetInfo().hasFloat128Type() &&
7133       (T->isFloat128Type() ||
7134        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7135     return true;
7136   if (const auto *EIT = T->getAs<BitIntType>())
7137     return EIT->getNumBits() >
7138            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7139   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7140       Context.getTypeSize(T) > 64U)
7141     return true;
7142   if (const auto *AT = T->getAsArrayTypeUnsafe())
7143     return isUnsupportedType(AT->getElementType());
7144   const auto *RT = T->getAs<RecordType>();
7145   if (!RT)
7146     return false;
7147   const RecordDecl *RD = RT->getDecl();
7148 
7149   // If this is a C++ record, check the bases first.
7150   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7151     for (const CXXBaseSpecifier &I : CXXRD->bases())
7152       if (isUnsupportedType(I.getType()))
7153         return true;
7154 
7155   for (const FieldDecl *I : RD->fields())
7156     if (isUnsupportedType(I->getType()))
7157       return true;
7158   return false;
7159 }
7160 
7161 /// Coerce the given type into an array with maximum allowed size of elements.
7162 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7163                                                    unsigned MaxSize) const {
7164   // Alignment and Size are measured in bits.
7165   const uint64_t Size = getContext().getTypeSize(Ty);
7166   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7167   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7168   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7169   const uint64_t NumElements = (Size + Div - 1) / Div;
7170   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7171 }
7172 
7173 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7174   if (RetTy->isVoidType())
7175     return ABIArgInfo::getIgnore();
7176 
7177   if (getContext().getLangOpts().OpenMP &&
7178       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7179     return coerceToIntArrayWithLimit(RetTy, 64);
7180 
7181   // note: this is different from default ABI
7182   if (!RetTy->isScalarType())
7183     return ABIArgInfo::getDirect();
7184 
7185   // Treat an enum type as its underlying type.
7186   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7187     RetTy = EnumTy->getDecl()->getIntegerType();
7188 
7189   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7190                                                : ABIArgInfo::getDirect());
7191 }
7192 
7193 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7194   // Treat an enum type as its underlying type.
7195   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7196     Ty = EnumTy->getDecl()->getIntegerType();
7197 
7198   // Return aggregates type as indirect by value
7199   if (isAggregateTypeForABI(Ty)) {
7200     // Under CUDA device compilation, tex/surf builtin types are replaced with
7201     // object types and passed directly.
7202     if (getContext().getLangOpts().CUDAIsDevice) {
7203       if (Ty->isCUDADeviceBuiltinSurfaceType())
7204         return ABIArgInfo::getDirect(
7205             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7206       if (Ty->isCUDADeviceBuiltinTextureType())
7207         return ABIArgInfo::getDirect(
7208             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7209     }
7210     return getNaturalAlignIndirect(Ty, /* byval */ true);
7211   }
7212 
7213   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7214     if ((EIT->getNumBits() > 128) ||
7215         (!getContext().getTargetInfo().hasInt128Type() &&
7216          EIT->getNumBits() > 64))
7217       return getNaturalAlignIndirect(Ty, /* byval */ true);
7218   }
7219 
7220   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7221                                             : ABIArgInfo::getDirect());
7222 }
7223 
7224 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7225   if (!getCXXABI().classifyReturnType(FI))
7226     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7227   for (auto &I : FI.arguments())
7228     I.info = classifyArgumentType(I.type);
7229 
7230   // Always honor user-specified calling convention.
7231   if (FI.getCallingConvention() != llvm::CallingConv::C)
7232     return;
7233 
7234   FI.setEffectiveCallingConvention(getRuntimeCC());
7235 }
7236 
7237 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7238                                 QualType Ty) const {
7239   llvm_unreachable("NVPTX does not support varargs");
7240 }
7241 
7242 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7243     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7244   if (GV->isDeclaration())
7245     return;
7246   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7247   if (VD) {
7248     if (M.getLangOpts().CUDA) {
7249       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7250         addNVVMMetadata(GV, "surface", 1);
7251       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7252         addNVVMMetadata(GV, "texture", 1);
7253       return;
7254     }
7255   }
7256 
7257   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7258   if (!FD) return;
7259 
7260   llvm::Function *F = cast<llvm::Function>(GV);
7261 
7262   // Perform special handling in OpenCL mode
7263   if (M.getLangOpts().OpenCL) {
7264     // Use OpenCL function attributes to check for kernel functions
7265     // By default, all functions are device functions
7266     if (FD->hasAttr<OpenCLKernelAttr>()) {
7267       // OpenCL __kernel functions get kernel metadata
7268       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7269       addNVVMMetadata(F, "kernel", 1);
7270       // And kernel functions are not subject to inlining
7271       F->addFnAttr(llvm::Attribute::NoInline);
7272     }
7273   }
7274 
7275   // Perform special handling in CUDA mode.
7276   if (M.getLangOpts().CUDA) {
7277     // CUDA __global__ functions get a kernel metadata entry.  Since
7278     // __global__ functions cannot be called from the device, we do not
7279     // need to set the noinline attribute.
7280     if (FD->hasAttr<CUDAGlobalAttr>()) {
7281       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7282       addNVVMMetadata(F, "kernel", 1);
7283     }
7284     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7285       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7286       llvm::APSInt MaxThreads(32);
7287       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7288       if (MaxThreads > 0)
7289         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7290 
7291       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7292       // not specified in __launch_bounds__ or if the user specified a 0 value,
7293       // we don't have to add a PTX directive.
7294       if (Attr->getMinBlocks()) {
7295         llvm::APSInt MinBlocks(32);
7296         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7297         if (MinBlocks > 0)
7298           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7299           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7300       }
7301     }
7302   }
7303 }
7304 
7305 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7306                                              StringRef Name, int Operand) {
7307   llvm::Module *M = GV->getParent();
7308   llvm::LLVMContext &Ctx = M->getContext();
7309 
7310   // Get "nvvm.annotations" metadata node
7311   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7312 
7313   llvm::Metadata *MDVals[] = {
7314       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7315       llvm::ConstantAsMetadata::get(
7316           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7317   // Append metadata to nvvm.annotations
7318   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7319 }
7320 
7321 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7322   return false;
7323 }
7324 }
7325 
7326 //===----------------------------------------------------------------------===//
7327 // SystemZ ABI Implementation
7328 //===----------------------------------------------------------------------===//
7329 
7330 namespace {
7331 
7332 class SystemZABIInfo : public SwiftABIInfo {
7333   bool HasVector;
7334   bool IsSoftFloatABI;
7335 
7336 public:
7337   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7338     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7339 
7340   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7341   bool isCompoundType(QualType Ty) const;
7342   bool isVectorArgumentType(QualType Ty) const;
7343   bool isFPArgumentType(QualType Ty) const;
7344   QualType GetSingleElementType(QualType Ty) const;
7345 
7346   ABIArgInfo classifyReturnType(QualType RetTy) const;
7347   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7348 
7349   void computeInfo(CGFunctionInfo &FI) const override {
7350     if (!getCXXABI().classifyReturnType(FI))
7351       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7352     for (auto &I : FI.arguments())
7353       I.info = classifyArgumentType(I.type);
7354   }
7355 
7356   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7357                     QualType Ty) const override;
7358 
7359   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7360                                     bool asReturnValue) const override {
7361     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7362   }
7363   bool isSwiftErrorInRegister() const override {
7364     return false;
7365   }
7366 };
7367 
7368 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7369 public:
7370   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7371       : TargetCodeGenInfo(
7372             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7373 
7374   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7375                           CGBuilderTy &Builder,
7376                           CodeGenModule &CGM) const override {
7377     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7378     // Only use TDC in constrained FP mode.
7379     if (!Builder.getIsFPConstrained())
7380       return nullptr;
7381 
7382     llvm::Type *Ty = V->getType();
7383     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7384       llvm::Module &M = CGM.getModule();
7385       auto &Ctx = M.getContext();
7386       llvm::Function *TDCFunc =
7387           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7388       unsigned TDCBits = 0;
7389       switch (BuiltinID) {
7390       case Builtin::BI__builtin_isnan:
7391         TDCBits = 0xf;
7392         break;
7393       case Builtin::BIfinite:
7394       case Builtin::BI__finite:
7395       case Builtin::BIfinitef:
7396       case Builtin::BI__finitef:
7397       case Builtin::BIfinitel:
7398       case Builtin::BI__finitel:
7399       case Builtin::BI__builtin_isfinite:
7400         TDCBits = 0xfc0;
7401         break;
7402       case Builtin::BI__builtin_isinf:
7403         TDCBits = 0x30;
7404         break;
7405       default:
7406         break;
7407       }
7408       if (TDCBits)
7409         return Builder.CreateCall(
7410             TDCFunc,
7411             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7412     }
7413     return nullptr;
7414   }
7415 };
7416 }
7417 
7418 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7419   // Treat an enum type as its underlying type.
7420   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7421     Ty = EnumTy->getDecl()->getIntegerType();
7422 
7423   // Promotable integer types are required to be promoted by the ABI.
7424   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7425     return true;
7426 
7427   if (const auto *EIT = Ty->getAs<BitIntType>())
7428     if (EIT->getNumBits() < 64)
7429       return true;
7430 
7431   // 32-bit values must also be promoted.
7432   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7433     switch (BT->getKind()) {
7434     case BuiltinType::Int:
7435     case BuiltinType::UInt:
7436       return true;
7437     default:
7438       return false;
7439     }
7440   return false;
7441 }
7442 
7443 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7444   return (Ty->isAnyComplexType() ||
7445           Ty->isVectorType() ||
7446           isAggregateTypeForABI(Ty));
7447 }
7448 
7449 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7450   return (HasVector &&
7451           Ty->isVectorType() &&
7452           getContext().getTypeSize(Ty) <= 128);
7453 }
7454 
7455 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7456   if (IsSoftFloatABI)
7457     return false;
7458 
7459   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7460     switch (BT->getKind()) {
7461     case BuiltinType::Float:
7462     case BuiltinType::Double:
7463       return true;
7464     default:
7465       return false;
7466     }
7467 
7468   return false;
7469 }
7470 
7471 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7472   const RecordType *RT = Ty->getAs<RecordType>();
7473 
7474   if (RT && RT->isStructureOrClassType()) {
7475     const RecordDecl *RD = RT->getDecl();
7476     QualType Found;
7477 
7478     // If this is a C++ record, check the bases first.
7479     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7480       for (const auto &I : CXXRD->bases()) {
7481         QualType Base = I.getType();
7482 
7483         // Empty bases don't affect things either way.
7484         if (isEmptyRecord(getContext(), Base, true))
7485           continue;
7486 
7487         if (!Found.isNull())
7488           return Ty;
7489         Found = GetSingleElementType(Base);
7490       }
7491 
7492     // Check the fields.
7493     for (const auto *FD : RD->fields()) {
7494       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7495       // Unlike isSingleElementStruct(), empty structure and array fields
7496       // do count.  So do anonymous bitfields that aren't zero-sized.
7497       if (getContext().getLangOpts().CPlusPlus &&
7498           FD->isZeroLengthBitField(getContext()))
7499         continue;
7500       // Like isSingleElementStruct(), ignore C++20 empty data members.
7501       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7502           isEmptyRecord(getContext(), FD->getType(), true))
7503         continue;
7504 
7505       // Unlike isSingleElementStruct(), arrays do not count.
7506       // Nested structures still do though.
7507       if (!Found.isNull())
7508         return Ty;
7509       Found = GetSingleElementType(FD->getType());
7510     }
7511 
7512     // Unlike isSingleElementStruct(), trailing padding is allowed.
7513     // An 8-byte aligned struct s { float f; } is passed as a double.
7514     if (!Found.isNull())
7515       return Found;
7516   }
7517 
7518   return Ty;
7519 }
7520 
7521 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7522                                   QualType Ty) const {
7523   // Assume that va_list type is correct; should be pointer to LLVM type:
7524   // struct {
7525   //   i64 __gpr;
7526   //   i64 __fpr;
7527   //   i8 *__overflow_arg_area;
7528   //   i8 *__reg_save_area;
7529   // };
7530 
7531   // Every non-vector argument occupies 8 bytes and is passed by preference
7532   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7533   // always passed on the stack.
7534   Ty = getContext().getCanonicalType(Ty);
7535   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7536   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7537   llvm::Type *DirectTy = ArgTy;
7538   ABIArgInfo AI = classifyArgumentType(Ty);
7539   bool IsIndirect = AI.isIndirect();
7540   bool InFPRs = false;
7541   bool IsVector = false;
7542   CharUnits UnpaddedSize;
7543   CharUnits DirectAlign;
7544   if (IsIndirect) {
7545     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7546     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7547   } else {
7548     if (AI.getCoerceToType())
7549       ArgTy = AI.getCoerceToType();
7550     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7551     IsVector = ArgTy->isVectorTy();
7552     UnpaddedSize = TyInfo.Width;
7553     DirectAlign = TyInfo.Align;
7554   }
7555   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7556   if (IsVector && UnpaddedSize > PaddedSize)
7557     PaddedSize = CharUnits::fromQuantity(16);
7558   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7559 
7560   CharUnits Padding = (PaddedSize - UnpaddedSize);
7561 
7562   llvm::Type *IndexTy = CGF.Int64Ty;
7563   llvm::Value *PaddedSizeV =
7564     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7565 
7566   if (IsVector) {
7567     // Work out the address of a vector argument on the stack.
7568     // Vector arguments are always passed in the high bits of a
7569     // single (8 byte) or double (16 byte) stack slot.
7570     Address OverflowArgAreaPtr =
7571         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7572     Address OverflowArgArea =
7573         Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7574                 CGF.Int8Ty, TyInfo.Align);
7575     Address MemAddr =
7576         CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7577 
7578     // Update overflow_arg_area_ptr pointer
7579     llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(
7580         OverflowArgArea.getElementType(), OverflowArgArea.getPointer(),
7581         PaddedSizeV, "overflow_arg_area");
7582     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7583 
7584     return MemAddr;
7585   }
7586 
7587   assert(PaddedSize.getQuantity() == 8);
7588 
7589   unsigned MaxRegs, RegCountField, RegSaveIndex;
7590   CharUnits RegPadding;
7591   if (InFPRs) {
7592     MaxRegs = 4; // Maximum of 4 FPR arguments
7593     RegCountField = 1; // __fpr
7594     RegSaveIndex = 16; // save offset for f0
7595     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7596   } else {
7597     MaxRegs = 5; // Maximum of 5 GPR arguments
7598     RegCountField = 0; // __gpr
7599     RegSaveIndex = 2; // save offset for r2
7600     RegPadding = Padding; // values are passed in the low bits of a GPR
7601   }
7602 
7603   Address RegCountPtr =
7604       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7605   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7606   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7607   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7608                                                  "fits_in_regs");
7609 
7610   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7611   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7612   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7613   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7614 
7615   // Emit code to load the value if it was passed in registers.
7616   CGF.EmitBlock(InRegBlock);
7617 
7618   // Work out the address of an argument register.
7619   llvm::Value *ScaledRegCount =
7620     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7621   llvm::Value *RegBase =
7622     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7623                                       + RegPadding.getQuantity());
7624   llvm::Value *RegOffset =
7625     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7626   Address RegSaveAreaPtr =
7627       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7628   llvm::Value *RegSaveArea =
7629       CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7630   Address RawRegAddr(
7631       CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"),
7632       CGF.Int8Ty, PaddedSize);
7633   Address RegAddr =
7634       CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7635 
7636   // Update the register count
7637   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7638   llvm::Value *NewRegCount =
7639     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7640   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7641   CGF.EmitBranch(ContBlock);
7642 
7643   // Emit code to load the value if it was passed in memory.
7644   CGF.EmitBlock(InMemBlock);
7645 
7646   // Work out the address of a stack argument.
7647   Address OverflowArgAreaPtr =
7648       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7649   Address OverflowArgArea =
7650       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7651               CGF.Int8Ty, PaddedSize);
7652   Address RawMemAddr =
7653       CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7654   Address MemAddr =
7655     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7656 
7657   // Update overflow_arg_area_ptr pointer
7658   llvm::Value *NewOverflowArgArea =
7659     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7660                           OverflowArgArea.getPointer(), PaddedSizeV,
7661                           "overflow_arg_area");
7662   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7663   CGF.EmitBranch(ContBlock);
7664 
7665   // Return the appropriate result.
7666   CGF.EmitBlock(ContBlock);
7667   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
7668                                  "va_arg.addr");
7669 
7670   if (IsIndirect)
7671     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), ArgTy,
7672                       TyInfo.Align);
7673 
7674   return ResAddr;
7675 }
7676 
7677 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7678   if (RetTy->isVoidType())
7679     return ABIArgInfo::getIgnore();
7680   if (isVectorArgumentType(RetTy))
7681     return ABIArgInfo::getDirect();
7682   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7683     return getNaturalAlignIndirect(RetTy);
7684   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7685                                                : ABIArgInfo::getDirect());
7686 }
7687 
7688 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7689   // Handle the generic C++ ABI.
7690   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7691     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7692 
7693   // Integers and enums are extended to full register width.
7694   if (isPromotableIntegerTypeForABI(Ty))
7695     return ABIArgInfo::getExtend(Ty);
7696 
7697   // Handle vector types and vector-like structure types.  Note that
7698   // as opposed to float-like structure types, we do not allow any
7699   // padding for vector-like structures, so verify the sizes match.
7700   uint64_t Size = getContext().getTypeSize(Ty);
7701   QualType SingleElementTy = GetSingleElementType(Ty);
7702   if (isVectorArgumentType(SingleElementTy) &&
7703       getContext().getTypeSize(SingleElementTy) == Size)
7704     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7705 
7706   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7707   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7708     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7709 
7710   // Handle small structures.
7711   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7712     // Structures with flexible arrays have variable length, so really
7713     // fail the size test above.
7714     const RecordDecl *RD = RT->getDecl();
7715     if (RD->hasFlexibleArrayMember())
7716       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7717 
7718     // The structure is passed as an unextended integer, a float, or a double.
7719     llvm::Type *PassTy;
7720     if (isFPArgumentType(SingleElementTy)) {
7721       assert(Size == 32 || Size == 64);
7722       if (Size == 32)
7723         PassTy = llvm::Type::getFloatTy(getVMContext());
7724       else
7725         PassTy = llvm::Type::getDoubleTy(getVMContext());
7726     } else
7727       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7728     return ABIArgInfo::getDirect(PassTy);
7729   }
7730 
7731   // Non-structure compounds are passed indirectly.
7732   if (isCompoundType(Ty))
7733     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7734 
7735   return ABIArgInfo::getDirect(nullptr);
7736 }
7737 
7738 //===----------------------------------------------------------------------===//
7739 // MSP430 ABI Implementation
7740 //===----------------------------------------------------------------------===//
7741 
7742 namespace {
7743 
7744 class MSP430ABIInfo : public DefaultABIInfo {
7745   static ABIArgInfo complexArgInfo() {
7746     ABIArgInfo Info = ABIArgInfo::getDirect();
7747     Info.setCanBeFlattened(false);
7748     return Info;
7749   }
7750 
7751 public:
7752   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7753 
7754   ABIArgInfo classifyReturnType(QualType RetTy) const {
7755     if (RetTy->isAnyComplexType())
7756       return complexArgInfo();
7757 
7758     return DefaultABIInfo::classifyReturnType(RetTy);
7759   }
7760 
7761   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7762     if (RetTy->isAnyComplexType())
7763       return complexArgInfo();
7764 
7765     return DefaultABIInfo::classifyArgumentType(RetTy);
7766   }
7767 
7768   // Just copy the original implementations because
7769   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7770   void computeInfo(CGFunctionInfo &FI) const override {
7771     if (!getCXXABI().classifyReturnType(FI))
7772       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7773     for (auto &I : FI.arguments())
7774       I.info = classifyArgumentType(I.type);
7775   }
7776 
7777   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7778                     QualType Ty) const override {
7779     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7780   }
7781 };
7782 
7783 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7784 public:
7785   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7786       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7787   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7788                            CodeGen::CodeGenModule &M) const override;
7789 };
7790 
7791 }
7792 
7793 void MSP430TargetCodeGenInfo::setTargetAttributes(
7794     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7795   if (GV->isDeclaration())
7796     return;
7797   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7798     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7799     if (!InterruptAttr)
7800       return;
7801 
7802     // Handle 'interrupt' attribute:
7803     llvm::Function *F = cast<llvm::Function>(GV);
7804 
7805     // Step 1: Set ISR calling convention.
7806     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7807 
7808     // Step 2: Add attributes goodness.
7809     F->addFnAttr(llvm::Attribute::NoInline);
7810     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7811   }
7812 }
7813 
7814 //===----------------------------------------------------------------------===//
7815 // MIPS ABI Implementation.  This works for both little-endian and
7816 // big-endian variants.
7817 //===----------------------------------------------------------------------===//
7818 
7819 namespace {
7820 class MipsABIInfo : public ABIInfo {
7821   bool IsO32;
7822   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7823   void CoerceToIntArgs(uint64_t TySize,
7824                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7825   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7826   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7827   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7828 public:
7829   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7830     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7831     StackAlignInBytes(IsO32 ? 8 : 16) {}
7832 
7833   ABIArgInfo classifyReturnType(QualType RetTy) const;
7834   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7835   void computeInfo(CGFunctionInfo &FI) const override;
7836   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7837                     QualType Ty) const override;
7838   ABIArgInfo extendType(QualType Ty) const;
7839 };
7840 
7841 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7842   unsigned SizeOfUnwindException;
7843 public:
7844   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7845       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7846         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7847 
7848   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7849     return 29;
7850   }
7851 
7852   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7853                            CodeGen::CodeGenModule &CGM) const override {
7854     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7855     if (!FD) return;
7856     llvm::Function *Fn = cast<llvm::Function>(GV);
7857 
7858     if (FD->hasAttr<MipsLongCallAttr>())
7859       Fn->addFnAttr("long-call");
7860     else if (FD->hasAttr<MipsShortCallAttr>())
7861       Fn->addFnAttr("short-call");
7862 
7863     // Other attributes do not have a meaning for declarations.
7864     if (GV->isDeclaration())
7865       return;
7866 
7867     if (FD->hasAttr<Mips16Attr>()) {
7868       Fn->addFnAttr("mips16");
7869     }
7870     else if (FD->hasAttr<NoMips16Attr>()) {
7871       Fn->addFnAttr("nomips16");
7872     }
7873 
7874     if (FD->hasAttr<MicroMipsAttr>())
7875       Fn->addFnAttr("micromips");
7876     else if (FD->hasAttr<NoMicroMipsAttr>())
7877       Fn->addFnAttr("nomicromips");
7878 
7879     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7880     if (!Attr)
7881       return;
7882 
7883     const char *Kind;
7884     switch (Attr->getInterrupt()) {
7885     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7886     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7887     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7888     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7889     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7890     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7891     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7892     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7893     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7894     }
7895 
7896     Fn->addFnAttr("interrupt", Kind);
7897 
7898   }
7899 
7900   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7901                                llvm::Value *Address) const override;
7902 
7903   unsigned getSizeOfUnwindException() const override {
7904     return SizeOfUnwindException;
7905   }
7906 };
7907 }
7908 
7909 void MipsABIInfo::CoerceToIntArgs(
7910     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7911   llvm::IntegerType *IntTy =
7912     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7913 
7914   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7915   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7916     ArgList.push_back(IntTy);
7917 
7918   // If necessary, add one more integer type to ArgList.
7919   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7920 
7921   if (R)
7922     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7923 }
7924 
7925 // In N32/64, an aligned double precision floating point field is passed in
7926 // a register.
7927 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7928   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7929 
7930   if (IsO32) {
7931     CoerceToIntArgs(TySize, ArgList);
7932     return llvm::StructType::get(getVMContext(), ArgList);
7933   }
7934 
7935   if (Ty->isComplexType())
7936     return CGT.ConvertType(Ty);
7937 
7938   const RecordType *RT = Ty->getAs<RecordType>();
7939 
7940   // Unions/vectors are passed in integer registers.
7941   if (!RT || !RT->isStructureOrClassType()) {
7942     CoerceToIntArgs(TySize, ArgList);
7943     return llvm::StructType::get(getVMContext(), ArgList);
7944   }
7945 
7946   const RecordDecl *RD = RT->getDecl();
7947   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7948   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7949 
7950   uint64_t LastOffset = 0;
7951   unsigned idx = 0;
7952   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7953 
7954   // Iterate over fields in the struct/class and check if there are any aligned
7955   // double fields.
7956   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7957        i != e; ++i, ++idx) {
7958     const QualType Ty = i->getType();
7959     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7960 
7961     if (!BT || BT->getKind() != BuiltinType::Double)
7962       continue;
7963 
7964     uint64_t Offset = Layout.getFieldOffset(idx);
7965     if (Offset % 64) // Ignore doubles that are not aligned.
7966       continue;
7967 
7968     // Add ((Offset - LastOffset) / 64) args of type i64.
7969     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7970       ArgList.push_back(I64);
7971 
7972     // Add double type.
7973     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7974     LastOffset = Offset + 64;
7975   }
7976 
7977   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7978   ArgList.append(IntArgList.begin(), IntArgList.end());
7979 
7980   return llvm::StructType::get(getVMContext(), ArgList);
7981 }
7982 
7983 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7984                                         uint64_t Offset) const {
7985   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7986     return nullptr;
7987 
7988   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7989 }
7990 
7991 ABIArgInfo
7992 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7993   Ty = useFirstFieldIfTransparentUnion(Ty);
7994 
7995   uint64_t OrigOffset = Offset;
7996   uint64_t TySize = getContext().getTypeSize(Ty);
7997   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7998 
7999   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
8000                    (uint64_t)StackAlignInBytes);
8001   unsigned CurrOffset = llvm::alignTo(Offset, Align);
8002   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
8003 
8004   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
8005     // Ignore empty aggregates.
8006     if (TySize == 0)
8007       return ABIArgInfo::getIgnore();
8008 
8009     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8010       Offset = OrigOffset + MinABIStackAlignInBytes;
8011       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8012     }
8013 
8014     // If we have reached here, aggregates are passed directly by coercing to
8015     // another structure type. Padding is inserted if the offset of the
8016     // aggregate is unaligned.
8017     ABIArgInfo ArgInfo =
8018         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8019                               getPaddingType(OrigOffset, CurrOffset));
8020     ArgInfo.setInReg(true);
8021     return ArgInfo;
8022   }
8023 
8024   // Treat an enum type as its underlying type.
8025   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8026     Ty = EnumTy->getDecl()->getIntegerType();
8027 
8028   // Make sure we pass indirectly things that are too large.
8029   if (const auto *EIT = Ty->getAs<BitIntType>())
8030     if (EIT->getNumBits() > 128 ||
8031         (EIT->getNumBits() > 64 &&
8032          !getContext().getTargetInfo().hasInt128Type()))
8033       return getNaturalAlignIndirect(Ty);
8034 
8035   // All integral types are promoted to the GPR width.
8036   if (Ty->isIntegralOrEnumerationType())
8037     return extendType(Ty);
8038 
8039   return ABIArgInfo::getDirect(
8040       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8041 }
8042 
8043 llvm::Type*
8044 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8045   const RecordType *RT = RetTy->getAs<RecordType>();
8046   SmallVector<llvm::Type*, 8> RTList;
8047 
8048   if (RT && RT->isStructureOrClassType()) {
8049     const RecordDecl *RD = RT->getDecl();
8050     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8051     unsigned FieldCnt = Layout.getFieldCount();
8052 
8053     // N32/64 returns struct/classes in floating point registers if the
8054     // following conditions are met:
8055     // 1. The size of the struct/class is no larger than 128-bit.
8056     // 2. The struct/class has one or two fields all of which are floating
8057     //    point types.
8058     // 3. The offset of the first field is zero (this follows what gcc does).
8059     //
8060     // Any other composite results are returned in integer registers.
8061     //
8062     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8063       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8064       for (; b != e; ++b) {
8065         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8066 
8067         if (!BT || !BT->isFloatingPoint())
8068           break;
8069 
8070         RTList.push_back(CGT.ConvertType(b->getType()));
8071       }
8072 
8073       if (b == e)
8074         return llvm::StructType::get(getVMContext(), RTList,
8075                                      RD->hasAttr<PackedAttr>());
8076 
8077       RTList.clear();
8078     }
8079   }
8080 
8081   CoerceToIntArgs(Size, RTList);
8082   return llvm::StructType::get(getVMContext(), RTList);
8083 }
8084 
8085 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8086   uint64_t Size = getContext().getTypeSize(RetTy);
8087 
8088   if (RetTy->isVoidType())
8089     return ABIArgInfo::getIgnore();
8090 
8091   // O32 doesn't treat zero-sized structs differently from other structs.
8092   // However, N32/N64 ignores zero sized return values.
8093   if (!IsO32 && Size == 0)
8094     return ABIArgInfo::getIgnore();
8095 
8096   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8097     if (Size <= 128) {
8098       if (RetTy->isAnyComplexType())
8099         return ABIArgInfo::getDirect();
8100 
8101       // O32 returns integer vectors in registers and N32/N64 returns all small
8102       // aggregates in registers.
8103       if (!IsO32 ||
8104           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8105         ABIArgInfo ArgInfo =
8106             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8107         ArgInfo.setInReg(true);
8108         return ArgInfo;
8109       }
8110     }
8111 
8112     return getNaturalAlignIndirect(RetTy);
8113   }
8114 
8115   // Treat an enum type as its underlying type.
8116   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8117     RetTy = EnumTy->getDecl()->getIntegerType();
8118 
8119   // Make sure we pass indirectly things that are too large.
8120   if (const auto *EIT = RetTy->getAs<BitIntType>())
8121     if (EIT->getNumBits() > 128 ||
8122         (EIT->getNumBits() > 64 &&
8123          !getContext().getTargetInfo().hasInt128Type()))
8124       return getNaturalAlignIndirect(RetTy);
8125 
8126   if (isPromotableIntegerTypeForABI(RetTy))
8127     return ABIArgInfo::getExtend(RetTy);
8128 
8129   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8130       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8131     return ABIArgInfo::getSignExtend(RetTy);
8132 
8133   return ABIArgInfo::getDirect();
8134 }
8135 
8136 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8137   ABIArgInfo &RetInfo = FI.getReturnInfo();
8138   if (!getCXXABI().classifyReturnType(FI))
8139     RetInfo = classifyReturnType(FI.getReturnType());
8140 
8141   // Check if a pointer to an aggregate is passed as a hidden argument.
8142   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8143 
8144   for (auto &I : FI.arguments())
8145     I.info = classifyArgumentType(I.type, Offset);
8146 }
8147 
8148 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8149                                QualType OrigTy) const {
8150   QualType Ty = OrigTy;
8151 
8152   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8153   // Pointers are also promoted in the same way but this only matters for N32.
8154   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8155   unsigned PtrWidth = getTarget().getPointerWidth(0);
8156   bool DidPromote = false;
8157   if ((Ty->isIntegerType() &&
8158           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8159       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8160     DidPromote = true;
8161     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8162                                             Ty->isSignedIntegerType());
8163   }
8164 
8165   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8166 
8167   // The alignment of things in the argument area is never larger than
8168   // StackAlignInBytes.
8169   TyInfo.Align =
8170     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8171 
8172   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8173   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8174 
8175   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8176                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8177 
8178 
8179   // If there was a promotion, "unpromote" into a temporary.
8180   // TODO: can we just use a pointer into a subset of the original slot?
8181   if (DidPromote) {
8182     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8183     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8184 
8185     // Truncate down to the right width.
8186     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8187                                                  : CGF.IntPtrTy);
8188     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8189     if (OrigTy->isPointerType())
8190       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8191 
8192     CGF.Builder.CreateStore(V, Temp);
8193     Addr = Temp;
8194   }
8195 
8196   return Addr;
8197 }
8198 
8199 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8200   int TySize = getContext().getTypeSize(Ty);
8201 
8202   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8203   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8204     return ABIArgInfo::getSignExtend(Ty);
8205 
8206   return ABIArgInfo::getExtend(Ty);
8207 }
8208 
8209 bool
8210 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8211                                                llvm::Value *Address) const {
8212   // This information comes from gcc's implementation, which seems to
8213   // as canonical as it gets.
8214 
8215   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8216   // are aliased to pairs of single-precision FP registers.
8217   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8218 
8219   // 0-31 are the general purpose registers, $0 - $31.
8220   // 32-63 are the floating-point registers, $f0 - $f31.
8221   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8222   // 66 is the (notional, I think) register for signal-handler return.
8223   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8224 
8225   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8226   // They are one bit wide and ignored here.
8227 
8228   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8229   // (coprocessor 1 is the FP unit)
8230   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8231   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8232   // 176-181 are the DSP accumulator registers.
8233   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8234   return false;
8235 }
8236 
8237 //===----------------------------------------------------------------------===//
8238 // M68k ABI Implementation
8239 //===----------------------------------------------------------------------===//
8240 
8241 namespace {
8242 
8243 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8244 public:
8245   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8246       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8247   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8248                            CodeGen::CodeGenModule &M) const override;
8249 };
8250 
8251 } // namespace
8252 
8253 void M68kTargetCodeGenInfo::setTargetAttributes(
8254     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8255   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8256     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8257       // Handle 'interrupt' attribute:
8258       llvm::Function *F = cast<llvm::Function>(GV);
8259 
8260       // Step 1: Set ISR calling convention.
8261       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8262 
8263       // Step 2: Add attributes goodness.
8264       F->addFnAttr(llvm::Attribute::NoInline);
8265 
8266       // Step 3: Emit ISR vector alias.
8267       unsigned Num = attr->getNumber() / 2;
8268       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8269                                 "__isr_" + Twine(Num), F);
8270     }
8271   }
8272 }
8273 
8274 //===----------------------------------------------------------------------===//
8275 // AVR ABI Implementation. Documented at
8276 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8277 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8278 //===----------------------------------------------------------------------===//
8279 
8280 namespace {
8281 class AVRABIInfo : public DefaultABIInfo {
8282 private:
8283   // The total amount of registers can be used to pass parameters. It is 18 on
8284   // AVR, or 6 on AVRTiny.
8285   const unsigned ParamRegs;
8286   // The total amount of registers can be used to pass return value. It is 8 on
8287   // AVR, or 4 on AVRTiny.
8288   const unsigned RetRegs;
8289 
8290 public:
8291   AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8292       : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {}
8293 
8294   ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const {
8295     if (isAggregateTypeForABI(Ty)) {
8296       // On AVR, a return struct with size less than or equals to 8 bytes is
8297       // returned directly via registers R18-R25. On AVRTiny, a return struct
8298       // with size less than or equals to 4 bytes is returned directly via
8299       // registers R22-R25.
8300       if (getContext().getTypeSize(Ty) <= RetRegs * 8)
8301         return ABIArgInfo::getDirect();
8302       // A return struct with larger size is returned via a stack
8303       // slot, along with a pointer to it as the function's implicit argument.
8304       LargeRet = true;
8305       return getNaturalAlignIndirect(Ty);
8306     }
8307     // Otherwise we follow the default way which is compatible.
8308     return DefaultABIInfo::classifyReturnType(Ty);
8309   }
8310 
8311   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const {
8312     unsigned TySize = getContext().getTypeSize(Ty);
8313 
8314     // An int8 type argument always costs two registers like an int16.
8315     if (TySize == 8 && NumRegs >= 2) {
8316       NumRegs -= 2;
8317       return ABIArgInfo::getExtend(Ty);
8318     }
8319 
8320     // If the argument size is an odd number of bytes, round up the size
8321     // to the next even number.
8322     TySize = llvm::alignTo(TySize, 16);
8323 
8324     // Any type including an array/struct type can be passed in rgisters,
8325     // if there are enough registers left.
8326     if (TySize <= NumRegs * 8) {
8327       NumRegs -= TySize / 8;
8328       return ABIArgInfo::getDirect();
8329     }
8330 
8331     // An argument is passed either completely in registers or completely in
8332     // memory. Since there are not enough registers left, current argument
8333     // and all other unprocessed arguments should be passed in memory.
8334     // However we still need to return `ABIArgInfo::getDirect()` other than
8335     // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot
8336     // will be allocated, so the stack frame layout will be incompatible with
8337     // avr-gcc.
8338     NumRegs = 0;
8339     return ABIArgInfo::getDirect();
8340   }
8341 
8342   void computeInfo(CGFunctionInfo &FI) const override {
8343     // Decide the return type.
8344     bool LargeRet = false;
8345     if (!getCXXABI().classifyReturnType(FI))
8346       FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet);
8347 
8348     // Decide each argument type. The total number of registers can be used for
8349     // arguments depends on several factors:
8350     // 1. Arguments of varargs functions are passed on the stack. This applies
8351     //    even to the named arguments. So no register can be used.
8352     // 2. Total 18 registers can be used on avr and 6 ones on avrtiny.
8353     // 3. If the return type is a struct with too large size, two registers
8354     //    (out of 18/6) will be cost as an implicit pointer argument.
8355     unsigned NumRegs = ParamRegs;
8356     if (FI.isVariadic())
8357       NumRegs = 0;
8358     else if (LargeRet)
8359       NumRegs -= 2;
8360     for (auto &I : FI.arguments())
8361       I.info = classifyArgumentType(I.type, NumRegs);
8362   }
8363 };
8364 
8365 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8366 public:
8367   AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8368       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {}
8369 
8370   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8371                                   const VarDecl *D) const override {
8372     // Check if global/static variable is defined in address space
8373     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8374     // but not constant.
8375     if (D) {
8376       LangAS AS = D->getType().getAddressSpace();
8377       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8378           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8379         CGM.getDiags().Report(D->getLocation(),
8380                               diag::err_verify_nonconst_addrspace)
8381             << "__flash*";
8382     }
8383     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8384   }
8385 
8386   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8387                            CodeGen::CodeGenModule &CGM) const override {
8388     if (GV->isDeclaration())
8389       return;
8390     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8391     if (!FD) return;
8392     auto *Fn = cast<llvm::Function>(GV);
8393 
8394     if (FD->getAttr<AVRInterruptAttr>())
8395       Fn->addFnAttr("interrupt");
8396 
8397     if (FD->getAttr<AVRSignalAttr>())
8398       Fn->addFnAttr("signal");
8399   }
8400 };
8401 }
8402 
8403 //===----------------------------------------------------------------------===//
8404 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8405 // Currently subclassed only to implement custom OpenCL C function attribute
8406 // handling.
8407 //===----------------------------------------------------------------------===//
8408 
8409 namespace {
8410 
8411 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8412 public:
8413   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8414     : DefaultTargetCodeGenInfo(CGT) {}
8415 
8416   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8417                            CodeGen::CodeGenModule &M) const override;
8418 };
8419 
8420 void TCETargetCodeGenInfo::setTargetAttributes(
8421     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8422   if (GV->isDeclaration())
8423     return;
8424   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8425   if (!FD) return;
8426 
8427   llvm::Function *F = cast<llvm::Function>(GV);
8428 
8429   if (M.getLangOpts().OpenCL) {
8430     if (FD->hasAttr<OpenCLKernelAttr>()) {
8431       // OpenCL C Kernel functions are not subject to inlining
8432       F->addFnAttr(llvm::Attribute::NoInline);
8433       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8434       if (Attr) {
8435         // Convert the reqd_work_group_size() attributes to metadata.
8436         llvm::LLVMContext &Context = F->getContext();
8437         llvm::NamedMDNode *OpenCLMetadata =
8438             M.getModule().getOrInsertNamedMetadata(
8439                 "opencl.kernel_wg_size_info");
8440 
8441         SmallVector<llvm::Metadata *, 5> Operands;
8442         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8443 
8444         Operands.push_back(
8445             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8446                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8447         Operands.push_back(
8448             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8449                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8450         Operands.push_back(
8451             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8452                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8453 
8454         // Add a boolean constant operand for "required" (true) or "hint"
8455         // (false) for implementing the work_group_size_hint attr later.
8456         // Currently always true as the hint is not yet implemented.
8457         Operands.push_back(
8458             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8459         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8460       }
8461     }
8462   }
8463 }
8464 
8465 }
8466 
8467 //===----------------------------------------------------------------------===//
8468 // Hexagon ABI Implementation
8469 //===----------------------------------------------------------------------===//
8470 
8471 namespace {
8472 
8473 class HexagonABIInfo : public DefaultABIInfo {
8474 public:
8475   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8476 
8477 private:
8478   ABIArgInfo classifyReturnType(QualType RetTy) const;
8479   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8480   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8481 
8482   void computeInfo(CGFunctionInfo &FI) const override;
8483 
8484   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8485                     QualType Ty) const override;
8486   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8487                               QualType Ty) const;
8488   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8489                               QualType Ty) const;
8490   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8491                                    QualType Ty) const;
8492 };
8493 
8494 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8495 public:
8496   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8497       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8498 
8499   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8500     return 29;
8501   }
8502 
8503   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8504                            CodeGen::CodeGenModule &GCM) const override {
8505     if (GV->isDeclaration())
8506       return;
8507     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8508     if (!FD)
8509       return;
8510   }
8511 };
8512 
8513 } // namespace
8514 
8515 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8516   unsigned RegsLeft = 6;
8517   if (!getCXXABI().classifyReturnType(FI))
8518     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8519   for (auto &I : FI.arguments())
8520     I.info = classifyArgumentType(I.type, &RegsLeft);
8521 }
8522 
8523 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8524   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8525                        " through registers");
8526 
8527   if (*RegsLeft == 0)
8528     return false;
8529 
8530   if (Size <= 32) {
8531     (*RegsLeft)--;
8532     return true;
8533   }
8534 
8535   if (2 <= (*RegsLeft & (~1U))) {
8536     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8537     return true;
8538   }
8539 
8540   // Next available register was r5 but candidate was greater than 32-bits so it
8541   // has to go on the stack. However we still consume r5
8542   if (*RegsLeft == 1)
8543     *RegsLeft = 0;
8544 
8545   return false;
8546 }
8547 
8548 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8549                                                 unsigned *RegsLeft) const {
8550   if (!isAggregateTypeForABI(Ty)) {
8551     // Treat an enum type as its underlying type.
8552     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8553       Ty = EnumTy->getDecl()->getIntegerType();
8554 
8555     uint64_t Size = getContext().getTypeSize(Ty);
8556     if (Size <= 64)
8557       HexagonAdjustRegsLeft(Size, RegsLeft);
8558 
8559     if (Size > 64 && Ty->isBitIntType())
8560       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8561 
8562     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8563                                              : ABIArgInfo::getDirect();
8564   }
8565 
8566   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8567     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8568 
8569   // Ignore empty records.
8570   if (isEmptyRecord(getContext(), Ty, true))
8571     return ABIArgInfo::getIgnore();
8572 
8573   uint64_t Size = getContext().getTypeSize(Ty);
8574   unsigned Align = getContext().getTypeAlign(Ty);
8575 
8576   if (Size > 64)
8577     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8578 
8579   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8580     Align = Size <= 32 ? 32 : 64;
8581   if (Size <= Align) {
8582     // Pass in the smallest viable integer type.
8583     if (!llvm::isPowerOf2_64(Size))
8584       Size = llvm::NextPowerOf2(Size);
8585     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8586   }
8587   return DefaultABIInfo::classifyArgumentType(Ty);
8588 }
8589 
8590 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8591   if (RetTy->isVoidType())
8592     return ABIArgInfo::getIgnore();
8593 
8594   const TargetInfo &T = CGT.getTarget();
8595   uint64_t Size = getContext().getTypeSize(RetTy);
8596 
8597   if (RetTy->getAs<VectorType>()) {
8598     // HVX vectors are returned in vector registers or register pairs.
8599     if (T.hasFeature("hvx")) {
8600       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8601       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8602       if (Size == VecSize || Size == 2*VecSize)
8603         return ABIArgInfo::getDirectInReg();
8604     }
8605     // Large vector types should be returned via memory.
8606     if (Size > 64)
8607       return getNaturalAlignIndirect(RetTy);
8608   }
8609 
8610   if (!isAggregateTypeForABI(RetTy)) {
8611     // Treat an enum type as its underlying type.
8612     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8613       RetTy = EnumTy->getDecl()->getIntegerType();
8614 
8615     if (Size > 64 && RetTy->isBitIntType())
8616       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8617 
8618     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8619                                                 : ABIArgInfo::getDirect();
8620   }
8621 
8622   if (isEmptyRecord(getContext(), RetTy, true))
8623     return ABIArgInfo::getIgnore();
8624 
8625   // Aggregates <= 8 bytes are returned in registers, other aggregates
8626   // are returned indirectly.
8627   if (Size <= 64) {
8628     // Return in the smallest viable integer type.
8629     if (!llvm::isPowerOf2_64(Size))
8630       Size = llvm::NextPowerOf2(Size);
8631     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8632   }
8633   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8634 }
8635 
8636 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8637                                             Address VAListAddr,
8638                                             QualType Ty) const {
8639   // Load the overflow area pointer.
8640   Address __overflow_area_pointer_p =
8641       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8642   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8643       __overflow_area_pointer_p, "__overflow_area_pointer");
8644 
8645   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8646   if (Align > 4) {
8647     // Alignment should be a power of 2.
8648     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8649 
8650     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8651     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8652 
8653     // Add offset to the current pointer to access the argument.
8654     __overflow_area_pointer =
8655         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8656     llvm::Value *AsInt =
8657         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8658 
8659     // Create a mask which should be "AND"ed
8660     // with (overflow_arg_area + align - 1)
8661     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8662     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8663         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8664         "__overflow_area_pointer.align");
8665   }
8666 
8667   // Get the type of the argument from memory and bitcast
8668   // overflow area pointer to the argument type.
8669   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8670   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8671       Address(__overflow_area_pointer, CGF.Int8Ty,
8672               CharUnits::fromQuantity(Align)),
8673       PTy);
8674 
8675   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8676   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8677 
8678   __overflow_area_pointer = CGF.Builder.CreateGEP(
8679       CGF.Int8Ty, __overflow_area_pointer,
8680       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8681       "__overflow_area_pointer.next");
8682   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8683 
8684   return AddrTyped;
8685 }
8686 
8687 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8688                                             Address VAListAddr,
8689                                             QualType Ty) const {
8690   // FIXME: Need to handle alignment
8691   llvm::Type *BP = CGF.Int8PtrTy;
8692   CGBuilderTy &Builder = CGF.Builder;
8693   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8694   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8695   // Handle address alignment for type alignment > 32 bits
8696   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8697   if (TyAlign > 4) {
8698     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8699     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8700     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8701     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8702     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8703   }
8704   Address AddrTyped = Builder.CreateElementBitCast(
8705       Address(Addr, CGF.Int8Ty, CharUnits::fromQuantity(TyAlign)),
8706       CGF.ConvertType(Ty));
8707 
8708   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8709   llvm::Value *NextAddr = Builder.CreateGEP(
8710       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8711   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8712 
8713   return AddrTyped;
8714 }
8715 
8716 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8717                                                  Address VAListAddr,
8718                                                  QualType Ty) const {
8719   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8720 
8721   if (ArgSize > 8)
8722     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8723 
8724   // Here we have check if the argument is in register area or
8725   // in overflow area.
8726   // If the saved register area pointer + argsize rounded up to alignment >
8727   // saved register area end pointer, argument is in overflow area.
8728   unsigned RegsLeft = 6;
8729   Ty = CGF.getContext().getCanonicalType(Ty);
8730   (void)classifyArgumentType(Ty, &RegsLeft);
8731 
8732   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8733   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8734   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8735   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8736 
8737   // Get rounded size of the argument.GCC does not allow vararg of
8738   // size < 4 bytes. We follow the same logic here.
8739   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8740   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8741 
8742   // Argument may be in saved register area
8743   CGF.EmitBlock(MaybeRegBlock);
8744 
8745   // Load the current saved register area pointer.
8746   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8747       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8748   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8749       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8750 
8751   // Load the saved register area end pointer.
8752   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8753       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8754   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8755       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8756 
8757   // If the size of argument is > 4 bytes, check if the stack
8758   // location is aligned to 8 bytes
8759   if (ArgAlign > 4) {
8760 
8761     llvm::Value *__current_saved_reg_area_pointer_int =
8762         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8763                                    CGF.Int32Ty);
8764 
8765     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8766         __current_saved_reg_area_pointer_int,
8767         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8768         "align_current_saved_reg_area_pointer");
8769 
8770     __current_saved_reg_area_pointer_int =
8771         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8772                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8773                               "align_current_saved_reg_area_pointer");
8774 
8775     __current_saved_reg_area_pointer =
8776         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8777                                    __current_saved_reg_area_pointer->getType(),
8778                                    "align_current_saved_reg_area_pointer");
8779   }
8780 
8781   llvm::Value *__new_saved_reg_area_pointer =
8782       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8783                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8784                             "__new_saved_reg_area_pointer");
8785 
8786   llvm::Value *UsingStack = nullptr;
8787   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8788                                          __saved_reg_area_end_pointer);
8789 
8790   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8791 
8792   // Argument in saved register area
8793   // Implement the block where argument is in register saved area
8794   CGF.EmitBlock(InRegBlock);
8795 
8796   llvm::Type *PTy = CGF.ConvertType(Ty);
8797   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8798       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8799 
8800   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8801                           __current_saved_reg_area_pointer_p);
8802 
8803   CGF.EmitBranch(ContBlock);
8804 
8805   // Argument in overflow area
8806   // Implement the block where the argument is in overflow area.
8807   CGF.EmitBlock(OnStackBlock);
8808 
8809   // Load the overflow area pointer
8810   Address __overflow_area_pointer_p =
8811       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8812   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8813       __overflow_area_pointer_p, "__overflow_area_pointer");
8814 
8815   // Align the overflow area pointer according to the alignment of the argument
8816   if (ArgAlign > 4) {
8817     llvm::Value *__overflow_area_pointer_int =
8818         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8819 
8820     __overflow_area_pointer_int =
8821         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8822                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8823                               "align_overflow_area_pointer");
8824 
8825     __overflow_area_pointer_int =
8826         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8827                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8828                               "align_overflow_area_pointer");
8829 
8830     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8831         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8832         "align_overflow_area_pointer");
8833   }
8834 
8835   // Get the pointer for next argument in overflow area and store it
8836   // to overflow area pointer.
8837   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8838       CGF.Int8Ty, __overflow_area_pointer,
8839       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8840       "__overflow_area_pointer.next");
8841 
8842   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8843                           __overflow_area_pointer_p);
8844 
8845   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8846                           __current_saved_reg_area_pointer_p);
8847 
8848   // Bitcast the overflow area pointer to the type of argument.
8849   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8850   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8851       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8852 
8853   CGF.EmitBranch(ContBlock);
8854 
8855   // Get the correct pointer to load the variable argument
8856   // Implement the ContBlock
8857   CGF.EmitBlock(ContBlock);
8858 
8859   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
8860   llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy);
8861   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8862   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8863   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8864 
8865   return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign));
8866 }
8867 
8868 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8869                                   QualType Ty) const {
8870 
8871   if (getTarget().getTriple().isMusl())
8872     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8873 
8874   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8875 }
8876 
8877 //===----------------------------------------------------------------------===//
8878 // Lanai ABI Implementation
8879 //===----------------------------------------------------------------------===//
8880 
8881 namespace {
8882 class LanaiABIInfo : public DefaultABIInfo {
8883 public:
8884   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8885 
8886   bool shouldUseInReg(QualType Ty, CCState &State) const;
8887 
8888   void computeInfo(CGFunctionInfo &FI) const override {
8889     CCState State(FI);
8890     // Lanai uses 4 registers to pass arguments unless the function has the
8891     // regparm attribute set.
8892     if (FI.getHasRegParm()) {
8893       State.FreeRegs = FI.getRegParm();
8894     } else {
8895       State.FreeRegs = 4;
8896     }
8897 
8898     if (!getCXXABI().classifyReturnType(FI))
8899       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8900     for (auto &I : FI.arguments())
8901       I.info = classifyArgumentType(I.type, State);
8902   }
8903 
8904   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8905   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8906 };
8907 } // end anonymous namespace
8908 
8909 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8910   unsigned Size = getContext().getTypeSize(Ty);
8911   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8912 
8913   if (SizeInRegs == 0)
8914     return false;
8915 
8916   if (SizeInRegs > State.FreeRegs) {
8917     State.FreeRegs = 0;
8918     return false;
8919   }
8920 
8921   State.FreeRegs -= SizeInRegs;
8922 
8923   return true;
8924 }
8925 
8926 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8927                                            CCState &State) const {
8928   if (!ByVal) {
8929     if (State.FreeRegs) {
8930       --State.FreeRegs; // Non-byval indirects just use one pointer.
8931       return getNaturalAlignIndirectInReg(Ty);
8932     }
8933     return getNaturalAlignIndirect(Ty, false);
8934   }
8935 
8936   // Compute the byval alignment.
8937   const unsigned MinABIStackAlignInBytes = 4;
8938   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8939   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8940                                  /*Realign=*/TypeAlign >
8941                                      MinABIStackAlignInBytes);
8942 }
8943 
8944 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8945                                               CCState &State) const {
8946   // Check with the C++ ABI first.
8947   const RecordType *RT = Ty->getAs<RecordType>();
8948   if (RT) {
8949     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8950     if (RAA == CGCXXABI::RAA_Indirect) {
8951       return getIndirectResult(Ty, /*ByVal=*/false, State);
8952     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8953       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8954     }
8955   }
8956 
8957   if (isAggregateTypeForABI(Ty)) {
8958     // Structures with flexible arrays are always indirect.
8959     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8960       return getIndirectResult(Ty, /*ByVal=*/true, State);
8961 
8962     // Ignore empty structs/unions.
8963     if (isEmptyRecord(getContext(), Ty, true))
8964       return ABIArgInfo::getIgnore();
8965 
8966     llvm::LLVMContext &LLVMContext = getVMContext();
8967     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8968     if (SizeInRegs <= State.FreeRegs) {
8969       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8970       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8971       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8972       State.FreeRegs -= SizeInRegs;
8973       return ABIArgInfo::getDirectInReg(Result);
8974     } else {
8975       State.FreeRegs = 0;
8976     }
8977     return getIndirectResult(Ty, true, State);
8978   }
8979 
8980   // Treat an enum type as its underlying type.
8981   if (const auto *EnumTy = Ty->getAs<EnumType>())
8982     Ty = EnumTy->getDecl()->getIntegerType();
8983 
8984   bool InReg = shouldUseInReg(Ty, State);
8985 
8986   // Don't pass >64 bit integers in registers.
8987   if (const auto *EIT = Ty->getAs<BitIntType>())
8988     if (EIT->getNumBits() > 64)
8989       return getIndirectResult(Ty, /*ByVal=*/true, State);
8990 
8991   if (isPromotableIntegerTypeForABI(Ty)) {
8992     if (InReg)
8993       return ABIArgInfo::getDirectInReg();
8994     return ABIArgInfo::getExtend(Ty);
8995   }
8996   if (InReg)
8997     return ABIArgInfo::getDirectInReg();
8998   return ABIArgInfo::getDirect();
8999 }
9000 
9001 namespace {
9002 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
9003 public:
9004   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9005       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
9006 };
9007 }
9008 
9009 //===----------------------------------------------------------------------===//
9010 // AMDGPU ABI Implementation
9011 //===----------------------------------------------------------------------===//
9012 
9013 namespace {
9014 
9015 class AMDGPUABIInfo final : public DefaultABIInfo {
9016 private:
9017   static const unsigned MaxNumRegsForArgsRet = 16;
9018 
9019   unsigned numRegsForType(QualType Ty) const;
9020 
9021   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
9022   bool isHomogeneousAggregateSmallEnough(const Type *Base,
9023                                          uint64_t Members) const override;
9024 
9025   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
9026   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
9027                                        unsigned ToAS) const {
9028     // Single value types.
9029     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
9030     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
9031       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
9032     return Ty;
9033   }
9034 
9035 public:
9036   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
9037     DefaultABIInfo(CGT) {}
9038 
9039   ABIArgInfo classifyReturnType(QualType RetTy) const;
9040   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
9041   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
9042 
9043   void computeInfo(CGFunctionInfo &FI) const override;
9044   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9045                     QualType Ty) const override;
9046 };
9047 
9048 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
9049   return true;
9050 }
9051 
9052 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
9053   const Type *Base, uint64_t Members) const {
9054   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
9055 
9056   // Homogeneous Aggregates may occupy at most 16 registers.
9057   return Members * NumRegs <= MaxNumRegsForArgsRet;
9058 }
9059 
9060 /// Estimate number of registers the type will use when passed in registers.
9061 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
9062   unsigned NumRegs = 0;
9063 
9064   if (const VectorType *VT = Ty->getAs<VectorType>()) {
9065     // Compute from the number of elements. The reported size is based on the
9066     // in-memory size, which includes the padding 4th element for 3-vectors.
9067     QualType EltTy = VT->getElementType();
9068     unsigned EltSize = getContext().getTypeSize(EltTy);
9069 
9070     // 16-bit element vectors should be passed as packed.
9071     if (EltSize == 16)
9072       return (VT->getNumElements() + 1) / 2;
9073 
9074     unsigned EltNumRegs = (EltSize + 31) / 32;
9075     return EltNumRegs * VT->getNumElements();
9076   }
9077 
9078   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9079     const RecordDecl *RD = RT->getDecl();
9080     assert(!RD->hasFlexibleArrayMember());
9081 
9082     for (const FieldDecl *Field : RD->fields()) {
9083       QualType FieldTy = Field->getType();
9084       NumRegs += numRegsForType(FieldTy);
9085     }
9086 
9087     return NumRegs;
9088   }
9089 
9090   return (getContext().getTypeSize(Ty) + 31) / 32;
9091 }
9092 
9093 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9094   llvm::CallingConv::ID CC = FI.getCallingConvention();
9095 
9096   if (!getCXXABI().classifyReturnType(FI))
9097     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9098 
9099   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9100   for (auto &Arg : FI.arguments()) {
9101     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9102       Arg.info = classifyKernelArgumentType(Arg.type);
9103     } else {
9104       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9105     }
9106   }
9107 }
9108 
9109 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9110                                  QualType Ty) const {
9111   llvm_unreachable("AMDGPU does not support varargs");
9112 }
9113 
9114 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9115   if (isAggregateTypeForABI(RetTy)) {
9116     // Records with non-trivial destructors/copy-constructors should not be
9117     // returned by value.
9118     if (!getRecordArgABI(RetTy, getCXXABI())) {
9119       // Ignore empty structs/unions.
9120       if (isEmptyRecord(getContext(), RetTy, true))
9121         return ABIArgInfo::getIgnore();
9122 
9123       // Lower single-element structs to just return a regular value.
9124       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9125         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9126 
9127       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9128         const RecordDecl *RD = RT->getDecl();
9129         if (RD->hasFlexibleArrayMember())
9130           return DefaultABIInfo::classifyReturnType(RetTy);
9131       }
9132 
9133       // Pack aggregates <= 4 bytes into single VGPR or pair.
9134       uint64_t Size = getContext().getTypeSize(RetTy);
9135       if (Size <= 16)
9136         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9137 
9138       if (Size <= 32)
9139         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9140 
9141       if (Size <= 64) {
9142         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9143         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9144       }
9145 
9146       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9147         return ABIArgInfo::getDirect();
9148     }
9149   }
9150 
9151   // Otherwise just do the default thing.
9152   return DefaultABIInfo::classifyReturnType(RetTy);
9153 }
9154 
9155 /// For kernels all parameters are really passed in a special buffer. It doesn't
9156 /// make sense to pass anything byval, so everything must be direct.
9157 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9158   Ty = useFirstFieldIfTransparentUnion(Ty);
9159 
9160   // TODO: Can we omit empty structs?
9161 
9162   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9163     Ty = QualType(SeltTy, 0);
9164 
9165   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9166   llvm::Type *LTy = OrigLTy;
9167   if (getContext().getLangOpts().HIP) {
9168     LTy = coerceKernelArgumentType(
9169         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9170         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9171   }
9172 
9173   // FIXME: Should also use this for OpenCL, but it requires addressing the
9174   // problem of kernels being called.
9175   //
9176   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9177   // to global address space when using byref. This would require implementing a
9178   // new kind of coercion of the in-memory type when for indirect arguments.
9179   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9180       isAggregateTypeForABI(Ty)) {
9181     return ABIArgInfo::getIndirectAliased(
9182         getContext().getTypeAlignInChars(Ty),
9183         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9184         false /*Realign*/, nullptr /*Padding*/);
9185   }
9186 
9187   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9188   // individual elements, which confuses the Clover OpenCL backend; therefore we
9189   // have to set it to false here. Other args of getDirect() are just defaults.
9190   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9191 }
9192 
9193 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9194                                                unsigned &NumRegsLeft) const {
9195   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9196 
9197   Ty = useFirstFieldIfTransparentUnion(Ty);
9198 
9199   if (isAggregateTypeForABI(Ty)) {
9200     // Records with non-trivial destructors/copy-constructors should not be
9201     // passed by value.
9202     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9203       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9204 
9205     // Ignore empty structs/unions.
9206     if (isEmptyRecord(getContext(), Ty, true))
9207       return ABIArgInfo::getIgnore();
9208 
9209     // Lower single-element structs to just pass a regular value. TODO: We
9210     // could do reasonable-size multiple-element structs too, using getExpand(),
9211     // though watch out for things like bitfields.
9212     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9213       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9214 
9215     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9216       const RecordDecl *RD = RT->getDecl();
9217       if (RD->hasFlexibleArrayMember())
9218         return DefaultABIInfo::classifyArgumentType(Ty);
9219     }
9220 
9221     // Pack aggregates <= 8 bytes into single VGPR or pair.
9222     uint64_t Size = getContext().getTypeSize(Ty);
9223     if (Size <= 64) {
9224       unsigned NumRegs = (Size + 31) / 32;
9225       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9226 
9227       if (Size <= 16)
9228         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9229 
9230       if (Size <= 32)
9231         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9232 
9233       // XXX: Should this be i64 instead, and should the limit increase?
9234       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9235       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9236     }
9237 
9238     if (NumRegsLeft > 0) {
9239       unsigned NumRegs = numRegsForType(Ty);
9240       if (NumRegsLeft >= NumRegs) {
9241         NumRegsLeft -= NumRegs;
9242         return ABIArgInfo::getDirect();
9243       }
9244     }
9245   }
9246 
9247   // Otherwise just do the default thing.
9248   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9249   if (!ArgInfo.isIndirect()) {
9250     unsigned NumRegs = numRegsForType(Ty);
9251     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9252   }
9253 
9254   return ArgInfo;
9255 }
9256 
9257 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9258 public:
9259   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9260       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9261 
9262   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9263                                  CodeGenModule &CGM) const;
9264 
9265   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9266                            CodeGen::CodeGenModule &M) const override;
9267   unsigned getOpenCLKernelCallingConv() const override;
9268 
9269   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9270       llvm::PointerType *T, QualType QT) const override;
9271 
9272   LangAS getASTAllocaAddressSpace() const override {
9273     return getLangASFromTargetAS(
9274         getABIInfo().getDataLayout().getAllocaAddrSpace());
9275   }
9276   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9277                                   const VarDecl *D) const override;
9278   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9279                                          SyncScope Scope,
9280                                          llvm::AtomicOrdering Ordering,
9281                                          llvm::LLVMContext &Ctx) const override;
9282   llvm::Function *
9283   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9284                             llvm::Function *BlockInvokeFunc,
9285                             llvm::Type *BlockTy) const override;
9286   bool shouldEmitStaticExternCAliases() const override;
9287   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9288 };
9289 }
9290 
9291 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9292                                               llvm::GlobalValue *GV) {
9293   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9294     return false;
9295 
9296   return D->hasAttr<OpenCLKernelAttr>() ||
9297          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9298          (isa<VarDecl>(D) &&
9299           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9300            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9301            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9302 }
9303 
9304 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9305     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9306   const auto *ReqdWGS =
9307       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9308   const bool IsOpenCLKernel =
9309       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9310   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9311 
9312   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9313   if (ReqdWGS || FlatWGS) {
9314     unsigned Min = 0;
9315     unsigned Max = 0;
9316     if (FlatWGS) {
9317       Min = FlatWGS->getMin()
9318                 ->EvaluateKnownConstInt(M.getContext())
9319                 .getExtValue();
9320       Max = FlatWGS->getMax()
9321                 ->EvaluateKnownConstInt(M.getContext())
9322                 .getExtValue();
9323     }
9324     if (ReqdWGS && Min == 0 && Max == 0)
9325       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9326 
9327     if (Min != 0) {
9328       assert(Min <= Max && "Min must be less than or equal Max");
9329 
9330       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9331       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9332     } else
9333       assert(Max == 0 && "Max must be zero");
9334   } else if (IsOpenCLKernel || IsHIPKernel) {
9335     // By default, restrict the maximum size to a value specified by
9336     // --gpu-max-threads-per-block=n or its default value for HIP.
9337     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9338     const unsigned DefaultMaxWorkGroupSize =
9339         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9340                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9341     std::string AttrVal =
9342         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9343     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9344   }
9345 
9346   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9347     unsigned Min =
9348         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9349     unsigned Max = Attr->getMax() ? Attr->getMax()
9350                                         ->EvaluateKnownConstInt(M.getContext())
9351                                         .getExtValue()
9352                                   : 0;
9353 
9354     if (Min != 0) {
9355       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9356 
9357       std::string AttrVal = llvm::utostr(Min);
9358       if (Max != 0)
9359         AttrVal = AttrVal + "," + llvm::utostr(Max);
9360       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9361     } else
9362       assert(Max == 0 && "Max must be zero");
9363   }
9364 
9365   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9366     unsigned NumSGPR = Attr->getNumSGPR();
9367 
9368     if (NumSGPR != 0)
9369       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9370   }
9371 
9372   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9373     uint32_t NumVGPR = Attr->getNumVGPR();
9374 
9375     if (NumVGPR != 0)
9376       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9377   }
9378 }
9379 
9380 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9381     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9382   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9383     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9384     GV->setDSOLocal(true);
9385   }
9386 
9387   if (GV->isDeclaration())
9388     return;
9389 
9390   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9391   if (!F)
9392     return;
9393 
9394   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9395   if (FD)
9396     setFunctionDeclAttributes(FD, F, M);
9397 
9398   const bool IsHIPKernel =
9399       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9400 
9401   if (IsHIPKernel)
9402     F->addFnAttr("uniform-work-group-size", "true");
9403 
9404   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9405     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9406 
9407   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9408     F->addFnAttr("amdgpu-ieee", "false");
9409 }
9410 
9411 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9412   return llvm::CallingConv::AMDGPU_KERNEL;
9413 }
9414 
9415 // Currently LLVM assumes null pointers always have value 0,
9416 // which results in incorrectly transformed IR. Therefore, instead of
9417 // emitting null pointers in private and local address spaces, a null
9418 // pointer in generic address space is emitted which is casted to a
9419 // pointer in local or private address space.
9420 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9421     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9422     QualType QT) const {
9423   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9424     return llvm::ConstantPointerNull::get(PT);
9425 
9426   auto &Ctx = CGM.getContext();
9427   auto NPT = llvm::PointerType::getWithSamePointeeType(
9428       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9429   return llvm::ConstantExpr::getAddrSpaceCast(
9430       llvm::ConstantPointerNull::get(NPT), PT);
9431 }
9432 
9433 LangAS
9434 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9435                                                   const VarDecl *D) const {
9436   assert(!CGM.getLangOpts().OpenCL &&
9437          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9438          "Address space agnostic languages only");
9439   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9440       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9441   if (!D)
9442     return DefaultGlobalAS;
9443 
9444   LangAS AddrSpace = D->getType().getAddressSpace();
9445   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9446   if (AddrSpace != LangAS::Default)
9447     return AddrSpace;
9448 
9449   // Only promote to address space 4 if VarDecl has constant initialization.
9450   if (CGM.isTypeConstant(D->getType(), false) &&
9451       D->hasConstantInitialization()) {
9452     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9453       return ConstAS.getValue();
9454   }
9455   return DefaultGlobalAS;
9456 }
9457 
9458 llvm::SyncScope::ID
9459 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9460                                             SyncScope Scope,
9461                                             llvm::AtomicOrdering Ordering,
9462                                             llvm::LLVMContext &Ctx) const {
9463   std::string Name;
9464   switch (Scope) {
9465   case SyncScope::HIPSingleThread:
9466     Name = "singlethread";
9467     break;
9468   case SyncScope::HIPWavefront:
9469   case SyncScope::OpenCLSubGroup:
9470     Name = "wavefront";
9471     break;
9472   case SyncScope::HIPWorkgroup:
9473   case SyncScope::OpenCLWorkGroup:
9474     Name = "workgroup";
9475     break;
9476   case SyncScope::HIPAgent:
9477   case SyncScope::OpenCLDevice:
9478     Name = "agent";
9479     break;
9480   case SyncScope::HIPSystem:
9481   case SyncScope::OpenCLAllSVMDevices:
9482     Name = "";
9483     break;
9484   }
9485 
9486   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9487     if (!Name.empty())
9488       Name = Twine(Twine(Name) + Twine("-")).str();
9489 
9490     Name = Twine(Twine(Name) + Twine("one-as")).str();
9491   }
9492 
9493   return Ctx.getOrInsertSyncScopeID(Name);
9494 }
9495 
9496 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9497   return false;
9498 }
9499 
9500 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9501     const FunctionType *&FT) const {
9502   FT = getABIInfo().getContext().adjustFunctionType(
9503       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9504 }
9505 
9506 //===----------------------------------------------------------------------===//
9507 // SPARC v8 ABI Implementation.
9508 // Based on the SPARC Compliance Definition version 2.4.1.
9509 //
9510 // Ensures that complex values are passed in registers.
9511 //
9512 namespace {
9513 class SparcV8ABIInfo : public DefaultABIInfo {
9514 public:
9515   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9516 
9517 private:
9518   ABIArgInfo classifyReturnType(QualType RetTy) const;
9519   void computeInfo(CGFunctionInfo &FI) const override;
9520 };
9521 } // end anonymous namespace
9522 
9523 
9524 ABIArgInfo
9525 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9526   if (Ty->isAnyComplexType()) {
9527     return ABIArgInfo::getDirect();
9528   }
9529   else {
9530     return DefaultABIInfo::classifyReturnType(Ty);
9531   }
9532 }
9533 
9534 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9535 
9536   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9537   for (auto &Arg : FI.arguments())
9538     Arg.info = classifyArgumentType(Arg.type);
9539 }
9540 
9541 namespace {
9542 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9543 public:
9544   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9545       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9546 
9547   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9548                                    llvm::Value *Address) const override {
9549     int Offset;
9550     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9551       Offset = 12;
9552     else
9553       Offset = 8;
9554     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9555                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9556   }
9557 
9558   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9559                                    llvm::Value *Address) const override {
9560     int Offset;
9561     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9562       Offset = -12;
9563     else
9564       Offset = -8;
9565     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9566                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9567   }
9568 };
9569 } // end anonymous namespace
9570 
9571 //===----------------------------------------------------------------------===//
9572 // SPARC v9 ABI Implementation.
9573 // Based on the SPARC Compliance Definition version 2.4.1.
9574 //
9575 // Function arguments a mapped to a nominal "parameter array" and promoted to
9576 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9577 // the array, structs larger than 16 bytes are passed indirectly.
9578 //
9579 // One case requires special care:
9580 //
9581 //   struct mixed {
9582 //     int i;
9583 //     float f;
9584 //   };
9585 //
9586 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9587 // parameter array, but the int is passed in an integer register, and the float
9588 // is passed in a floating point register. This is represented as two arguments
9589 // with the LLVM IR inreg attribute:
9590 //
9591 //   declare void f(i32 inreg %i, float inreg %f)
9592 //
9593 // The code generator will only allocate 4 bytes from the parameter array for
9594 // the inreg arguments. All other arguments are allocated a multiple of 8
9595 // bytes.
9596 //
9597 namespace {
9598 class SparcV9ABIInfo : public ABIInfo {
9599 public:
9600   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9601 
9602 private:
9603   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9604   void computeInfo(CGFunctionInfo &FI) const override;
9605   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9606                     QualType Ty) const override;
9607 
9608   // Coercion type builder for structs passed in registers. The coercion type
9609   // serves two purposes:
9610   //
9611   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9612   //    in registers.
9613   // 2. Expose aligned floating point elements as first-level elements, so the
9614   //    code generator knows to pass them in floating point registers.
9615   //
9616   // We also compute the InReg flag which indicates that the struct contains
9617   // aligned 32-bit floats.
9618   //
9619   struct CoerceBuilder {
9620     llvm::LLVMContext &Context;
9621     const llvm::DataLayout &DL;
9622     SmallVector<llvm::Type*, 8> Elems;
9623     uint64_t Size;
9624     bool InReg;
9625 
9626     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9627       : Context(c), DL(dl), Size(0), InReg(false) {}
9628 
9629     // Pad Elems with integers until Size is ToSize.
9630     void pad(uint64_t ToSize) {
9631       assert(ToSize >= Size && "Cannot remove elements");
9632       if (ToSize == Size)
9633         return;
9634 
9635       // Finish the current 64-bit word.
9636       uint64_t Aligned = llvm::alignTo(Size, 64);
9637       if (Aligned > Size && Aligned <= ToSize) {
9638         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9639         Size = Aligned;
9640       }
9641 
9642       // Add whole 64-bit words.
9643       while (Size + 64 <= ToSize) {
9644         Elems.push_back(llvm::Type::getInt64Ty(Context));
9645         Size += 64;
9646       }
9647 
9648       // Final in-word padding.
9649       if (Size < ToSize) {
9650         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9651         Size = ToSize;
9652       }
9653     }
9654 
9655     // Add a floating point element at Offset.
9656     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9657       // Unaligned floats are treated as integers.
9658       if (Offset % Bits)
9659         return;
9660       // The InReg flag is only required if there are any floats < 64 bits.
9661       if (Bits < 64)
9662         InReg = true;
9663       pad(Offset);
9664       Elems.push_back(Ty);
9665       Size = Offset + Bits;
9666     }
9667 
9668     // Add a struct type to the coercion type, starting at Offset (in bits).
9669     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9670       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9671       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9672         llvm::Type *ElemTy = StrTy->getElementType(i);
9673         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9674         switch (ElemTy->getTypeID()) {
9675         case llvm::Type::StructTyID:
9676           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9677           break;
9678         case llvm::Type::FloatTyID:
9679           addFloat(ElemOffset, ElemTy, 32);
9680           break;
9681         case llvm::Type::DoubleTyID:
9682           addFloat(ElemOffset, ElemTy, 64);
9683           break;
9684         case llvm::Type::FP128TyID:
9685           addFloat(ElemOffset, ElemTy, 128);
9686           break;
9687         case llvm::Type::PointerTyID:
9688           if (ElemOffset % 64 == 0) {
9689             pad(ElemOffset);
9690             Elems.push_back(ElemTy);
9691             Size += 64;
9692           }
9693           break;
9694         default:
9695           break;
9696         }
9697       }
9698     }
9699 
9700     // Check if Ty is a usable substitute for the coercion type.
9701     bool isUsableType(llvm::StructType *Ty) const {
9702       return llvm::makeArrayRef(Elems) == Ty->elements();
9703     }
9704 
9705     // Get the coercion type as a literal struct type.
9706     llvm::Type *getType() const {
9707       if (Elems.size() == 1)
9708         return Elems.front();
9709       else
9710         return llvm::StructType::get(Context, Elems);
9711     }
9712   };
9713 };
9714 } // end anonymous namespace
9715 
9716 ABIArgInfo
9717 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9718   if (Ty->isVoidType())
9719     return ABIArgInfo::getIgnore();
9720 
9721   uint64_t Size = getContext().getTypeSize(Ty);
9722 
9723   // Anything too big to fit in registers is passed with an explicit indirect
9724   // pointer / sret pointer.
9725   if (Size > SizeLimit)
9726     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9727 
9728   // Treat an enum type as its underlying type.
9729   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9730     Ty = EnumTy->getDecl()->getIntegerType();
9731 
9732   // Integer types smaller than a register are extended.
9733   if (Size < 64 && Ty->isIntegerType())
9734     return ABIArgInfo::getExtend(Ty);
9735 
9736   if (const auto *EIT = Ty->getAs<BitIntType>())
9737     if (EIT->getNumBits() < 64)
9738       return ABIArgInfo::getExtend(Ty);
9739 
9740   // Other non-aggregates go in registers.
9741   if (!isAggregateTypeForABI(Ty))
9742     return ABIArgInfo::getDirect();
9743 
9744   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9745   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9746   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9747     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9748 
9749   // This is a small aggregate type that should be passed in registers.
9750   // Build a coercion type from the LLVM struct type.
9751   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9752   if (!StrTy)
9753     return ABIArgInfo::getDirect();
9754 
9755   CoerceBuilder CB(getVMContext(), getDataLayout());
9756   CB.addStruct(0, StrTy);
9757   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9758 
9759   // Try to use the original type for coercion.
9760   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9761 
9762   if (CB.InReg)
9763     return ABIArgInfo::getDirectInReg(CoerceTy);
9764   else
9765     return ABIArgInfo::getDirect(CoerceTy);
9766 }
9767 
9768 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9769                                   QualType Ty) const {
9770   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9771   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9772   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9773     AI.setCoerceToType(ArgTy);
9774 
9775   CharUnits SlotSize = CharUnits::fromQuantity(8);
9776 
9777   CGBuilderTy &Builder = CGF.Builder;
9778   Address Addr = Address(Builder.CreateLoad(VAListAddr, "ap.cur"),
9779                          getVAListElementType(CGF), SlotSize);
9780   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9781 
9782   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9783 
9784   Address ArgAddr = Address::invalid();
9785   CharUnits Stride;
9786   switch (AI.getKind()) {
9787   case ABIArgInfo::Expand:
9788   case ABIArgInfo::CoerceAndExpand:
9789   case ABIArgInfo::InAlloca:
9790     llvm_unreachable("Unsupported ABI kind for va_arg");
9791 
9792   case ABIArgInfo::Extend: {
9793     Stride = SlotSize;
9794     CharUnits Offset = SlotSize - TypeInfo.Width;
9795     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9796     break;
9797   }
9798 
9799   case ABIArgInfo::Direct: {
9800     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9801     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9802     ArgAddr = Addr;
9803     break;
9804   }
9805 
9806   case ABIArgInfo::Indirect:
9807   case ABIArgInfo::IndirectAliased:
9808     Stride = SlotSize;
9809     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9810     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), ArgTy,
9811                       TypeInfo.Align);
9812     break;
9813 
9814   case ABIArgInfo::Ignore:
9815     return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align);
9816   }
9817 
9818   // Update VAList.
9819   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9820   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9821 
9822   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9823 }
9824 
9825 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9826   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9827   for (auto &I : FI.arguments())
9828     I.info = classifyType(I.type, 16 * 8);
9829 }
9830 
9831 namespace {
9832 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9833 public:
9834   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9835       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9836 
9837   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9838     return 14;
9839   }
9840 
9841   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9842                                llvm::Value *Address) const override;
9843 
9844   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9845                                    llvm::Value *Address) const override {
9846     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9847                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9848   }
9849 
9850   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9851                                    llvm::Value *Address) const override {
9852     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9853                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9854   }
9855 };
9856 } // end anonymous namespace
9857 
9858 bool
9859 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9860                                                 llvm::Value *Address) const {
9861   // This is calculated from the LLVM and GCC tables and verified
9862   // against gcc output.  AFAIK all ABIs use the same encoding.
9863 
9864   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9865 
9866   llvm::IntegerType *i8 = CGF.Int8Ty;
9867   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9868   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9869 
9870   // 0-31: the 8-byte general-purpose registers
9871   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9872 
9873   // 32-63: f0-31, the 4-byte floating-point registers
9874   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9875 
9876   //   Y   = 64
9877   //   PSR = 65
9878   //   WIM = 66
9879   //   TBR = 67
9880   //   PC  = 68
9881   //   NPC = 69
9882   //   FSR = 70
9883   //   CSR = 71
9884   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9885 
9886   // 72-87: d0-15, the 8-byte floating-point registers
9887   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9888 
9889   return false;
9890 }
9891 
9892 // ARC ABI implementation.
9893 namespace {
9894 
9895 class ARCABIInfo : public DefaultABIInfo {
9896 public:
9897   using DefaultABIInfo::DefaultABIInfo;
9898 
9899 private:
9900   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9901                     QualType Ty) const override;
9902 
9903   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9904     if (!State.FreeRegs)
9905       return;
9906     if (Info.isIndirect() && Info.getInReg())
9907       State.FreeRegs--;
9908     else if (Info.isDirect() && Info.getInReg()) {
9909       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9910       if (sz < State.FreeRegs)
9911         State.FreeRegs -= sz;
9912       else
9913         State.FreeRegs = 0;
9914     }
9915   }
9916 
9917   void computeInfo(CGFunctionInfo &FI) const override {
9918     CCState State(FI);
9919     // ARC uses 8 registers to pass arguments.
9920     State.FreeRegs = 8;
9921 
9922     if (!getCXXABI().classifyReturnType(FI))
9923       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9924     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9925     for (auto &I : FI.arguments()) {
9926       I.info = classifyArgumentType(I.type, State.FreeRegs);
9927       updateState(I.info, I.type, State);
9928     }
9929   }
9930 
9931   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9932   ABIArgInfo getIndirectByValue(QualType Ty) const;
9933   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9934   ABIArgInfo classifyReturnType(QualType RetTy) const;
9935 };
9936 
9937 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9938 public:
9939   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9940       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9941 };
9942 
9943 
9944 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9945   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9946                        getNaturalAlignIndirect(Ty, false);
9947 }
9948 
9949 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9950   // Compute the byval alignment.
9951   const unsigned MinABIStackAlignInBytes = 4;
9952   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9953   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9954                                  TypeAlign > MinABIStackAlignInBytes);
9955 }
9956 
9957 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9958                               QualType Ty) const {
9959   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9960                           getContext().getTypeInfoInChars(Ty),
9961                           CharUnits::fromQuantity(4), true);
9962 }
9963 
9964 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9965                                             uint8_t FreeRegs) const {
9966   // Handle the generic C++ ABI.
9967   const RecordType *RT = Ty->getAs<RecordType>();
9968   if (RT) {
9969     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9970     if (RAA == CGCXXABI::RAA_Indirect)
9971       return getIndirectByRef(Ty, FreeRegs > 0);
9972 
9973     if (RAA == CGCXXABI::RAA_DirectInMemory)
9974       return getIndirectByValue(Ty);
9975   }
9976 
9977   // Treat an enum type as its underlying type.
9978   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9979     Ty = EnumTy->getDecl()->getIntegerType();
9980 
9981   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9982 
9983   if (isAggregateTypeForABI(Ty)) {
9984     // Structures with flexible arrays are always indirect.
9985     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9986       return getIndirectByValue(Ty);
9987 
9988     // Ignore empty structs/unions.
9989     if (isEmptyRecord(getContext(), Ty, true))
9990       return ABIArgInfo::getIgnore();
9991 
9992     llvm::LLVMContext &LLVMContext = getVMContext();
9993 
9994     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9995     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9996     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9997 
9998     return FreeRegs >= SizeInRegs ?
9999         ABIArgInfo::getDirectInReg(Result) :
10000         ABIArgInfo::getDirect(Result, 0, nullptr, false);
10001   }
10002 
10003   if (const auto *EIT = Ty->getAs<BitIntType>())
10004     if (EIT->getNumBits() > 64)
10005       return getIndirectByValue(Ty);
10006 
10007   return isPromotableIntegerTypeForABI(Ty)
10008              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
10009                                        : ABIArgInfo::getExtend(Ty))
10010              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
10011                                        : ABIArgInfo::getDirect());
10012 }
10013 
10014 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
10015   if (RetTy->isAnyComplexType())
10016     return ABIArgInfo::getDirectInReg();
10017 
10018   // Arguments of size > 4 registers are indirect.
10019   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
10020   if (RetSize > 4)
10021     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
10022 
10023   return DefaultABIInfo::classifyReturnType(RetTy);
10024 }
10025 
10026 } // End anonymous namespace.
10027 
10028 //===----------------------------------------------------------------------===//
10029 // XCore ABI Implementation
10030 //===----------------------------------------------------------------------===//
10031 
10032 namespace {
10033 
10034 /// A SmallStringEnc instance is used to build up the TypeString by passing
10035 /// it by reference between functions that append to it.
10036 typedef llvm::SmallString<128> SmallStringEnc;
10037 
10038 /// TypeStringCache caches the meta encodings of Types.
10039 ///
10040 /// The reason for caching TypeStrings is two fold:
10041 ///   1. To cache a type's encoding for later uses;
10042 ///   2. As a means to break recursive member type inclusion.
10043 ///
10044 /// A cache Entry can have a Status of:
10045 ///   NonRecursive:   The type encoding is not recursive;
10046 ///   Recursive:      The type encoding is recursive;
10047 ///   Incomplete:     An incomplete TypeString;
10048 ///   IncompleteUsed: An incomplete TypeString that has been used in a
10049 ///                   Recursive type encoding.
10050 ///
10051 /// A NonRecursive entry will have all of its sub-members expanded as fully
10052 /// as possible. Whilst it may contain types which are recursive, the type
10053 /// itself is not recursive and thus its encoding may be safely used whenever
10054 /// the type is encountered.
10055 ///
10056 /// A Recursive entry will have all of its sub-members expanded as fully as
10057 /// possible. The type itself is recursive and it may contain other types which
10058 /// are recursive. The Recursive encoding must not be used during the expansion
10059 /// of a recursive type's recursive branch. For simplicity the code uses
10060 /// IncompleteCount to reject all usage of Recursive encodings for member types.
10061 ///
10062 /// An Incomplete entry is always a RecordType and only encodes its
10063 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
10064 /// are placed into the cache during type expansion as a means to identify and
10065 /// handle recursive inclusion of types as sub-members. If there is recursion
10066 /// the entry becomes IncompleteUsed.
10067 ///
10068 /// During the expansion of a RecordType's members:
10069 ///
10070 ///   If the cache contains a NonRecursive encoding for the member type, the
10071 ///   cached encoding is used;
10072 ///
10073 ///   If the cache contains a Recursive encoding for the member type, the
10074 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10075 ///
10076 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10077 ///   cache to break potential recursive inclusion of itself as a sub-member;
10078 ///
10079 ///   Once a member RecordType has been expanded, its temporary incomplete
10080 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10081 ///   it is swapped back in;
10082 ///
10083 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10084 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10085 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10086 ///
10087 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10088 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10089 ///   Else the member is part of a recursive type and thus the recursion has
10090 ///   been exited too soon for the encoding to be correct for the member.
10091 ///
10092 class TypeStringCache {
10093   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10094   struct Entry {
10095     std::string Str;     // The encoded TypeString for the type.
10096     enum Status State;   // Information about the encoding in 'Str'.
10097     std::string Swapped; // A temporary place holder for a Recursive encoding
10098                          // during the expansion of RecordType's members.
10099   };
10100   std::map<const IdentifierInfo *, struct Entry> Map;
10101   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10102   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10103 public:
10104   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10105   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10106   bool removeIncomplete(const IdentifierInfo *ID);
10107   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10108                      bool IsRecursive);
10109   StringRef lookupStr(const IdentifierInfo *ID);
10110 };
10111 
10112 /// TypeString encodings for enum & union fields must be order.
10113 /// FieldEncoding is a helper for this ordering process.
10114 class FieldEncoding {
10115   bool HasName;
10116   std::string Enc;
10117 public:
10118   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10119   StringRef str() { return Enc; }
10120   bool operator<(const FieldEncoding &rhs) const {
10121     if (HasName != rhs.HasName) return HasName;
10122     return Enc < rhs.Enc;
10123   }
10124 };
10125 
10126 class XCoreABIInfo : public DefaultABIInfo {
10127 public:
10128   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10129   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10130                     QualType Ty) const override;
10131 };
10132 
10133 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10134   mutable TypeStringCache TSC;
10135   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10136                     const CodeGen::CodeGenModule &M) const;
10137 
10138 public:
10139   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10140       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10141   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10142                           const llvm::MapVector<GlobalDecl, StringRef>
10143                               &MangledDeclNames) const override;
10144 };
10145 
10146 } // End anonymous namespace.
10147 
10148 // TODO: this implementation is likely now redundant with the default
10149 // EmitVAArg.
10150 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10151                                 QualType Ty) const {
10152   CGBuilderTy &Builder = CGF.Builder;
10153 
10154   // Get the VAList.
10155   CharUnits SlotSize = CharUnits::fromQuantity(4);
10156   Address AP = Address(Builder.CreateLoad(VAListAddr),
10157                        getVAListElementType(CGF), SlotSize);
10158 
10159   // Handle the argument.
10160   ABIArgInfo AI = classifyArgumentType(Ty);
10161   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10162   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10163   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10164     AI.setCoerceToType(ArgTy);
10165   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10166 
10167   Address Val = Address::invalid();
10168   CharUnits ArgSize = CharUnits::Zero();
10169   switch (AI.getKind()) {
10170   case ABIArgInfo::Expand:
10171   case ABIArgInfo::CoerceAndExpand:
10172   case ABIArgInfo::InAlloca:
10173     llvm_unreachable("Unsupported ABI kind for va_arg");
10174   case ABIArgInfo::Ignore:
10175     Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign);
10176     ArgSize = CharUnits::Zero();
10177     break;
10178   case ABIArgInfo::Extend:
10179   case ABIArgInfo::Direct:
10180     Val = Builder.CreateElementBitCast(AP, ArgTy);
10181     ArgSize = CharUnits::fromQuantity(
10182         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10183     ArgSize = ArgSize.alignTo(SlotSize);
10184     break;
10185   case ABIArgInfo::Indirect:
10186   case ABIArgInfo::IndirectAliased:
10187     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10188     Val = Address(Builder.CreateLoad(Val), ArgTy, TypeAlign);
10189     ArgSize = SlotSize;
10190     break;
10191   }
10192 
10193   // Increment the VAList.
10194   if (!ArgSize.isZero()) {
10195     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10196     Builder.CreateStore(APN.getPointer(), VAListAddr);
10197   }
10198 
10199   return Val;
10200 }
10201 
10202 /// During the expansion of a RecordType, an incomplete TypeString is placed
10203 /// into the cache as a means to identify and break recursion.
10204 /// If there is a Recursive encoding in the cache, it is swapped out and will
10205 /// be reinserted by removeIncomplete().
10206 /// All other types of encoding should have been used rather than arriving here.
10207 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10208                                     std::string StubEnc) {
10209   if (!ID)
10210     return;
10211   Entry &E = Map[ID];
10212   assert( (E.Str.empty() || E.State == Recursive) &&
10213          "Incorrectly use of addIncomplete");
10214   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10215   E.Swapped.swap(E.Str); // swap out the Recursive
10216   E.Str.swap(StubEnc);
10217   E.State = Incomplete;
10218   ++IncompleteCount;
10219 }
10220 
10221 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10222 /// must be removed from the cache.
10223 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10224 /// Returns true if the RecordType was defined recursively.
10225 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10226   if (!ID)
10227     return false;
10228   auto I = Map.find(ID);
10229   assert(I != Map.end() && "Entry not present");
10230   Entry &E = I->second;
10231   assert( (E.State == Incomplete ||
10232            E.State == IncompleteUsed) &&
10233          "Entry must be an incomplete type");
10234   bool IsRecursive = false;
10235   if (E.State == IncompleteUsed) {
10236     // We made use of our Incomplete encoding, thus we are recursive.
10237     IsRecursive = true;
10238     --IncompleteUsedCount;
10239   }
10240   if (E.Swapped.empty())
10241     Map.erase(I);
10242   else {
10243     // Swap the Recursive back.
10244     E.Swapped.swap(E.Str);
10245     E.Swapped.clear();
10246     E.State = Recursive;
10247   }
10248   --IncompleteCount;
10249   return IsRecursive;
10250 }
10251 
10252 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10253 /// Recursive (viz: all sub-members were expanded as fully as possible).
10254 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10255                                     bool IsRecursive) {
10256   if (!ID || IncompleteUsedCount)
10257     return; // No key or it is is an incomplete sub-type so don't add.
10258   Entry &E = Map[ID];
10259   if (IsRecursive && !E.Str.empty()) {
10260     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10261            "This is not the same Recursive entry");
10262     // The parent container was not recursive after all, so we could have used
10263     // this Recursive sub-member entry after all, but we assumed the worse when
10264     // we started viz: IncompleteCount!=0.
10265     return;
10266   }
10267   assert(E.Str.empty() && "Entry already present");
10268   E.Str = Str.str();
10269   E.State = IsRecursive? Recursive : NonRecursive;
10270 }
10271 
10272 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10273 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10274 /// encoding is Recursive, return an empty StringRef.
10275 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10276   if (!ID)
10277     return StringRef();   // We have no key.
10278   auto I = Map.find(ID);
10279   if (I == Map.end())
10280     return StringRef();   // We have no encoding.
10281   Entry &E = I->second;
10282   if (E.State == Recursive && IncompleteCount)
10283     return StringRef();   // We don't use Recursive encodings for member types.
10284 
10285   if (E.State == Incomplete) {
10286     // The incomplete type is being used to break out of recursion.
10287     E.State = IncompleteUsed;
10288     ++IncompleteUsedCount;
10289   }
10290   return E.Str;
10291 }
10292 
10293 /// The XCore ABI includes a type information section that communicates symbol
10294 /// type information to the linker. The linker uses this information to verify
10295 /// safety/correctness of things such as array bound and pointers et al.
10296 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10297 /// This type information (TypeString) is emitted into meta data for all global
10298 /// symbols: definitions, declarations, functions & variables.
10299 ///
10300 /// The TypeString carries type, qualifier, name, size & value details.
10301 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10302 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10303 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10304 ///
10305 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10306                           const CodeGen::CodeGenModule &CGM,
10307                           TypeStringCache &TSC);
10308 
10309 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10310 void XCoreTargetCodeGenInfo::emitTargetMD(
10311     const Decl *D, llvm::GlobalValue *GV,
10312     const CodeGen::CodeGenModule &CGM) const {
10313   SmallStringEnc Enc;
10314   if (getTypeString(Enc, D, CGM, TSC)) {
10315     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10316     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10317                                 llvm::MDString::get(Ctx, Enc.str())};
10318     llvm::NamedMDNode *MD =
10319       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10320     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10321   }
10322 }
10323 
10324 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10325     CodeGen::CodeGenModule &CGM,
10326     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10327   // Warning, new MangledDeclNames may be appended within this loop.
10328   // We rely on MapVector insertions adding new elements to the end
10329   // of the container.
10330   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10331     auto Val = *(MangledDeclNames.begin() + I);
10332     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10333     if (GV) {
10334       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10335       emitTargetMD(D, GV, CGM);
10336     }
10337   }
10338 }
10339 
10340 //===----------------------------------------------------------------------===//
10341 // Base ABI and target codegen info implementation common between SPIR and
10342 // SPIR-V.
10343 //===----------------------------------------------------------------------===//
10344 
10345 namespace {
10346 class CommonSPIRABIInfo : public DefaultABIInfo {
10347 public:
10348   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10349 
10350 private:
10351   void setCCs();
10352 };
10353 
10354 class SPIRVABIInfo : public CommonSPIRABIInfo {
10355 public:
10356   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10357   void computeInfo(CGFunctionInfo &FI) const override;
10358 
10359 private:
10360   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10361 };
10362 } // end anonymous namespace
10363 namespace {
10364 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10365 public:
10366   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10367       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10368   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10369       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10370 
10371   LangAS getASTAllocaAddressSpace() const override {
10372     return getLangASFromTargetAS(
10373         getABIInfo().getDataLayout().getAllocaAddrSpace());
10374   }
10375 
10376   unsigned getOpenCLKernelCallingConv() const override;
10377 };
10378 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10379 public:
10380   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10381       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10382   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10383 };
10384 } // End anonymous namespace.
10385 
10386 void CommonSPIRABIInfo::setCCs() {
10387   assert(getRuntimeCC() == llvm::CallingConv::C);
10388   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10389 }
10390 
10391 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10392   if (getContext().getLangOpts().CUDAIsDevice) {
10393     // Coerce pointer arguments with default address space to CrossWorkGroup
10394     // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the
10395     // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space.
10396     llvm::Type *LTy = CGT.ConvertType(Ty);
10397     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10398     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10399     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10400     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10401       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10402       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10403     }
10404   }
10405   return classifyArgumentType(Ty);
10406 }
10407 
10408 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10409   // The logic is same as in DefaultABIInfo with an exception on the kernel
10410   // arguments handling.
10411   llvm::CallingConv::ID CC = FI.getCallingConvention();
10412 
10413   if (!getCXXABI().classifyReturnType(FI))
10414     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10415 
10416   for (auto &I : FI.arguments()) {
10417     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10418       I.info = classifyKernelArgumentType(I.type);
10419     } else {
10420       I.info = classifyArgumentType(I.type);
10421     }
10422   }
10423 }
10424 
10425 namespace clang {
10426 namespace CodeGen {
10427 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10428   if (CGM.getTarget().getTriple().isSPIRV())
10429     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10430   else
10431     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10432 }
10433 }
10434 }
10435 
10436 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10437   return llvm::CallingConv::SPIR_KERNEL;
10438 }
10439 
10440 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10441     const FunctionType *&FT) const {
10442   // Convert HIP kernels to SPIR-V kernels.
10443   if (getABIInfo().getContext().getLangOpts().HIP) {
10444     FT = getABIInfo().getContext().adjustFunctionType(
10445         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10446     return;
10447   }
10448 }
10449 
10450 static bool appendType(SmallStringEnc &Enc, QualType QType,
10451                        const CodeGen::CodeGenModule &CGM,
10452                        TypeStringCache &TSC);
10453 
10454 /// Helper function for appendRecordType().
10455 /// Builds a SmallVector containing the encoded field types in declaration
10456 /// order.
10457 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10458                              const RecordDecl *RD,
10459                              const CodeGen::CodeGenModule &CGM,
10460                              TypeStringCache &TSC) {
10461   for (const auto *Field : RD->fields()) {
10462     SmallStringEnc Enc;
10463     Enc += "m(";
10464     Enc += Field->getName();
10465     Enc += "){";
10466     if (Field->isBitField()) {
10467       Enc += "b(";
10468       llvm::raw_svector_ostream OS(Enc);
10469       OS << Field->getBitWidthValue(CGM.getContext());
10470       Enc += ':';
10471     }
10472     if (!appendType(Enc, Field->getType(), CGM, TSC))
10473       return false;
10474     if (Field->isBitField())
10475       Enc += ')';
10476     Enc += '}';
10477     FE.emplace_back(!Field->getName().empty(), Enc);
10478   }
10479   return true;
10480 }
10481 
10482 /// Appends structure and union types to Enc and adds encoding to cache.
10483 /// Recursively calls appendType (via extractFieldType) for each field.
10484 /// Union types have their fields ordered according to the ABI.
10485 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10486                              const CodeGen::CodeGenModule &CGM,
10487                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10488   // Append the cached TypeString if we have one.
10489   StringRef TypeString = TSC.lookupStr(ID);
10490   if (!TypeString.empty()) {
10491     Enc += TypeString;
10492     return true;
10493   }
10494 
10495   // Start to emit an incomplete TypeString.
10496   size_t Start = Enc.size();
10497   Enc += (RT->isUnionType()? 'u' : 's');
10498   Enc += '(';
10499   if (ID)
10500     Enc += ID->getName();
10501   Enc += "){";
10502 
10503   // We collect all encoded fields and order as necessary.
10504   bool IsRecursive = false;
10505   const RecordDecl *RD = RT->getDecl()->getDefinition();
10506   if (RD && !RD->field_empty()) {
10507     // An incomplete TypeString stub is placed in the cache for this RecordType
10508     // so that recursive calls to this RecordType will use it whilst building a
10509     // complete TypeString for this RecordType.
10510     SmallVector<FieldEncoding, 16> FE;
10511     std::string StubEnc(Enc.substr(Start).str());
10512     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10513     TSC.addIncomplete(ID, std::move(StubEnc));
10514     if (!extractFieldType(FE, RD, CGM, TSC)) {
10515       (void) TSC.removeIncomplete(ID);
10516       return false;
10517     }
10518     IsRecursive = TSC.removeIncomplete(ID);
10519     // The ABI requires unions to be sorted but not structures.
10520     // See FieldEncoding::operator< for sort algorithm.
10521     if (RT->isUnionType())
10522       llvm::sort(FE);
10523     // We can now complete the TypeString.
10524     unsigned E = FE.size();
10525     for (unsigned I = 0; I != E; ++I) {
10526       if (I)
10527         Enc += ',';
10528       Enc += FE[I].str();
10529     }
10530   }
10531   Enc += '}';
10532   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10533   return true;
10534 }
10535 
10536 /// Appends enum types to Enc and adds the encoding to the cache.
10537 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10538                            TypeStringCache &TSC,
10539                            const IdentifierInfo *ID) {
10540   // Append the cached TypeString if we have one.
10541   StringRef TypeString = TSC.lookupStr(ID);
10542   if (!TypeString.empty()) {
10543     Enc += TypeString;
10544     return true;
10545   }
10546 
10547   size_t Start = Enc.size();
10548   Enc += "e(";
10549   if (ID)
10550     Enc += ID->getName();
10551   Enc += "){";
10552 
10553   // We collect all encoded enumerations and order them alphanumerically.
10554   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10555     SmallVector<FieldEncoding, 16> FE;
10556     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10557          ++I) {
10558       SmallStringEnc EnumEnc;
10559       EnumEnc += "m(";
10560       EnumEnc += I->getName();
10561       EnumEnc += "){";
10562       I->getInitVal().toString(EnumEnc);
10563       EnumEnc += '}';
10564       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10565     }
10566     llvm::sort(FE);
10567     unsigned E = FE.size();
10568     for (unsigned I = 0; I != E; ++I) {
10569       if (I)
10570         Enc += ',';
10571       Enc += FE[I].str();
10572     }
10573   }
10574   Enc += '}';
10575   TSC.addIfComplete(ID, Enc.substr(Start), false);
10576   return true;
10577 }
10578 
10579 /// Appends type's qualifier to Enc.
10580 /// This is done prior to appending the type's encoding.
10581 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10582   // Qualifiers are emitted in alphabetical order.
10583   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10584   int Lookup = 0;
10585   if (QT.isConstQualified())
10586     Lookup += 1<<0;
10587   if (QT.isRestrictQualified())
10588     Lookup += 1<<1;
10589   if (QT.isVolatileQualified())
10590     Lookup += 1<<2;
10591   Enc += Table[Lookup];
10592 }
10593 
10594 /// Appends built-in types to Enc.
10595 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10596   const char *EncType;
10597   switch (BT->getKind()) {
10598     case BuiltinType::Void:
10599       EncType = "0";
10600       break;
10601     case BuiltinType::Bool:
10602       EncType = "b";
10603       break;
10604     case BuiltinType::Char_U:
10605       EncType = "uc";
10606       break;
10607     case BuiltinType::UChar:
10608       EncType = "uc";
10609       break;
10610     case BuiltinType::SChar:
10611       EncType = "sc";
10612       break;
10613     case BuiltinType::UShort:
10614       EncType = "us";
10615       break;
10616     case BuiltinType::Short:
10617       EncType = "ss";
10618       break;
10619     case BuiltinType::UInt:
10620       EncType = "ui";
10621       break;
10622     case BuiltinType::Int:
10623       EncType = "si";
10624       break;
10625     case BuiltinType::ULong:
10626       EncType = "ul";
10627       break;
10628     case BuiltinType::Long:
10629       EncType = "sl";
10630       break;
10631     case BuiltinType::ULongLong:
10632       EncType = "ull";
10633       break;
10634     case BuiltinType::LongLong:
10635       EncType = "sll";
10636       break;
10637     case BuiltinType::Float:
10638       EncType = "ft";
10639       break;
10640     case BuiltinType::Double:
10641       EncType = "d";
10642       break;
10643     case BuiltinType::LongDouble:
10644       EncType = "ld";
10645       break;
10646     default:
10647       return false;
10648   }
10649   Enc += EncType;
10650   return true;
10651 }
10652 
10653 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10654 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10655                               const CodeGen::CodeGenModule &CGM,
10656                               TypeStringCache &TSC) {
10657   Enc += "p(";
10658   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10659     return false;
10660   Enc += ')';
10661   return true;
10662 }
10663 
10664 /// Appends array encoding to Enc before calling appendType for the element.
10665 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10666                             const ArrayType *AT,
10667                             const CodeGen::CodeGenModule &CGM,
10668                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10669   if (AT->getSizeModifier() != ArrayType::Normal)
10670     return false;
10671   Enc += "a(";
10672   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10673     CAT->getSize().toStringUnsigned(Enc);
10674   else
10675     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10676   Enc += ':';
10677   // The Qualifiers should be attached to the type rather than the array.
10678   appendQualifier(Enc, QT);
10679   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10680     return false;
10681   Enc += ')';
10682   return true;
10683 }
10684 
10685 /// Appends a function encoding to Enc, calling appendType for the return type
10686 /// and the arguments.
10687 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10688                              const CodeGen::CodeGenModule &CGM,
10689                              TypeStringCache &TSC) {
10690   Enc += "f{";
10691   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10692     return false;
10693   Enc += "}(";
10694   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10695     // N.B. we are only interested in the adjusted param types.
10696     auto I = FPT->param_type_begin();
10697     auto E = FPT->param_type_end();
10698     if (I != E) {
10699       do {
10700         if (!appendType(Enc, *I, CGM, TSC))
10701           return false;
10702         ++I;
10703         if (I != E)
10704           Enc += ',';
10705       } while (I != E);
10706       if (FPT->isVariadic())
10707         Enc += ",va";
10708     } else {
10709       if (FPT->isVariadic())
10710         Enc += "va";
10711       else
10712         Enc += '0';
10713     }
10714   }
10715   Enc += ')';
10716   return true;
10717 }
10718 
10719 /// Handles the type's qualifier before dispatching a call to handle specific
10720 /// type encodings.
10721 static bool appendType(SmallStringEnc &Enc, QualType QType,
10722                        const CodeGen::CodeGenModule &CGM,
10723                        TypeStringCache &TSC) {
10724 
10725   QualType QT = QType.getCanonicalType();
10726 
10727   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10728     // The Qualifiers should be attached to the type rather than the array.
10729     // Thus we don't call appendQualifier() here.
10730     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10731 
10732   appendQualifier(Enc, QT);
10733 
10734   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10735     return appendBuiltinType(Enc, BT);
10736 
10737   if (const PointerType *PT = QT->getAs<PointerType>())
10738     return appendPointerType(Enc, PT, CGM, TSC);
10739 
10740   if (const EnumType *ET = QT->getAs<EnumType>())
10741     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10742 
10743   if (const RecordType *RT = QT->getAsStructureType())
10744     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10745 
10746   if (const RecordType *RT = QT->getAsUnionType())
10747     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10748 
10749   if (const FunctionType *FT = QT->getAs<FunctionType>())
10750     return appendFunctionType(Enc, FT, CGM, TSC);
10751 
10752   return false;
10753 }
10754 
10755 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10756                           const CodeGen::CodeGenModule &CGM,
10757                           TypeStringCache &TSC) {
10758   if (!D)
10759     return false;
10760 
10761   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10762     if (FD->getLanguageLinkage() != CLanguageLinkage)
10763       return false;
10764     return appendType(Enc, FD->getType(), CGM, TSC);
10765   }
10766 
10767   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10768     if (VD->getLanguageLinkage() != CLanguageLinkage)
10769       return false;
10770     QualType QT = VD->getType().getCanonicalType();
10771     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10772       // Global ArrayTypes are given a size of '*' if the size is unknown.
10773       // The Qualifiers should be attached to the type rather than the array.
10774       // Thus we don't call appendQualifier() here.
10775       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10776     }
10777     return appendType(Enc, QT, CGM, TSC);
10778   }
10779   return false;
10780 }
10781 
10782 //===----------------------------------------------------------------------===//
10783 // RISCV ABI Implementation
10784 //===----------------------------------------------------------------------===//
10785 
10786 namespace {
10787 class RISCVABIInfo : public DefaultABIInfo {
10788 private:
10789   // Size of the integer ('x') registers in bits.
10790   unsigned XLen;
10791   // Size of the floating point ('f') registers in bits. Note that the target
10792   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10793   // with soft float ABI has FLen==0).
10794   unsigned FLen;
10795   static const int NumArgGPRs = 8;
10796   static const int NumArgFPRs = 8;
10797   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10798                                       llvm::Type *&Field1Ty,
10799                                       CharUnits &Field1Off,
10800                                       llvm::Type *&Field2Ty,
10801                                       CharUnits &Field2Off) const;
10802 
10803 public:
10804   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10805       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10806 
10807   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10808   // non-virtual, but computeInfo is virtual, so we overload it.
10809   void computeInfo(CGFunctionInfo &FI) const override;
10810 
10811   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10812                                   int &ArgFPRsLeft) const;
10813   ABIArgInfo classifyReturnType(QualType RetTy) const;
10814 
10815   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10816                     QualType Ty) const override;
10817 
10818   ABIArgInfo extendType(QualType Ty) const;
10819 
10820   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10821                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10822                                 CharUnits &Field2Off, int &NeededArgGPRs,
10823                                 int &NeededArgFPRs) const;
10824   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10825                                                CharUnits Field1Off,
10826                                                llvm::Type *Field2Ty,
10827                                                CharUnits Field2Off) const;
10828 };
10829 } // end anonymous namespace
10830 
10831 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10832   QualType RetTy = FI.getReturnType();
10833   if (!getCXXABI().classifyReturnType(FI))
10834     FI.getReturnInfo() = classifyReturnType(RetTy);
10835 
10836   // IsRetIndirect is true if classifyArgumentType indicated the value should
10837   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10838   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10839   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10840   // list and pass indirectly on RV32.
10841   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10842   if (!IsRetIndirect && RetTy->isScalarType() &&
10843       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10844     if (RetTy->isComplexType() && FLen) {
10845       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10846       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10847     } else {
10848       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10849       IsRetIndirect = true;
10850     }
10851   }
10852 
10853   // We must track the number of GPRs used in order to conform to the RISC-V
10854   // ABI, as integer scalars passed in registers should have signext/zeroext
10855   // when promoted, but are anyext if passed on the stack. As GPR usage is
10856   // different for variadic arguments, we must also track whether we are
10857   // examining a vararg or not.
10858   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10859   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10860   int NumFixedArgs = FI.getNumRequiredArgs();
10861 
10862   int ArgNum = 0;
10863   for (auto &ArgInfo : FI.arguments()) {
10864     bool IsFixed = ArgNum < NumFixedArgs;
10865     ArgInfo.info =
10866         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10867     ArgNum++;
10868   }
10869 }
10870 
10871 // Returns true if the struct is a potential candidate for the floating point
10872 // calling convention. If this function returns true, the caller is
10873 // responsible for checking that if there is only a single field then that
10874 // field is a float.
10875 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10876                                                   llvm::Type *&Field1Ty,
10877                                                   CharUnits &Field1Off,
10878                                                   llvm::Type *&Field2Ty,
10879                                                   CharUnits &Field2Off) const {
10880   bool IsInt = Ty->isIntegralOrEnumerationType();
10881   bool IsFloat = Ty->isRealFloatingType();
10882 
10883   if (IsInt || IsFloat) {
10884     uint64_t Size = getContext().getTypeSize(Ty);
10885     if (IsInt && Size > XLen)
10886       return false;
10887     // Can't be eligible if larger than the FP registers. Half precision isn't
10888     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10889     // default to the integer ABI in that case.
10890     if (IsFloat && (Size > FLen || Size < 32))
10891       return false;
10892     // Can't be eligible if an integer type was already found (int+int pairs
10893     // are not eligible).
10894     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10895       return false;
10896     if (!Field1Ty) {
10897       Field1Ty = CGT.ConvertType(Ty);
10898       Field1Off = CurOff;
10899       return true;
10900     }
10901     if (!Field2Ty) {
10902       Field2Ty = CGT.ConvertType(Ty);
10903       Field2Off = CurOff;
10904       return true;
10905     }
10906     return false;
10907   }
10908 
10909   if (auto CTy = Ty->getAs<ComplexType>()) {
10910     if (Field1Ty)
10911       return false;
10912     QualType EltTy = CTy->getElementType();
10913     if (getContext().getTypeSize(EltTy) > FLen)
10914       return false;
10915     Field1Ty = CGT.ConvertType(EltTy);
10916     Field1Off = CurOff;
10917     Field2Ty = Field1Ty;
10918     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10919     return true;
10920   }
10921 
10922   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10923     uint64_t ArraySize = ATy->getSize().getZExtValue();
10924     QualType EltTy = ATy->getElementType();
10925     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10926     for (uint64_t i = 0; i < ArraySize; ++i) {
10927       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10928                                                 Field1Off, Field2Ty, Field2Off);
10929       if (!Ret)
10930         return false;
10931       CurOff += EltSize;
10932     }
10933     return true;
10934   }
10935 
10936   if (const auto *RTy = Ty->getAs<RecordType>()) {
10937     // Structures with either a non-trivial destructor or a non-trivial
10938     // copy constructor are not eligible for the FP calling convention.
10939     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10940       return false;
10941     if (isEmptyRecord(getContext(), Ty, true))
10942       return true;
10943     const RecordDecl *RD = RTy->getDecl();
10944     // Unions aren't eligible unless they're empty (which is caught above).
10945     if (RD->isUnion())
10946       return false;
10947     int ZeroWidthBitFieldCount = 0;
10948     for (const FieldDecl *FD : RD->fields()) {
10949       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10950       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10951       QualType QTy = FD->getType();
10952       if (FD->isBitField()) {
10953         unsigned BitWidth = FD->getBitWidthValue(getContext());
10954         // Allow a bitfield with a type greater than XLen as long as the
10955         // bitwidth is XLen or less.
10956         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10957           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10958         if (BitWidth == 0) {
10959           ZeroWidthBitFieldCount++;
10960           continue;
10961         }
10962       }
10963 
10964       bool Ret = detectFPCCEligibleStructHelper(
10965           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10966           Field1Ty, Field1Off, Field2Ty, Field2Off);
10967       if (!Ret)
10968         return false;
10969 
10970       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10971       // or int+fp structs, but are ignored for a struct with an fp field and
10972       // any number of zero-width bitfields.
10973       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10974         return false;
10975     }
10976     return Field1Ty != nullptr;
10977   }
10978 
10979   return false;
10980 }
10981 
10982 // Determine if a struct is eligible for passing according to the floating
10983 // point calling convention (i.e., when flattened it contains a single fp
10984 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10985 // NeededArgGPRs are incremented appropriately.
10986 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10987                                             CharUnits &Field1Off,
10988                                             llvm::Type *&Field2Ty,
10989                                             CharUnits &Field2Off,
10990                                             int &NeededArgGPRs,
10991                                             int &NeededArgFPRs) const {
10992   Field1Ty = nullptr;
10993   Field2Ty = nullptr;
10994   NeededArgGPRs = 0;
10995   NeededArgFPRs = 0;
10996   bool IsCandidate = detectFPCCEligibleStructHelper(
10997       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10998   // Not really a candidate if we have a single int but no float.
10999   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
11000     return false;
11001   if (!IsCandidate)
11002     return false;
11003   if (Field1Ty && Field1Ty->isFloatingPointTy())
11004     NeededArgFPRs++;
11005   else if (Field1Ty)
11006     NeededArgGPRs++;
11007   if (Field2Ty && Field2Ty->isFloatingPointTy())
11008     NeededArgFPRs++;
11009   else if (Field2Ty)
11010     NeededArgGPRs++;
11011   return true;
11012 }
11013 
11014 // Call getCoerceAndExpand for the two-element flattened struct described by
11015 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
11016 // appropriate coerceToType and unpaddedCoerceToType.
11017 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
11018     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
11019     CharUnits Field2Off) const {
11020   SmallVector<llvm::Type *, 3> CoerceElts;
11021   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
11022   if (!Field1Off.isZero())
11023     CoerceElts.push_back(llvm::ArrayType::get(
11024         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
11025 
11026   CoerceElts.push_back(Field1Ty);
11027   UnpaddedCoerceElts.push_back(Field1Ty);
11028 
11029   if (!Field2Ty) {
11030     return ABIArgInfo::getCoerceAndExpand(
11031         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
11032         UnpaddedCoerceElts[0]);
11033   }
11034 
11035   CharUnits Field2Align =
11036       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
11037   CharUnits Field1End = Field1Off +
11038       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
11039   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
11040 
11041   CharUnits Padding = CharUnits::Zero();
11042   if (Field2Off > Field2OffNoPadNoPack)
11043     Padding = Field2Off - Field2OffNoPadNoPack;
11044   else if (Field2Off != Field2Align && Field2Off > Field1End)
11045     Padding = Field2Off - Field1End;
11046 
11047   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
11048 
11049   if (!Padding.isZero())
11050     CoerceElts.push_back(llvm::ArrayType::get(
11051         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
11052 
11053   CoerceElts.push_back(Field2Ty);
11054   UnpaddedCoerceElts.push_back(Field2Ty);
11055 
11056   auto CoerceToType =
11057       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
11058   auto UnpaddedCoerceToType =
11059       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
11060 
11061   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
11062 }
11063 
11064 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
11065                                               int &ArgGPRsLeft,
11066                                               int &ArgFPRsLeft) const {
11067   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
11068   Ty = useFirstFieldIfTransparentUnion(Ty);
11069 
11070   // Structures with either a non-trivial destructor or a non-trivial
11071   // copy constructor are always passed indirectly.
11072   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11073     if (ArgGPRsLeft)
11074       ArgGPRsLeft -= 1;
11075     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11076                                            CGCXXABI::RAA_DirectInMemory);
11077   }
11078 
11079   // Ignore empty structs/unions.
11080   if (isEmptyRecord(getContext(), Ty, true))
11081     return ABIArgInfo::getIgnore();
11082 
11083   uint64_t Size = getContext().getTypeSize(Ty);
11084 
11085   // Pass floating point values via FPRs if possible.
11086   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11087       FLen >= Size && ArgFPRsLeft) {
11088     ArgFPRsLeft--;
11089     return ABIArgInfo::getDirect();
11090   }
11091 
11092   // Complex types for the hard float ABI must be passed direct rather than
11093   // using CoerceAndExpand.
11094   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11095     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11096     if (getContext().getTypeSize(EltTy) <= FLen) {
11097       ArgFPRsLeft -= 2;
11098       return ABIArgInfo::getDirect();
11099     }
11100   }
11101 
11102   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11103     llvm::Type *Field1Ty = nullptr;
11104     llvm::Type *Field2Ty = nullptr;
11105     CharUnits Field1Off = CharUnits::Zero();
11106     CharUnits Field2Off = CharUnits::Zero();
11107     int NeededArgGPRs = 0;
11108     int NeededArgFPRs = 0;
11109     bool IsCandidate =
11110         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11111                                  NeededArgGPRs, NeededArgFPRs);
11112     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11113         NeededArgFPRs <= ArgFPRsLeft) {
11114       ArgGPRsLeft -= NeededArgGPRs;
11115       ArgFPRsLeft -= NeededArgFPRs;
11116       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11117                                                Field2Off);
11118     }
11119   }
11120 
11121   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11122   bool MustUseStack = false;
11123   // Determine the number of GPRs needed to pass the current argument
11124   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11125   // register pairs, so may consume 3 registers.
11126   int NeededArgGPRs = 1;
11127   if (!IsFixed && NeededAlign == 2 * XLen)
11128     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11129   else if (Size > XLen && Size <= 2 * XLen)
11130     NeededArgGPRs = 2;
11131 
11132   if (NeededArgGPRs > ArgGPRsLeft) {
11133     MustUseStack = true;
11134     NeededArgGPRs = ArgGPRsLeft;
11135   }
11136 
11137   ArgGPRsLeft -= NeededArgGPRs;
11138 
11139   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11140     // Treat an enum type as its underlying type.
11141     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11142       Ty = EnumTy->getDecl()->getIntegerType();
11143 
11144     // All integral types are promoted to XLen width, unless passed on the
11145     // stack.
11146     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11147       return extendType(Ty);
11148     }
11149 
11150     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11151       if (EIT->getNumBits() < XLen && !MustUseStack)
11152         return extendType(Ty);
11153       if (EIT->getNumBits() > 128 ||
11154           (!getContext().getTargetInfo().hasInt128Type() &&
11155            EIT->getNumBits() > 64))
11156         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11157     }
11158 
11159     return ABIArgInfo::getDirect();
11160   }
11161 
11162   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11163   // so coerce to integers.
11164   if (Size <= 2 * XLen) {
11165     unsigned Alignment = getContext().getTypeAlign(Ty);
11166 
11167     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11168     // required, and a 2-element XLen array if only XLen alignment is required.
11169     if (Size <= XLen) {
11170       return ABIArgInfo::getDirect(
11171           llvm::IntegerType::get(getVMContext(), XLen));
11172     } else if (Alignment == 2 * XLen) {
11173       return ABIArgInfo::getDirect(
11174           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11175     } else {
11176       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11177           llvm::IntegerType::get(getVMContext(), XLen), 2));
11178     }
11179   }
11180   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11181 }
11182 
11183 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11184   if (RetTy->isVoidType())
11185     return ABIArgInfo::getIgnore();
11186 
11187   int ArgGPRsLeft = 2;
11188   int ArgFPRsLeft = FLen ? 2 : 0;
11189 
11190   // The rules for return and argument types are the same, so defer to
11191   // classifyArgumentType.
11192   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11193                               ArgFPRsLeft);
11194 }
11195 
11196 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11197                                 QualType Ty) const {
11198   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11199 
11200   // Empty records are ignored for parameter passing purposes.
11201   if (isEmptyRecord(getContext(), Ty, true)) {
11202     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
11203                            getVAListElementType(CGF), SlotSize);
11204     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11205     return Addr;
11206   }
11207 
11208   auto TInfo = getContext().getTypeInfoInChars(Ty);
11209 
11210   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11211   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11212 
11213   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11214                           SlotSize, /*AllowHigherAlign=*/true);
11215 }
11216 
11217 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11218   int TySize = getContext().getTypeSize(Ty);
11219   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11220   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11221     return ABIArgInfo::getSignExtend(Ty);
11222   return ABIArgInfo::getExtend(Ty);
11223 }
11224 
11225 namespace {
11226 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11227 public:
11228   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11229                          unsigned FLen)
11230       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11231 
11232   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11233                            CodeGen::CodeGenModule &CGM) const override {
11234     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11235     if (!FD) return;
11236 
11237     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11238     if (!Attr)
11239       return;
11240 
11241     const char *Kind;
11242     switch (Attr->getInterrupt()) {
11243     case RISCVInterruptAttr::user: Kind = "user"; break;
11244     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11245     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11246     }
11247 
11248     auto *Fn = cast<llvm::Function>(GV);
11249 
11250     Fn->addFnAttr("interrupt", Kind);
11251   }
11252 };
11253 } // namespace
11254 
11255 //===----------------------------------------------------------------------===//
11256 // VE ABI Implementation.
11257 //
11258 namespace {
11259 class VEABIInfo : public DefaultABIInfo {
11260 public:
11261   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11262 
11263 private:
11264   ABIArgInfo classifyReturnType(QualType RetTy) const;
11265   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11266   void computeInfo(CGFunctionInfo &FI) const override;
11267 };
11268 } // end anonymous namespace
11269 
11270 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11271   if (Ty->isAnyComplexType())
11272     return ABIArgInfo::getDirect();
11273   uint64_t Size = getContext().getTypeSize(Ty);
11274   if (Size < 64 && Ty->isIntegerType())
11275     return ABIArgInfo::getExtend(Ty);
11276   return DefaultABIInfo::classifyReturnType(Ty);
11277 }
11278 
11279 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11280   if (Ty->isAnyComplexType())
11281     return ABIArgInfo::getDirect();
11282   uint64_t Size = getContext().getTypeSize(Ty);
11283   if (Size < 64 && Ty->isIntegerType())
11284     return ABIArgInfo::getExtend(Ty);
11285   return DefaultABIInfo::classifyArgumentType(Ty);
11286 }
11287 
11288 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11289   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11290   for (auto &Arg : FI.arguments())
11291     Arg.info = classifyArgumentType(Arg.type);
11292 }
11293 
11294 namespace {
11295 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11296 public:
11297   VETargetCodeGenInfo(CodeGenTypes &CGT)
11298       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11299   // VE ABI requires the arguments of variadic and prototype-less functions
11300   // are passed in both registers and memory.
11301   bool isNoProtoCallVariadic(const CallArgList &args,
11302                              const FunctionNoProtoType *fnType) const override {
11303     return true;
11304   }
11305 };
11306 } // end anonymous namespace
11307 
11308 //===----------------------------------------------------------------------===//
11309 // Driver code
11310 //===----------------------------------------------------------------------===//
11311 
11312 bool CodeGenModule::supportsCOMDAT() const {
11313   return getTriple().supportsCOMDAT();
11314 }
11315 
11316 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11317   if (TheTargetCodeGenInfo)
11318     return *TheTargetCodeGenInfo;
11319 
11320   // Helper to set the unique_ptr while still keeping the return value.
11321   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11322     this->TheTargetCodeGenInfo.reset(P);
11323     return *P;
11324   };
11325 
11326   const llvm::Triple &Triple = getTarget().getTriple();
11327   switch (Triple.getArch()) {
11328   default:
11329     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11330 
11331   case llvm::Triple::le32:
11332     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11333   case llvm::Triple::m68k:
11334     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11335   case llvm::Triple::mips:
11336   case llvm::Triple::mipsel:
11337     if (Triple.getOS() == llvm::Triple::NaCl)
11338       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11339     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11340 
11341   case llvm::Triple::mips64:
11342   case llvm::Triple::mips64el:
11343     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11344 
11345   case llvm::Triple::avr: {
11346     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
11347     // on avrtiny. For passing return value, R18~R25 are used on avr, and
11348     // R22~R25 are used on avrtiny.
11349     unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18;
11350     unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8;
11351     return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR));
11352   }
11353 
11354   case llvm::Triple::aarch64:
11355   case llvm::Triple::aarch64_32:
11356   case llvm::Triple::aarch64_be: {
11357     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11358     if (getTarget().getABI() == "darwinpcs")
11359       Kind = AArch64ABIInfo::DarwinPCS;
11360     else if (Triple.isOSWindows())
11361       return SetCGInfo(
11362           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11363 
11364     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11365   }
11366 
11367   case llvm::Triple::wasm32:
11368   case llvm::Triple::wasm64: {
11369     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11370     if (getTarget().getABI() == "experimental-mv")
11371       Kind = WebAssemblyABIInfo::ExperimentalMV;
11372     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11373   }
11374 
11375   case llvm::Triple::arm:
11376   case llvm::Triple::armeb:
11377   case llvm::Triple::thumb:
11378   case llvm::Triple::thumbeb: {
11379     if (Triple.getOS() == llvm::Triple::Win32) {
11380       return SetCGInfo(
11381           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11382     }
11383 
11384     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11385     StringRef ABIStr = getTarget().getABI();
11386     if (ABIStr == "apcs-gnu")
11387       Kind = ARMABIInfo::APCS;
11388     else if (ABIStr == "aapcs16")
11389       Kind = ARMABIInfo::AAPCS16_VFP;
11390     else if (CodeGenOpts.FloatABI == "hard" ||
11391              (CodeGenOpts.FloatABI != "soft" &&
11392               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11393                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11394                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11395       Kind = ARMABIInfo::AAPCS_VFP;
11396 
11397     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11398   }
11399 
11400   case llvm::Triple::ppc: {
11401     if (Triple.isOSAIX())
11402       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11403 
11404     bool IsSoftFloat =
11405         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11406     bool RetSmallStructInRegABI =
11407         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11408     return SetCGInfo(
11409         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11410   }
11411   case llvm::Triple::ppcle: {
11412     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11413     bool RetSmallStructInRegABI =
11414         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11415     return SetCGInfo(
11416         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11417   }
11418   case llvm::Triple::ppc64:
11419     if (Triple.isOSAIX())
11420       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11421 
11422     if (Triple.isOSBinFormatELF()) {
11423       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11424       if (getTarget().getABI() == "elfv2")
11425         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11426       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11427 
11428       return SetCGInfo(
11429           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11430     }
11431     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11432   case llvm::Triple::ppc64le: {
11433     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11434     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11435     if (getTarget().getABI() == "elfv1")
11436       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11437     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11438 
11439     return SetCGInfo(
11440         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11441   }
11442 
11443   case llvm::Triple::nvptx:
11444   case llvm::Triple::nvptx64:
11445     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11446 
11447   case llvm::Triple::msp430:
11448     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11449 
11450   case llvm::Triple::riscv32:
11451   case llvm::Triple::riscv64: {
11452     StringRef ABIStr = getTarget().getABI();
11453     unsigned XLen = getTarget().getPointerWidth(0);
11454     unsigned ABIFLen = 0;
11455     if (ABIStr.endswith("f"))
11456       ABIFLen = 32;
11457     else if (ABIStr.endswith("d"))
11458       ABIFLen = 64;
11459     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11460   }
11461 
11462   case llvm::Triple::systemz: {
11463     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11464     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11465     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11466   }
11467 
11468   case llvm::Triple::tce:
11469   case llvm::Triple::tcele:
11470     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11471 
11472   case llvm::Triple::x86: {
11473     bool IsDarwinVectorABI = Triple.isOSDarwin();
11474     bool RetSmallStructInRegABI =
11475         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11476     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11477 
11478     if (Triple.getOS() == llvm::Triple::Win32) {
11479       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11480           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11481           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11482     } else {
11483       return SetCGInfo(new X86_32TargetCodeGenInfo(
11484           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11485           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11486           CodeGenOpts.FloatABI == "soft"));
11487     }
11488   }
11489 
11490   case llvm::Triple::x86_64: {
11491     StringRef ABI = getTarget().getABI();
11492     X86AVXABILevel AVXLevel =
11493         (ABI == "avx512"
11494              ? X86AVXABILevel::AVX512
11495              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11496 
11497     switch (Triple.getOS()) {
11498     case llvm::Triple::Win32:
11499       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11500     default:
11501       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11502     }
11503   }
11504   case llvm::Triple::hexagon:
11505     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11506   case llvm::Triple::lanai:
11507     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11508   case llvm::Triple::r600:
11509     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11510   case llvm::Triple::amdgcn:
11511     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11512   case llvm::Triple::sparc:
11513     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11514   case llvm::Triple::sparcv9:
11515     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11516   case llvm::Triple::xcore:
11517     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11518   case llvm::Triple::arc:
11519     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11520   case llvm::Triple::spir:
11521   case llvm::Triple::spir64:
11522     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11523   case llvm::Triple::spirv32:
11524   case llvm::Triple::spirv64:
11525     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11526   case llvm::Triple::ve:
11527     return SetCGInfo(new VETargetCodeGenInfo(Types));
11528   }
11529 }
11530 
11531 /// Create an OpenCL kernel for an enqueued block.
11532 ///
11533 /// The kernel has the same function type as the block invoke function. Its
11534 /// name is the name of the block invoke function postfixed with "_kernel".
11535 /// It simply calls the block invoke function then returns.
11536 llvm::Function *
11537 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11538                                              llvm::Function *Invoke,
11539                                              llvm::Type *BlockTy) const {
11540   auto *InvokeFT = Invoke->getFunctionType();
11541   auto &C = CGF.getLLVMContext();
11542   std::string Name = Invoke->getName().str() + "_kernel";
11543   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C),
11544                                      InvokeFT->params(), false);
11545   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11546                                    &CGF.CGM.getModule());
11547   auto IP = CGF.Builder.saveIP();
11548   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11549   auto &Builder = CGF.Builder;
11550   Builder.SetInsertPoint(BB);
11551   llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args()));
11552   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11553   call->setCallingConv(Invoke->getCallingConv());
11554   Builder.CreateRetVoid();
11555   Builder.restoreIP(IP);
11556   return F;
11557 }
11558 
11559 /// Create an OpenCL kernel for an enqueued block.
11560 ///
11561 /// The type of the first argument (the block literal) is the struct type
11562 /// of the block literal instead of a pointer type. The first argument
11563 /// (block literal) is passed directly by value to the kernel. The kernel
11564 /// allocates the same type of struct on stack and stores the block literal
11565 /// to it and passes its pointer to the block invoke function. The kernel
11566 /// has "enqueued-block" function attribute and kernel argument metadata.
11567 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11568     CodeGenFunction &CGF, llvm::Function *Invoke,
11569     llvm::Type *BlockTy) const {
11570   auto &Builder = CGF.Builder;
11571   auto &C = CGF.getLLVMContext();
11572 
11573   auto *InvokeFT = Invoke->getFunctionType();
11574   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11575   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11576   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11577   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11578   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11579   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11580   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11581 
11582   ArgTys.push_back(BlockTy);
11583   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11584   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11585   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11586   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11587   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11588   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11589   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11590     ArgTys.push_back(InvokeFT->getParamType(I));
11591     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11592     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11593     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11594     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11595     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11596     ArgNames.push_back(
11597         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11598   }
11599   std::string Name = Invoke->getName().str() + "_kernel";
11600   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11601   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11602                                    &CGF.CGM.getModule());
11603   F->addFnAttr("enqueued-block");
11604   auto IP = CGF.Builder.saveIP();
11605   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11606   Builder.SetInsertPoint(BB);
11607   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11608   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11609   BlockPtr->setAlignment(BlockAlign);
11610   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11611   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11612   llvm::SmallVector<llvm::Value *, 2> Args;
11613   Args.push_back(Cast);
11614   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11615     Args.push_back(I);
11616   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11617   call->setCallingConv(Invoke->getCallingConv());
11618   Builder.CreateRetVoid();
11619   Builder.restoreIP(IP);
11620 
11621   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11622   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11623   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11624   F->setMetadata("kernel_arg_base_type",
11625                  llvm::MDNode::get(C, ArgBaseTypeNames));
11626   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11627   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11628     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11629 
11630   return F;
11631 }
11632