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/CodeGenOptions.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "clang/CodeGen/SwiftCallingConv.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IntrinsicsNVPTX.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm> // std::sort
35 
36 using namespace clang;
37 using namespace CodeGen;
38 
39 // Helper for coercing an aggregate argument or return value into an integer
40 // array of the same size (including padding) and alignment.  This alternate
41 // coercion happens only for the RenderScript ABI and can be removed after
42 // runtimes that rely on it are no longer supported.
43 //
44 // RenderScript assumes that the size of the argument / return value in the IR
45 // is the same as the size of the corresponding qualified type. This helper
46 // coerces the aggregate type into an array of the same size (including
47 // padding).  This coercion is used in lieu of expansion of struct members or
48 // other canonical coercions that return a coerced-type of larger size.
49 //
50 // Ty          - The argument / return value type
51 // Context     - The associated ASTContext
52 // LLVMContext - The associated LLVMContext
53 static ABIArgInfo coerceToIntArray(QualType Ty,
54                                    ASTContext &Context,
55                                    llvm::LLVMContext &LLVMContext) {
56   // Alignment and Size are measured in bits.
57   const uint64_t Size = Context.getTypeSize(Ty);
58   const uint64_t Alignment = Context.getTypeAlign(Ty);
59   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
60   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
61   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
62 }
63 
64 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
65                                llvm::Value *Array,
66                                llvm::Value *Value,
67                                unsigned FirstIndex,
68                                unsigned LastIndex) {
69   // Alternatively, we could emit this as a loop in the source.
70   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
71     llvm::Value *Cell =
72         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
73     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
74   }
75 }
76 
77 static bool isAggregateTypeForABI(QualType T) {
78   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
79          T->isMemberFunctionPointerType();
80 }
81 
82 ABIArgInfo
83 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
84                                  llvm::Type *Padding) const {
85   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
86                                  ByRef, Realign, Padding);
87 }
88 
89 ABIArgInfo
90 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
91   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
92                                       /*ByRef*/ false, Realign);
93 }
94 
95 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
96                              QualType Ty) const {
97   return Address::invalid();
98 }
99 
100 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
101   if (Ty->isPromotableIntegerType())
102     return true;
103 
104   if (const auto *EIT = Ty->getAs<ExtIntType>())
105     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
106       return true;
107 
108   return false;
109 }
110 
111 ABIInfo::~ABIInfo() {}
112 
113 /// Does the given lowering require more than the given number of
114 /// registers when expanded?
115 ///
116 /// This is intended to be the basis of a reasonable basic implementation
117 /// of should{Pass,Return}IndirectlyForSwift.
118 ///
119 /// For most targets, a limit of four total registers is reasonable; this
120 /// limits the amount of code required in order to move around the value
121 /// in case it wasn't produced immediately prior to the call by the caller
122 /// (or wasn't produced in exactly the right registers) or isn't used
123 /// immediately within the callee.  But some targets may need to further
124 /// limit the register count due to an inability to support that many
125 /// return registers.
126 static bool occupiesMoreThan(CodeGenTypes &cgt,
127                              ArrayRef<llvm::Type*> scalarTypes,
128                              unsigned maxAllRegisters) {
129   unsigned intCount = 0, fpCount = 0;
130   for (llvm::Type *type : scalarTypes) {
131     if (type->isPointerTy()) {
132       intCount++;
133     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
134       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
135       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
136     } else {
137       assert(type->isVectorTy() || type->isFloatingPointTy());
138       fpCount++;
139     }
140   }
141 
142   return (intCount + fpCount > maxAllRegisters);
143 }
144 
145 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
146                                              llvm::Type *eltTy,
147                                              unsigned numElts) const {
148   // The default implementation of this assumes that the target guarantees
149   // 128-bit SIMD support but nothing more.
150   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
151 }
152 
153 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
154                                               CGCXXABI &CXXABI) {
155   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
156   if (!RD) {
157     if (!RT->getDecl()->canPassInRegisters())
158       return CGCXXABI::RAA_Indirect;
159     return CGCXXABI::RAA_Default;
160   }
161   return CXXABI.getRecordArgABI(RD);
162 }
163 
164 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
165                                               CGCXXABI &CXXABI) {
166   const RecordType *RT = T->getAs<RecordType>();
167   if (!RT)
168     return CGCXXABI::RAA_Default;
169   return getRecordArgABI(RT, CXXABI);
170 }
171 
172 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
173                                const ABIInfo &Info) {
174   QualType Ty = FI.getReturnType();
175 
176   if (const auto *RT = Ty->getAs<RecordType>())
177     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
178         !RT->getDecl()->canPassInRegisters()) {
179       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
180       return true;
181     }
182 
183   return CXXABI.classifyReturnType(FI);
184 }
185 
186 /// Pass transparent unions as if they were the type of the first element. Sema
187 /// should ensure that all elements of the union have the same "machine type".
188 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
189   if (const RecordType *UT = Ty->getAsUnionType()) {
190     const RecordDecl *UD = UT->getDecl();
191     if (UD->hasAttr<TransparentUnionAttr>()) {
192       assert(!UD->field_empty() && "sema created an empty transparent union");
193       return UD->field_begin()->getType();
194     }
195   }
196   return Ty;
197 }
198 
199 CGCXXABI &ABIInfo::getCXXABI() const {
200   return CGT.getCXXABI();
201 }
202 
203 ASTContext &ABIInfo::getContext() const {
204   return CGT.getContext();
205 }
206 
207 llvm::LLVMContext &ABIInfo::getVMContext() const {
208   return CGT.getLLVMContext();
209 }
210 
211 const llvm::DataLayout &ABIInfo::getDataLayout() const {
212   return CGT.getDataLayout();
213 }
214 
215 const TargetInfo &ABIInfo::getTarget() const {
216   return CGT.getTarget();
217 }
218 
219 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
220   return CGT.getCodeGenOpts();
221 }
222 
223 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
224 
225 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
226   return false;
227 }
228 
229 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
230                                                 uint64_t Members) const {
231   return false;
232 }
233 
234 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
235   raw_ostream &OS = llvm::errs();
236   OS << "(ABIArgInfo Kind=";
237   switch (TheKind) {
238   case Direct:
239     OS << "Direct Type=";
240     if (llvm::Type *Ty = getCoerceToType())
241       Ty->print(OS);
242     else
243       OS << "null";
244     break;
245   case Extend:
246     OS << "Extend";
247     break;
248   case Ignore:
249     OS << "Ignore";
250     break;
251   case InAlloca:
252     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
253     break;
254   case Indirect:
255     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
256        << " ByVal=" << getIndirectByVal()
257        << " Realign=" << getIndirectRealign();
258     break;
259   case Expand:
260     OS << "Expand";
261     break;
262   case CoerceAndExpand:
263     OS << "CoerceAndExpand Type=";
264     getCoerceAndExpandType()->print(OS);
265     break;
266   }
267   OS << ")\n";
268 }
269 
270 // Dynamically round a pointer up to a multiple of the given alignment.
271 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
272                                                   llvm::Value *Ptr,
273                                                   CharUnits Align) {
274   llvm::Value *PtrAsInt = Ptr;
275   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
276   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
277   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
278         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
279   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
280            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
281   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
282                                         Ptr->getType(),
283                                         Ptr->getName() + ".aligned");
284   return PtrAsInt;
285 }
286 
287 /// Emit va_arg for a platform using the common void* representation,
288 /// where arguments are simply emitted in an array of slots on the stack.
289 ///
290 /// This version implements the core direct-value passing rules.
291 ///
292 /// \param SlotSize - The size and alignment of a stack slot.
293 ///   Each argument will be allocated to a multiple of this number of
294 ///   slots, and all the slots will be aligned to this value.
295 /// \param AllowHigherAlign - The slot alignment is not a cap;
296 ///   an argument type with an alignment greater than the slot size
297 ///   will be emitted on a higher-alignment address, potentially
298 ///   leaving one or more empty slots behind as padding.  If this
299 ///   is false, the returned address might be less-aligned than
300 ///   DirectAlign.
301 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
302                                       Address VAListAddr,
303                                       llvm::Type *DirectTy,
304                                       CharUnits DirectSize,
305                                       CharUnits DirectAlign,
306                                       CharUnits SlotSize,
307                                       bool AllowHigherAlign) {
308   // Cast the element type to i8* if necessary.  Some platforms define
309   // va_list as a struct containing an i8* instead of just an i8*.
310   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
311     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
312 
313   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
314 
315   // If the CC aligns values higher than the slot size, do so if needed.
316   Address Addr = Address::invalid();
317   if (AllowHigherAlign && DirectAlign > SlotSize) {
318     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
319                                                  DirectAlign);
320   } else {
321     Addr = Address(Ptr, SlotSize);
322   }
323 
324   // Advance the pointer past the argument, then store that back.
325   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
326   Address NextPtr =
327       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
328   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
329 
330   // If the argument is smaller than a slot, and this is a big-endian
331   // target, the argument will be right-adjusted in its slot.
332   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
333       !DirectTy->isStructTy()) {
334     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
335   }
336 
337   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
338   return Addr;
339 }
340 
341 /// Emit va_arg for a platform using the common void* representation,
342 /// where arguments are simply emitted in an array of slots on the stack.
343 ///
344 /// \param IsIndirect - Values of this type are passed indirectly.
345 /// \param ValueInfo - The size and alignment of this type, generally
346 ///   computed with getContext().getTypeInfoInChars(ValueTy).
347 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
348 ///   Each argument will be allocated to a multiple of this number of
349 ///   slots, and all the slots will be aligned to this value.
350 /// \param AllowHigherAlign - The slot alignment is not a cap;
351 ///   an argument type with an alignment greater than the slot size
352 ///   will be emitted on a higher-alignment address, potentially
353 ///   leaving one or more empty slots behind as padding.
354 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
355                                 QualType ValueTy, bool IsIndirect,
356                                 std::pair<CharUnits, CharUnits> ValueInfo,
357                                 CharUnits SlotSizeAndAlign,
358                                 bool AllowHigherAlign) {
359   // The size and alignment of the value that was passed directly.
360   CharUnits DirectSize, DirectAlign;
361   if (IsIndirect) {
362     DirectSize = CGF.getPointerSize();
363     DirectAlign = CGF.getPointerAlign();
364   } else {
365     DirectSize = ValueInfo.first;
366     DirectAlign = ValueInfo.second;
367   }
368 
369   // Cast the address we've calculated to the right type.
370   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
371   if (IsIndirect)
372     DirectTy = DirectTy->getPointerTo(0);
373 
374   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
375                                         DirectSize, DirectAlign,
376                                         SlotSizeAndAlign,
377                                         AllowHigherAlign);
378 
379   if (IsIndirect) {
380     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
381   }
382 
383   return Addr;
384 
385 }
386 
387 static Address emitMergePHI(CodeGenFunction &CGF,
388                             Address Addr1, llvm::BasicBlock *Block1,
389                             Address Addr2, llvm::BasicBlock *Block2,
390                             const llvm::Twine &Name = "") {
391   assert(Addr1.getType() == Addr2.getType());
392   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
393   PHI->addIncoming(Addr1.getPointer(), Block1);
394   PHI->addIncoming(Addr2.getPointer(), Block2);
395   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
396   return Address(PHI, Align);
397 }
398 
399 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
400 
401 // If someone can figure out a general rule for this, that would be great.
402 // It's probably just doomed to be platform-dependent, though.
403 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
404   // Verified for:
405   //   x86-64     FreeBSD, Linux, Darwin
406   //   x86-32     FreeBSD, Linux, Darwin
407   //   PowerPC    Linux, Darwin
408   //   ARM        Darwin (*not* EABI)
409   //   AArch64    Linux
410   return 32;
411 }
412 
413 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
414                                      const FunctionNoProtoType *fnType) const {
415   // The following conventions are known to require this to be false:
416   //   x86_stdcall
417   //   MIPS
418   // For everything else, we just prefer false unless we opt out.
419   return false;
420 }
421 
422 void
423 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
424                                              llvm::SmallString<24> &Opt) const {
425   // This assumes the user is passing a library name like "rt" instead of a
426   // filename like "librt.a/so", and that they don't care whether it's static or
427   // dynamic.
428   Opt = "-l";
429   Opt += Lib;
430 }
431 
432 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
433   // OpenCL kernels are called via an explicit runtime API with arguments
434   // set with clSetKernelArg(), not as normal sub-functions.
435   // Return SPIR_KERNEL by default as the kernel calling convention to
436   // ensure the fingerprint is fixed such way that each OpenCL argument
437   // gets one matching argument in the produced kernel function argument
438   // list to enable feasible implementation of clSetKernelArg() with
439   // aggregates etc. In case we would use the default C calling conv here,
440   // clSetKernelArg() might break depending on the target-specific
441   // conventions; different targets might split structs passed as values
442   // to multiple function arguments etc.
443   return llvm::CallingConv::SPIR_KERNEL;
444 }
445 
446 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
447     llvm::PointerType *T, QualType QT) const {
448   return llvm::ConstantPointerNull::get(T);
449 }
450 
451 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
452                                                    const VarDecl *D) const {
453   assert(!CGM.getLangOpts().OpenCL &&
454          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
455          "Address space agnostic languages only");
456   return D ? D->getType().getAddressSpace() : LangAS::Default;
457 }
458 
459 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
460     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
461     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
462   // Since target may map different address spaces in AST to the same address
463   // space, an address space conversion may end up as a bitcast.
464   if (auto *C = dyn_cast<llvm::Constant>(Src))
465     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
466   // Try to preserve the source's name to make IR more readable.
467   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
468       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
469 }
470 
471 llvm::Constant *
472 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
473                                         LangAS SrcAddr, LangAS DestAddr,
474                                         llvm::Type *DestTy) const {
475   // Since target may map different address spaces in AST to the same address
476   // space, an address space conversion may end up as a bitcast.
477   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
478 }
479 
480 llvm::SyncScope::ID
481 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
482                                       SyncScope Scope,
483                                       llvm::AtomicOrdering Ordering,
484                                       llvm::LLVMContext &Ctx) const {
485   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
486 }
487 
488 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
489 
490 /// isEmptyField - Return true iff a the field is "empty", that is it
491 /// is an unnamed bit-field or an (array of) empty record(s).
492 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
493                          bool AllowArrays) {
494   if (FD->isUnnamedBitfield())
495     return true;
496 
497   QualType FT = FD->getType();
498 
499   // Constant arrays of empty records count as empty, strip them off.
500   // Constant arrays of zero length always count as empty.
501   if (AllowArrays)
502     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
503       if (AT->getSize() == 0)
504         return true;
505       FT = AT->getElementType();
506     }
507 
508   const RecordType *RT = FT->getAs<RecordType>();
509   if (!RT)
510     return false;
511 
512   // C++ record fields are never empty, at least in the Itanium ABI.
513   //
514   // FIXME: We should use a predicate for whether this behavior is true in the
515   // current ABI.
516   if (isa<CXXRecordDecl>(RT->getDecl()))
517     return false;
518 
519   return isEmptyRecord(Context, FT, AllowArrays);
520 }
521 
522 /// isEmptyRecord - Return true iff a structure contains only empty
523 /// fields. Note that a structure with a flexible array member is not
524 /// considered empty.
525 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
526   const RecordType *RT = T->getAs<RecordType>();
527   if (!RT)
528     return false;
529   const RecordDecl *RD = RT->getDecl();
530   if (RD->hasFlexibleArrayMember())
531     return false;
532 
533   // If this is a C++ record, check the bases first.
534   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
535     for (const auto &I : CXXRD->bases())
536       if (!isEmptyRecord(Context, I.getType(), true))
537         return false;
538 
539   for (const auto *I : RD->fields())
540     if (!isEmptyField(Context, I, AllowArrays))
541       return false;
542   return true;
543 }
544 
545 /// isSingleElementStruct - Determine if a structure is a "single
546 /// element struct", i.e. it has exactly one non-empty field or
547 /// exactly one field which is itself a single element
548 /// struct. Structures with flexible array members are never
549 /// considered single element structs.
550 ///
551 /// \return The field declaration for the single non-empty field, if
552 /// it exists.
553 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
554   const RecordType *RT = T->getAs<RecordType>();
555   if (!RT)
556     return nullptr;
557 
558   const RecordDecl *RD = RT->getDecl();
559   if (RD->hasFlexibleArrayMember())
560     return nullptr;
561 
562   const Type *Found = nullptr;
563 
564   // If this is a C++ record, check the bases first.
565   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
566     for (const auto &I : CXXRD->bases()) {
567       // Ignore empty records.
568       if (isEmptyRecord(Context, I.getType(), true))
569         continue;
570 
571       // If we already found an element then this isn't a single-element struct.
572       if (Found)
573         return nullptr;
574 
575       // If this is non-empty and not a single element struct, the composite
576       // cannot be a single element struct.
577       Found = isSingleElementStruct(I.getType(), Context);
578       if (!Found)
579         return nullptr;
580     }
581   }
582 
583   // Check for single element.
584   for (const auto *FD : RD->fields()) {
585     QualType FT = FD->getType();
586 
587     // Ignore empty fields.
588     if (isEmptyField(Context, FD, true))
589       continue;
590 
591     // If we already found an element then this isn't a single-element
592     // struct.
593     if (Found)
594       return nullptr;
595 
596     // Treat single element arrays as the element.
597     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
598       if (AT->getSize().getZExtValue() != 1)
599         break;
600       FT = AT->getElementType();
601     }
602 
603     if (!isAggregateTypeForABI(FT)) {
604       Found = FT.getTypePtr();
605     } else {
606       Found = isSingleElementStruct(FT, Context);
607       if (!Found)
608         return nullptr;
609     }
610   }
611 
612   // We don't consider a struct a single-element struct if it has
613   // padding beyond the element type.
614   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
615     return nullptr;
616 
617   return Found;
618 }
619 
620 namespace {
621 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
622                        const ABIArgInfo &AI) {
623   // This default implementation defers to the llvm backend's va_arg
624   // instruction. It can handle only passing arguments directly
625   // (typically only handled in the backend for primitive types), or
626   // aggregates passed indirectly by pointer (NOTE: if the "byval"
627   // flag has ABI impact in the callee, this implementation cannot
628   // work.)
629 
630   // Only a few cases are covered here at the moment -- those needed
631   // by the default abi.
632   llvm::Value *Val;
633 
634   if (AI.isIndirect()) {
635     assert(!AI.getPaddingType() &&
636            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
637     assert(
638         !AI.getIndirectRealign() &&
639         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
640 
641     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
642     CharUnits TyAlignForABI = TyInfo.second;
643 
644     llvm::Type *BaseTy =
645         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
646     llvm::Value *Addr =
647         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
648     return Address(Addr, TyAlignForABI);
649   } else {
650     assert((AI.isDirect() || AI.isExtend()) &&
651            "Unexpected ArgInfo Kind in generic VAArg emitter!");
652 
653     assert(!AI.getInReg() &&
654            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
655     assert(!AI.getPaddingType() &&
656            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
657     assert(!AI.getDirectOffset() &&
658            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
659     assert(!AI.getCoerceToType() &&
660            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
661 
662     Address Temp = CGF.CreateMemTemp(Ty, "varet");
663     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
664     CGF.Builder.CreateStore(Val, Temp);
665     return Temp;
666   }
667 }
668 
669 /// DefaultABIInfo - The default implementation for ABI specific
670 /// details. This implementation provides information which results in
671 /// self-consistent and sensible LLVM IR generation, but does not
672 /// conform to any particular ABI.
673 class DefaultABIInfo : public ABIInfo {
674 public:
675   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
676 
677   ABIArgInfo classifyReturnType(QualType RetTy) const;
678   ABIArgInfo classifyArgumentType(QualType RetTy) const;
679 
680   void computeInfo(CGFunctionInfo &FI) const override {
681     if (!getCXXABI().classifyReturnType(FI))
682       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
683     for (auto &I : FI.arguments())
684       I.info = classifyArgumentType(I.type);
685   }
686 
687   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
688                     QualType Ty) const override {
689     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
690   }
691 };
692 
693 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
694 public:
695   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
696       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
697 };
698 
699 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
700   Ty = useFirstFieldIfTransparentUnion(Ty);
701 
702   if (isAggregateTypeForABI(Ty)) {
703     // Records with non-trivial destructors/copy-constructors should not be
704     // passed by value.
705     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
706       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
707 
708     return getNaturalAlignIndirect(Ty);
709   }
710 
711   // Treat an enum type as its underlying type.
712   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
713     Ty = EnumTy->getDecl()->getIntegerType();
714 
715   ASTContext &Context = getContext();
716   if (const auto *EIT = Ty->getAs<ExtIntType>())
717     if (EIT->getNumBits() >
718         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
719                                 ? Context.Int128Ty
720                                 : Context.LongLongTy))
721       return getNaturalAlignIndirect(Ty);
722 
723   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
724                                             : ABIArgInfo::getDirect());
725 }
726 
727 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
728   if (RetTy->isVoidType())
729     return ABIArgInfo::getIgnore();
730 
731   if (isAggregateTypeForABI(RetTy))
732     return getNaturalAlignIndirect(RetTy);
733 
734   // Treat an enum type as its underlying type.
735   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
736     RetTy = EnumTy->getDecl()->getIntegerType();
737 
738   if (const auto *EIT = RetTy->getAs<ExtIntType>())
739     if (EIT->getNumBits() >
740         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
741                                      ? getContext().Int128Ty
742                                      : getContext().LongLongTy))
743       return getNaturalAlignIndirect(RetTy);
744 
745   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
746                                                : ABIArgInfo::getDirect());
747 }
748 
749 //===----------------------------------------------------------------------===//
750 // WebAssembly ABI Implementation
751 //
752 // This is a very simple ABI that relies a lot on DefaultABIInfo.
753 //===----------------------------------------------------------------------===//
754 
755 class WebAssemblyABIInfo final : public SwiftABIInfo {
756 public:
757   enum ABIKind {
758     MVP = 0,
759     ExperimentalMV = 1,
760   };
761 
762 private:
763   DefaultABIInfo defaultInfo;
764   ABIKind Kind;
765 
766 public:
767   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
768       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
769 
770 private:
771   ABIArgInfo classifyReturnType(QualType RetTy) const;
772   ABIArgInfo classifyArgumentType(QualType Ty) const;
773 
774   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
775   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
776   // overload them.
777   void computeInfo(CGFunctionInfo &FI) const override {
778     if (!getCXXABI().classifyReturnType(FI))
779       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
780     for (auto &Arg : FI.arguments())
781       Arg.info = classifyArgumentType(Arg.type);
782   }
783 
784   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
785                     QualType Ty) const override;
786 
787   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
788                                     bool asReturnValue) const override {
789     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
790   }
791 
792   bool isSwiftErrorInRegister() const override {
793     return false;
794   }
795 };
796 
797 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
798 public:
799   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
800                                         WebAssemblyABIInfo::ABIKind K)
801       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
802 
803   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
804                            CodeGen::CodeGenModule &CGM) const override {
805     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
806     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
807       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
808         llvm::Function *Fn = cast<llvm::Function>(GV);
809         llvm::AttrBuilder B;
810         B.addAttribute("wasm-import-module", Attr->getImportModule());
811         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
812       }
813       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
814         llvm::Function *Fn = cast<llvm::Function>(GV);
815         llvm::AttrBuilder B;
816         B.addAttribute("wasm-import-name", Attr->getImportName());
817         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
818       }
819       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
820         llvm::Function *Fn = cast<llvm::Function>(GV);
821         llvm::AttrBuilder B;
822         B.addAttribute("wasm-export-name", Attr->getExportName());
823         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
824       }
825     }
826 
827     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
828       llvm::Function *Fn = cast<llvm::Function>(GV);
829       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
830         Fn->addFnAttr("no-prototype");
831     }
832   }
833 };
834 
835 /// Classify argument of given type \p Ty.
836 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
837   Ty = useFirstFieldIfTransparentUnion(Ty);
838 
839   if (isAggregateTypeForABI(Ty)) {
840     // Records with non-trivial destructors/copy-constructors should not be
841     // passed by value.
842     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
843       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
844     // Ignore empty structs/unions.
845     if (isEmptyRecord(getContext(), Ty, true))
846       return ABIArgInfo::getIgnore();
847     // Lower single-element structs to just pass a regular value. TODO: We
848     // could do reasonable-size multiple-element structs too, using getExpand(),
849     // though watch out for things like bitfields.
850     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
851       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
852     // For the experimental multivalue ABI, fully expand all other aggregates
853     if (Kind == ABIKind::ExperimentalMV) {
854       const RecordType *RT = Ty->getAs<RecordType>();
855       assert(RT);
856       bool HasBitField = false;
857       for (auto *Field : RT->getDecl()->fields()) {
858         if (Field->isBitField()) {
859           HasBitField = true;
860           break;
861         }
862       }
863       if (!HasBitField)
864         return ABIArgInfo::getExpand();
865     }
866   }
867 
868   // Otherwise just do the default thing.
869   return defaultInfo.classifyArgumentType(Ty);
870 }
871 
872 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
873   if (isAggregateTypeForABI(RetTy)) {
874     // Records with non-trivial destructors/copy-constructors should not be
875     // returned by value.
876     if (!getRecordArgABI(RetTy, getCXXABI())) {
877       // Ignore empty structs/unions.
878       if (isEmptyRecord(getContext(), RetTy, true))
879         return ABIArgInfo::getIgnore();
880       // Lower single-element structs to just return a regular value. TODO: We
881       // could do reasonable-size multiple-element structs too, using
882       // ABIArgInfo::getDirect().
883       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
884         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
885       // For the experimental multivalue ABI, return all other aggregates
886       if (Kind == ABIKind::ExperimentalMV)
887         return ABIArgInfo::getDirect();
888     }
889   }
890 
891   // Otherwise just do the default thing.
892   return defaultInfo.classifyReturnType(RetTy);
893 }
894 
895 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
896                                       QualType Ty) const {
897   bool IsIndirect = isAggregateTypeForABI(Ty) &&
898                     !isEmptyRecord(getContext(), Ty, true) &&
899                     !isSingleElementStruct(Ty, getContext());
900   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
901                           getContext().getTypeInfoInChars(Ty),
902                           CharUnits::fromQuantity(4),
903                           /*AllowHigherAlign=*/true);
904 }
905 
906 //===----------------------------------------------------------------------===//
907 // le32/PNaCl bitcode ABI Implementation
908 //
909 // This is a simplified version of the x86_32 ABI.  Arguments and return values
910 // are always passed on the stack.
911 //===----------------------------------------------------------------------===//
912 
913 class PNaClABIInfo : public ABIInfo {
914  public:
915   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
916 
917   ABIArgInfo classifyReturnType(QualType RetTy) const;
918   ABIArgInfo classifyArgumentType(QualType RetTy) const;
919 
920   void computeInfo(CGFunctionInfo &FI) const override;
921   Address EmitVAArg(CodeGenFunction &CGF,
922                     Address VAListAddr, QualType Ty) const override;
923 };
924 
925 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
926  public:
927    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
928        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
929 };
930 
931 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
932   if (!getCXXABI().classifyReturnType(FI))
933     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
934 
935   for (auto &I : FI.arguments())
936     I.info = classifyArgumentType(I.type);
937 }
938 
939 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
940                                 QualType Ty) const {
941   // The PNaCL ABI is a bit odd, in that varargs don't use normal
942   // function classification. Structs get passed directly for varargs
943   // functions, through a rewriting transform in
944   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
945   // this target to actually support a va_arg instructions with an
946   // aggregate type, unlike other targets.
947   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
948 }
949 
950 /// Classify argument of given type \p Ty.
951 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
952   if (isAggregateTypeForABI(Ty)) {
953     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
954       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
955     return getNaturalAlignIndirect(Ty);
956   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
957     // Treat an enum type as its underlying type.
958     Ty = EnumTy->getDecl()->getIntegerType();
959   } else if (Ty->isFloatingType()) {
960     // Floating-point types don't go inreg.
961     return ABIArgInfo::getDirect();
962   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
963     // Treat extended integers as integers if <=64, otherwise pass indirectly.
964     if (EIT->getNumBits() > 64)
965       return getNaturalAlignIndirect(Ty);
966     return ABIArgInfo::getDirect();
967   }
968 
969   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
970                                             : ABIArgInfo::getDirect());
971 }
972 
973 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
974   if (RetTy->isVoidType())
975     return ABIArgInfo::getIgnore();
976 
977   // In the PNaCl ABI we always return records/structures on the stack.
978   if (isAggregateTypeForABI(RetTy))
979     return getNaturalAlignIndirect(RetTy);
980 
981   // Treat extended integers as integers if <=64, otherwise pass indirectly.
982   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
983     if (EIT->getNumBits() > 64)
984       return getNaturalAlignIndirect(RetTy);
985     return ABIArgInfo::getDirect();
986   }
987 
988   // Treat an enum type as its underlying type.
989   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
990     RetTy = EnumTy->getDecl()->getIntegerType();
991 
992   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
993                                                : ABIArgInfo::getDirect());
994 }
995 
996 /// IsX86_MMXType - Return true if this is an MMX type.
997 bool IsX86_MMXType(llvm::Type *IRType) {
998   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
999   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1000     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1001     IRType->getScalarSizeInBits() != 64;
1002 }
1003 
1004 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1005                                           StringRef Constraint,
1006                                           llvm::Type* Ty) {
1007   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1008                      .Cases("y", "&y", "^Ym", true)
1009                      .Default(false);
1010   if (IsMMXCons && Ty->isVectorTy()) {
1011     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1012         64) {
1013       // Invalid MMX constraint
1014       return nullptr;
1015     }
1016 
1017     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1018   }
1019 
1020   // No operation needed
1021   return Ty;
1022 }
1023 
1024 /// Returns true if this type can be passed in SSE registers with the
1025 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1026 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1027   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1028     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1029       if (BT->getKind() == BuiltinType::LongDouble) {
1030         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1031             &llvm::APFloat::x87DoubleExtended())
1032           return false;
1033       }
1034       return true;
1035     }
1036   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1037     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1038     // registers specially.
1039     unsigned VecSize = Context.getTypeSize(VT);
1040     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1041       return true;
1042   }
1043   return false;
1044 }
1045 
1046 /// Returns true if this aggregate is small enough to be passed in SSE registers
1047 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1048 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1049   return NumMembers <= 4;
1050 }
1051 
1052 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1053 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1054   auto AI = ABIArgInfo::getDirect(T);
1055   AI.setInReg(true);
1056   AI.setCanBeFlattened(false);
1057   return AI;
1058 }
1059 
1060 //===----------------------------------------------------------------------===//
1061 // X86-32 ABI Implementation
1062 //===----------------------------------------------------------------------===//
1063 
1064 /// Similar to llvm::CCState, but for Clang.
1065 struct CCState {
1066   CCState(CGFunctionInfo &FI)
1067       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1068 
1069   llvm::SmallBitVector IsPreassigned;
1070   unsigned CC = CallingConv::CC_C;
1071   unsigned FreeRegs = 0;
1072   unsigned FreeSSERegs = 0;
1073 };
1074 
1075 enum {
1076   // Vectorcall only allows the first 6 parameters to be passed in registers.
1077   VectorcallMaxParamNumAsReg = 6
1078 };
1079 
1080 /// X86_32ABIInfo - The X86-32 ABI information.
1081 class X86_32ABIInfo : public SwiftABIInfo {
1082   enum Class {
1083     Integer,
1084     Float
1085   };
1086 
1087   static const unsigned MinABIStackAlignInBytes = 4;
1088 
1089   bool IsDarwinVectorABI;
1090   bool IsRetSmallStructInRegABI;
1091   bool IsWin32StructABI;
1092   bool IsSoftFloatABI;
1093   bool IsMCUABI;
1094   unsigned DefaultNumRegisterParameters;
1095 
1096   static bool isRegisterSize(unsigned Size) {
1097     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1098   }
1099 
1100   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1101     // FIXME: Assumes vectorcall is in use.
1102     return isX86VectorTypeForVectorCall(getContext(), Ty);
1103   }
1104 
1105   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1106                                          uint64_t NumMembers) const override {
1107     // FIXME: Assumes vectorcall is in use.
1108     return isX86VectorCallAggregateSmallEnough(NumMembers);
1109   }
1110 
1111   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1112 
1113   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1114   /// such that the argument will be passed in memory.
1115   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1116 
1117   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1118 
1119   /// Return the alignment to use for the given type on the stack.
1120   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1121 
1122   Class classify(QualType Ty) const;
1123   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1124   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1125 
1126   /// Updates the number of available free registers, returns
1127   /// true if any registers were allocated.
1128   bool updateFreeRegs(QualType Ty, CCState &State) const;
1129 
1130   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1131                                 bool &NeedsPadding) const;
1132   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1133 
1134   bool canExpandIndirectArgument(QualType Ty) const;
1135 
1136   /// Rewrite the function info so that all memory arguments use
1137   /// inalloca.
1138   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1139 
1140   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1141                            CharUnits &StackOffset, ABIArgInfo &Info,
1142                            QualType Type) const;
1143   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1144 
1145 public:
1146 
1147   void computeInfo(CGFunctionInfo &FI) const override;
1148   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1149                     QualType Ty) const override;
1150 
1151   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1152                 bool RetSmallStructInRegABI, bool Win32StructABI,
1153                 unsigned NumRegisterParameters, bool SoftFloatABI)
1154     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1155       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1156       IsWin32StructABI(Win32StructABI),
1157       IsSoftFloatABI(SoftFloatABI),
1158       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1159       DefaultNumRegisterParameters(NumRegisterParameters) {}
1160 
1161   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1162                                     bool asReturnValue) const override {
1163     // LLVM's x86-32 lowering currently only assigns up to three
1164     // integer registers and three fp registers.  Oddly, it'll use up to
1165     // four vector registers for vectors, but those can overlap with the
1166     // scalar registers.
1167     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1168   }
1169 
1170   bool isSwiftErrorInRegister() const override {
1171     // x86-32 lowering does not support passing swifterror in a register.
1172     return false;
1173   }
1174 };
1175 
1176 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1177 public:
1178   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1179                           bool RetSmallStructInRegABI, bool Win32StructABI,
1180                           unsigned NumRegisterParameters, bool SoftFloatABI)
1181       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1182             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1183             NumRegisterParameters, SoftFloatABI)) {}
1184 
1185   static bool isStructReturnInRegABI(
1186       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1187 
1188   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1189                            CodeGen::CodeGenModule &CGM) const override;
1190 
1191   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1192     // Darwin uses different dwarf register numbers for EH.
1193     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1194     return 4;
1195   }
1196 
1197   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1198                                llvm::Value *Address) const override;
1199 
1200   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1201                                   StringRef Constraint,
1202                                   llvm::Type* Ty) const override {
1203     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1204   }
1205 
1206   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1207                                 std::string &Constraints,
1208                                 std::vector<llvm::Type *> &ResultRegTypes,
1209                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1210                                 std::vector<LValue> &ResultRegDests,
1211                                 std::string &AsmString,
1212                                 unsigned NumOutputs) const override;
1213 
1214   llvm::Constant *
1215   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1216     unsigned Sig = (0xeb << 0) |  // jmp rel8
1217                    (0x06 << 8) |  //           .+0x08
1218                    ('v' << 16) |
1219                    ('2' << 24);
1220     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1221   }
1222 
1223   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1224     return "movl\t%ebp, %ebp"
1225            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1226   }
1227 };
1228 
1229 }
1230 
1231 /// Rewrite input constraint references after adding some output constraints.
1232 /// In the case where there is one output and one input and we add one output,
1233 /// we need to replace all operand references greater than or equal to 1:
1234 ///     mov $0, $1
1235 ///     mov eax, $1
1236 /// The result will be:
1237 ///     mov $0, $2
1238 ///     mov eax, $2
1239 static void rewriteInputConstraintReferences(unsigned FirstIn,
1240                                              unsigned NumNewOuts,
1241                                              std::string &AsmString) {
1242   std::string Buf;
1243   llvm::raw_string_ostream OS(Buf);
1244   size_t Pos = 0;
1245   while (Pos < AsmString.size()) {
1246     size_t DollarStart = AsmString.find('$', Pos);
1247     if (DollarStart == std::string::npos)
1248       DollarStart = AsmString.size();
1249     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1250     if (DollarEnd == std::string::npos)
1251       DollarEnd = AsmString.size();
1252     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1253     Pos = DollarEnd;
1254     size_t NumDollars = DollarEnd - DollarStart;
1255     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1256       // We have an operand reference.
1257       size_t DigitStart = Pos;
1258       if (AsmString[DigitStart] == '{') {
1259         OS << '{';
1260         ++DigitStart;
1261       }
1262       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1263       if (DigitEnd == std::string::npos)
1264         DigitEnd = AsmString.size();
1265       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1266       unsigned OperandIndex;
1267       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1268         if (OperandIndex >= FirstIn)
1269           OperandIndex += NumNewOuts;
1270         OS << OperandIndex;
1271       } else {
1272         OS << OperandStr;
1273       }
1274       Pos = DigitEnd;
1275     }
1276   }
1277   AsmString = std::move(OS.str());
1278 }
1279 
1280 /// Add output constraints for EAX:EDX because they are return registers.
1281 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1282     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1283     std::vector<llvm::Type *> &ResultRegTypes,
1284     std::vector<llvm::Type *> &ResultTruncRegTypes,
1285     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1286     unsigned NumOutputs) const {
1287   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1288 
1289   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1290   // larger.
1291   if (!Constraints.empty())
1292     Constraints += ',';
1293   if (RetWidth <= 32) {
1294     Constraints += "={eax}";
1295     ResultRegTypes.push_back(CGF.Int32Ty);
1296   } else {
1297     // Use the 'A' constraint for EAX:EDX.
1298     Constraints += "=A";
1299     ResultRegTypes.push_back(CGF.Int64Ty);
1300   }
1301 
1302   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1303   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1304   ResultTruncRegTypes.push_back(CoerceTy);
1305 
1306   // Coerce the integer by bitcasting the return slot pointer.
1307   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1308                                                   CoerceTy->getPointerTo()));
1309   ResultRegDests.push_back(ReturnSlot);
1310 
1311   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1312 }
1313 
1314 /// shouldReturnTypeInRegister - Determine if the given type should be
1315 /// returned in a register (for the Darwin and MCU ABI).
1316 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1317                                                ASTContext &Context) const {
1318   uint64_t Size = Context.getTypeSize(Ty);
1319 
1320   // For i386, type must be register sized.
1321   // For the MCU ABI, it only needs to be <= 8-byte
1322   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1323    return false;
1324 
1325   if (Ty->isVectorType()) {
1326     // 64- and 128- bit vectors inside structures are not returned in
1327     // registers.
1328     if (Size == 64 || Size == 128)
1329       return false;
1330 
1331     return true;
1332   }
1333 
1334   // If this is a builtin, pointer, enum, complex type, member pointer, or
1335   // member function pointer it is ok.
1336   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1337       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1338       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1339     return true;
1340 
1341   // Arrays are treated like records.
1342   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1343     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1344 
1345   // Otherwise, it must be a record type.
1346   const RecordType *RT = Ty->getAs<RecordType>();
1347   if (!RT) return false;
1348 
1349   // FIXME: Traverse bases here too.
1350 
1351   // Structure types are passed in register if all fields would be
1352   // passed in a register.
1353   for (const auto *FD : RT->getDecl()->fields()) {
1354     // Empty fields are ignored.
1355     if (isEmptyField(Context, FD, true))
1356       continue;
1357 
1358     // Check fields recursively.
1359     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1360       return false;
1361   }
1362   return true;
1363 }
1364 
1365 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1366   // Treat complex types as the element type.
1367   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1368     Ty = CTy->getElementType();
1369 
1370   // Check for a type which we know has a simple scalar argument-passing
1371   // convention without any padding.  (We're specifically looking for 32
1372   // and 64-bit integer and integer-equivalents, float, and double.)
1373   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1374       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1375     return false;
1376 
1377   uint64_t Size = Context.getTypeSize(Ty);
1378   return Size == 32 || Size == 64;
1379 }
1380 
1381 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1382                           uint64_t &Size) {
1383   for (const auto *FD : RD->fields()) {
1384     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1385     // argument is smaller than 32-bits, expanding the struct will create
1386     // alignment padding.
1387     if (!is32Or64BitBasicType(FD->getType(), Context))
1388       return false;
1389 
1390     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1391     // how to expand them yet, and the predicate for telling if a bitfield still
1392     // counts as "basic" is more complicated than what we were doing previously.
1393     if (FD->isBitField())
1394       return false;
1395 
1396     Size += Context.getTypeSize(FD->getType());
1397   }
1398   return true;
1399 }
1400 
1401 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1402                                  uint64_t &Size) {
1403   // Don't do this if there are any non-empty bases.
1404   for (const CXXBaseSpecifier &Base : RD->bases()) {
1405     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1406                               Size))
1407       return false;
1408   }
1409   if (!addFieldSizes(Context, RD, Size))
1410     return false;
1411   return true;
1412 }
1413 
1414 /// Test whether an argument type which is to be passed indirectly (on the
1415 /// stack) would have the equivalent layout if it was expanded into separate
1416 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1417 /// optimizations.
1418 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1419   // We can only expand structure types.
1420   const RecordType *RT = Ty->getAs<RecordType>();
1421   if (!RT)
1422     return false;
1423   const RecordDecl *RD = RT->getDecl();
1424   uint64_t Size = 0;
1425   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1426     if (!IsWin32StructABI) {
1427       // On non-Windows, we have to conservatively match our old bitcode
1428       // prototypes in order to be ABI-compatible at the bitcode level.
1429       if (!CXXRD->isCLike())
1430         return false;
1431     } else {
1432       // Don't do this for dynamic classes.
1433       if (CXXRD->isDynamicClass())
1434         return false;
1435     }
1436     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1437       return false;
1438   } else {
1439     if (!addFieldSizes(getContext(), RD, Size))
1440       return false;
1441   }
1442 
1443   // We can do this if there was no alignment padding.
1444   return Size == getContext().getTypeSize(Ty);
1445 }
1446 
1447 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1448   // If the return value is indirect, then the hidden argument is consuming one
1449   // integer register.
1450   if (State.FreeRegs) {
1451     --State.FreeRegs;
1452     if (!IsMCUABI)
1453       return getNaturalAlignIndirectInReg(RetTy);
1454   }
1455   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1456 }
1457 
1458 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1459                                              CCState &State) const {
1460   if (RetTy->isVoidType())
1461     return ABIArgInfo::getIgnore();
1462 
1463   const Type *Base = nullptr;
1464   uint64_t NumElts = 0;
1465   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1466        State.CC == llvm::CallingConv::X86_RegCall) &&
1467       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1468     // The LLVM struct type for such an aggregate should lower properly.
1469     return ABIArgInfo::getDirect();
1470   }
1471 
1472   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1473     // On Darwin, some vectors are returned in registers.
1474     if (IsDarwinVectorABI) {
1475       uint64_t Size = getContext().getTypeSize(RetTy);
1476 
1477       // 128-bit vectors are a special case; they are returned in
1478       // registers and we need to make sure to pick a type the LLVM
1479       // backend will like.
1480       if (Size == 128)
1481         return ABIArgInfo::getDirect(llvm::VectorType::get(
1482                   llvm::Type::getInt64Ty(getVMContext()), 2));
1483 
1484       // Always return in register if it fits in a general purpose
1485       // register, or if it is 64 bits and has a single element.
1486       if ((Size == 8 || Size == 16 || Size == 32) ||
1487           (Size == 64 && VT->getNumElements() == 1))
1488         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1489                                                             Size));
1490 
1491       return getIndirectReturnResult(RetTy, State);
1492     }
1493 
1494     return ABIArgInfo::getDirect();
1495   }
1496 
1497   if (isAggregateTypeForABI(RetTy)) {
1498     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1499       // Structures with flexible arrays are always indirect.
1500       if (RT->getDecl()->hasFlexibleArrayMember())
1501         return getIndirectReturnResult(RetTy, State);
1502     }
1503 
1504     // If specified, structs and unions are always indirect.
1505     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1506       return getIndirectReturnResult(RetTy, State);
1507 
1508     // Ignore empty structs/unions.
1509     if (isEmptyRecord(getContext(), RetTy, true))
1510       return ABIArgInfo::getIgnore();
1511 
1512     // Small structures which are register sized are generally returned
1513     // in a register.
1514     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1515       uint64_t Size = getContext().getTypeSize(RetTy);
1516 
1517       // As a special-case, if the struct is a "single-element" struct, and
1518       // the field is of type "float" or "double", return it in a
1519       // floating-point register. (MSVC does not apply this special case.)
1520       // We apply a similar transformation for pointer types to improve the
1521       // quality of the generated IR.
1522       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1523         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1524             || SeltTy->hasPointerRepresentation())
1525           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1526 
1527       // FIXME: We should be able to narrow this integer in cases with dead
1528       // padding.
1529       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1530     }
1531 
1532     return getIndirectReturnResult(RetTy, State);
1533   }
1534 
1535   // Treat an enum type as its underlying type.
1536   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1537     RetTy = EnumTy->getDecl()->getIntegerType();
1538 
1539   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1540     if (EIT->getNumBits() > 64)
1541       return getIndirectReturnResult(RetTy, State);
1542 
1543   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1544                                                : ABIArgInfo::getDirect());
1545 }
1546 
1547 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1548   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1549 }
1550 
1551 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1552   const RecordType *RT = Ty->getAs<RecordType>();
1553   if (!RT)
1554     return 0;
1555   const RecordDecl *RD = RT->getDecl();
1556 
1557   // If this is a C++ record, check the bases first.
1558   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1559     for (const auto &I : CXXRD->bases())
1560       if (!isRecordWithSSEVectorType(Context, I.getType()))
1561         return false;
1562 
1563   for (const auto *i : RD->fields()) {
1564     QualType FT = i->getType();
1565 
1566     if (isSSEVectorType(Context, FT))
1567       return true;
1568 
1569     if (isRecordWithSSEVectorType(Context, FT))
1570       return true;
1571   }
1572 
1573   return false;
1574 }
1575 
1576 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1577                                                  unsigned Align) const {
1578   // Otherwise, if the alignment is less than or equal to the minimum ABI
1579   // alignment, just use the default; the backend will handle this.
1580   if (Align <= MinABIStackAlignInBytes)
1581     return 0; // Use default alignment.
1582 
1583   // On non-Darwin, the stack type alignment is always 4.
1584   if (!IsDarwinVectorABI) {
1585     // Set explicit alignment, since we may need to realign the top.
1586     return MinABIStackAlignInBytes;
1587   }
1588 
1589   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1590   if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1591                       isRecordWithSSEVectorType(getContext(), Ty)))
1592     return 16;
1593 
1594   return MinABIStackAlignInBytes;
1595 }
1596 
1597 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1598                                             CCState &State) const {
1599   if (!ByVal) {
1600     if (State.FreeRegs) {
1601       --State.FreeRegs; // Non-byval indirects just use one pointer.
1602       if (!IsMCUABI)
1603         return getNaturalAlignIndirectInReg(Ty);
1604     }
1605     return getNaturalAlignIndirect(Ty, false);
1606   }
1607 
1608   // Compute the byval alignment.
1609   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1610   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1611   if (StackAlign == 0)
1612     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1613 
1614   // If the stack alignment is less than the type alignment, realign the
1615   // argument.
1616   bool Realign = TypeAlign > StackAlign;
1617   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1618                                  /*ByVal=*/true, Realign);
1619 }
1620 
1621 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1622   const Type *T = isSingleElementStruct(Ty, getContext());
1623   if (!T)
1624     T = Ty.getTypePtr();
1625 
1626   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1627     BuiltinType::Kind K = BT->getKind();
1628     if (K == BuiltinType::Float || K == BuiltinType::Double)
1629       return Float;
1630   }
1631   return Integer;
1632 }
1633 
1634 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1635   if (!IsSoftFloatABI) {
1636     Class C = classify(Ty);
1637     if (C == Float)
1638       return false;
1639   }
1640 
1641   unsigned Size = getContext().getTypeSize(Ty);
1642   unsigned SizeInRegs = (Size + 31) / 32;
1643 
1644   if (SizeInRegs == 0)
1645     return false;
1646 
1647   if (!IsMCUABI) {
1648     if (SizeInRegs > State.FreeRegs) {
1649       State.FreeRegs = 0;
1650       return false;
1651     }
1652   } else {
1653     // The MCU psABI allows passing parameters in-reg even if there are
1654     // earlier parameters that are passed on the stack. Also,
1655     // it does not allow passing >8-byte structs in-register,
1656     // even if there are 3 free registers available.
1657     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1658       return false;
1659   }
1660 
1661   State.FreeRegs -= SizeInRegs;
1662   return true;
1663 }
1664 
1665 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1666                                              bool &InReg,
1667                                              bool &NeedsPadding) const {
1668   // On Windows, aggregates other than HFAs are never passed in registers, and
1669   // they do not consume register slots. Homogenous floating-point aggregates
1670   // (HFAs) have already been dealt with at this point.
1671   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1672     return false;
1673 
1674   NeedsPadding = false;
1675   InReg = !IsMCUABI;
1676 
1677   if (!updateFreeRegs(Ty, State))
1678     return false;
1679 
1680   if (IsMCUABI)
1681     return true;
1682 
1683   if (State.CC == llvm::CallingConv::X86_FastCall ||
1684       State.CC == llvm::CallingConv::X86_VectorCall ||
1685       State.CC == llvm::CallingConv::X86_RegCall) {
1686     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1687       NeedsPadding = true;
1688 
1689     return false;
1690   }
1691 
1692   return true;
1693 }
1694 
1695 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1696   if (!updateFreeRegs(Ty, State))
1697     return false;
1698 
1699   if (IsMCUABI)
1700     return false;
1701 
1702   if (State.CC == llvm::CallingConv::X86_FastCall ||
1703       State.CC == llvm::CallingConv::X86_VectorCall ||
1704       State.CC == llvm::CallingConv::X86_RegCall) {
1705     if (getContext().getTypeSize(Ty) > 32)
1706       return false;
1707 
1708     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1709         Ty->isReferenceType());
1710   }
1711 
1712   return true;
1713 }
1714 
1715 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1716   // Vectorcall x86 works subtly different than in x64, so the format is
1717   // a bit different than the x64 version.  First, all vector types (not HVAs)
1718   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1719   // This differs from the x64 implementation, where the first 6 by INDEX get
1720   // registers.
1721   // In the second pass over the arguments, HVAs are passed in the remaining
1722   // vector registers if possible, or indirectly by address. The address will be
1723   // passed in ECX/EDX if available. Any other arguments are passed according to
1724   // the usual fastcall rules.
1725   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1726   for (int I = 0, E = Args.size(); I < E; ++I) {
1727     const Type *Base = nullptr;
1728     uint64_t NumElts = 0;
1729     const QualType &Ty = Args[I].type;
1730     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1731         isHomogeneousAggregate(Ty, Base, NumElts)) {
1732       if (State.FreeSSERegs >= NumElts) {
1733         State.FreeSSERegs -= NumElts;
1734         Args[I].info = ABIArgInfo::getDirectInReg();
1735         State.IsPreassigned.set(I);
1736       }
1737     }
1738   }
1739 }
1740 
1741 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1742                                                CCState &State) const {
1743   // FIXME: Set alignment on indirect arguments.
1744   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1745   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1746   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1747 
1748   Ty = useFirstFieldIfTransparentUnion(Ty);
1749   TypeInfo TI = getContext().getTypeInfo(Ty);
1750 
1751   // Check with the C++ ABI first.
1752   const RecordType *RT = Ty->getAs<RecordType>();
1753   if (RT) {
1754     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1755     if (RAA == CGCXXABI::RAA_Indirect) {
1756       return getIndirectResult(Ty, false, State);
1757     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1758       // The field index doesn't matter, we'll fix it up later.
1759       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1760     }
1761   }
1762 
1763   // Regcall uses the concept of a homogenous vector aggregate, similar
1764   // to other targets.
1765   const Type *Base = nullptr;
1766   uint64_t NumElts = 0;
1767   if ((IsRegCall || IsVectorCall) &&
1768       isHomogeneousAggregate(Ty, Base, NumElts)) {
1769     if (State.FreeSSERegs >= NumElts) {
1770       State.FreeSSERegs -= NumElts;
1771 
1772       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1773       // does.
1774       if (IsVectorCall)
1775         return getDirectX86Hva();
1776 
1777       if (Ty->isBuiltinType() || Ty->isVectorType())
1778         return ABIArgInfo::getDirect();
1779       return ABIArgInfo::getExpand();
1780     }
1781     return getIndirectResult(Ty, /*ByVal=*/false, State);
1782   }
1783 
1784   if (isAggregateTypeForABI(Ty)) {
1785     // Structures with flexible arrays are always indirect.
1786     // FIXME: This should not be byval!
1787     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1788       return getIndirectResult(Ty, true, State);
1789 
1790     // Ignore empty structs/unions on non-Windows.
1791     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1792       return ABIArgInfo::getIgnore();
1793 
1794     llvm::LLVMContext &LLVMContext = getVMContext();
1795     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1796     bool NeedsPadding = false;
1797     bool InReg;
1798     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1799       unsigned SizeInRegs = (TI.Width + 31) / 32;
1800       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1801       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1802       if (InReg)
1803         return ABIArgInfo::getDirectInReg(Result);
1804       else
1805         return ABIArgInfo::getDirect(Result);
1806     }
1807     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1808 
1809     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1810     // added in MSVC 2015.
1811     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1812       return getIndirectResult(Ty, /*ByVal=*/false, State);
1813 
1814     // Expand small (<= 128-bit) record types when we know that the stack layout
1815     // of those arguments will match the struct. This is important because the
1816     // LLVM backend isn't smart enough to remove byval, which inhibits many
1817     // optimizations.
1818     // Don't do this for the MCU if there are still free integer registers
1819     // (see X86_64 ABI for full explanation).
1820     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1821         canExpandIndirectArgument(Ty))
1822       return ABIArgInfo::getExpandWithPadding(
1823           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1824 
1825     return getIndirectResult(Ty, true, State);
1826   }
1827 
1828   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1829     // On Windows, vectors are passed directly if registers are available, or
1830     // indirectly if not. This avoids the need to align argument memory. Pass
1831     // user-defined vector types larger than 512 bits indirectly for simplicity.
1832     if (IsWin32StructABI) {
1833       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1834         --State.FreeSSERegs;
1835         return ABIArgInfo::getDirectInReg();
1836       }
1837       return getIndirectResult(Ty, /*ByVal=*/false, State);
1838     }
1839 
1840     // On Darwin, some vectors are passed in memory, we handle this by passing
1841     // it as an i8/i16/i32/i64.
1842     if (IsDarwinVectorABI) {
1843       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1844           (TI.Width == 64 && VT->getNumElements() == 1))
1845         return ABIArgInfo::getDirect(
1846             llvm::IntegerType::get(getVMContext(), TI.Width));
1847     }
1848 
1849     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1850       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1851 
1852     return ABIArgInfo::getDirect();
1853   }
1854 
1855 
1856   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1857     Ty = EnumTy->getDecl()->getIntegerType();
1858 
1859   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1860 
1861   if (isPromotableIntegerTypeForABI(Ty)) {
1862     if (InReg)
1863       return ABIArgInfo::getExtendInReg(Ty);
1864     return ABIArgInfo::getExtend(Ty);
1865   }
1866 
1867   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1868     if (EIT->getNumBits() <= 64) {
1869       if (InReg)
1870         return ABIArgInfo::getDirectInReg();
1871       return ABIArgInfo::getDirect();
1872     }
1873     return getIndirectResult(Ty, /*ByVal=*/false, State);
1874   }
1875 
1876   if (InReg)
1877     return ABIArgInfo::getDirectInReg();
1878   return ABIArgInfo::getDirect();
1879 }
1880 
1881 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1882   CCState State(FI);
1883   if (IsMCUABI)
1884     State.FreeRegs = 3;
1885   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1886     State.FreeRegs = 2;
1887     State.FreeSSERegs = 3;
1888   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1889     State.FreeRegs = 2;
1890     State.FreeSSERegs = 6;
1891   } else if (FI.getHasRegParm())
1892     State.FreeRegs = FI.getRegParm();
1893   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1894     State.FreeRegs = 5;
1895     State.FreeSSERegs = 8;
1896   } else if (IsWin32StructABI) {
1897     // Since MSVC 2015, the first three SSE vectors have been passed in
1898     // registers. The rest are passed indirectly.
1899     State.FreeRegs = DefaultNumRegisterParameters;
1900     State.FreeSSERegs = 3;
1901   } else
1902     State.FreeRegs = DefaultNumRegisterParameters;
1903 
1904   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1905     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1906   } else if (FI.getReturnInfo().isIndirect()) {
1907     // The C++ ABI is not aware of register usage, so we have to check if the
1908     // return value was sret and put it in a register ourselves if appropriate.
1909     if (State.FreeRegs) {
1910       --State.FreeRegs;  // The sret parameter consumes a register.
1911       if (!IsMCUABI)
1912         FI.getReturnInfo().setInReg(true);
1913     }
1914   }
1915 
1916   // The chain argument effectively gives us another free register.
1917   if (FI.isChainCall())
1918     ++State.FreeRegs;
1919 
1920   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1921   // arguments to XMM registers as available.
1922   if (State.CC == llvm::CallingConv::X86_VectorCall)
1923     runVectorCallFirstPass(FI, State);
1924 
1925   bool UsedInAlloca = false;
1926   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1927   for (int I = 0, E = Args.size(); I < E; ++I) {
1928     // Skip arguments that have already been assigned.
1929     if (State.IsPreassigned.test(I))
1930       continue;
1931 
1932     Args[I].info = classifyArgumentType(Args[I].type, State);
1933     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1934   }
1935 
1936   // If we needed to use inalloca for any argument, do a second pass and rewrite
1937   // all the memory arguments to use inalloca.
1938   if (UsedInAlloca)
1939     rewriteWithInAlloca(FI);
1940 }
1941 
1942 void
1943 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1944                                    CharUnits &StackOffset, ABIArgInfo &Info,
1945                                    QualType Type) const {
1946   // Arguments are always 4-byte-aligned.
1947   CharUnits WordSize = CharUnits::fromQuantity(4);
1948   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1949 
1950   // sret pointers and indirect things will require an extra pointer
1951   // indirection, unless they are byval. Most things are byval, and will not
1952   // require this indirection.
1953   bool IsIndirect = false;
1954   if (Info.isIndirect() && !Info.getIndirectByVal())
1955     IsIndirect = true;
1956   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1957   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1958   if (IsIndirect)
1959     LLTy = LLTy->getPointerTo(0);
1960   FrameFields.push_back(LLTy);
1961   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1962 
1963   // Insert padding bytes to respect alignment.
1964   CharUnits FieldEnd = StackOffset;
1965   StackOffset = FieldEnd.alignTo(WordSize);
1966   if (StackOffset != FieldEnd) {
1967     CharUnits NumBytes = StackOffset - FieldEnd;
1968     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1969     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1970     FrameFields.push_back(Ty);
1971   }
1972 }
1973 
1974 static bool isArgInAlloca(const ABIArgInfo &Info) {
1975   // Leave ignored and inreg arguments alone.
1976   switch (Info.getKind()) {
1977   case ABIArgInfo::InAlloca:
1978     return true;
1979   case ABIArgInfo::Ignore:
1980     return false;
1981   case ABIArgInfo::Indirect:
1982   case ABIArgInfo::Direct:
1983   case ABIArgInfo::Extend:
1984     return !Info.getInReg();
1985   case ABIArgInfo::Expand:
1986   case ABIArgInfo::CoerceAndExpand:
1987     // These are aggregate types which are never passed in registers when
1988     // inalloca is involved.
1989     return true;
1990   }
1991   llvm_unreachable("invalid enum");
1992 }
1993 
1994 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1995   assert(IsWin32StructABI && "inalloca only supported on win32");
1996 
1997   // Build a packed struct type for all of the arguments in memory.
1998   SmallVector<llvm::Type *, 6> FrameFields;
1999 
2000   // The stack alignment is always 4.
2001   CharUnits StackAlign = CharUnits::fromQuantity(4);
2002 
2003   CharUnits StackOffset;
2004   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2005 
2006   // Put 'this' into the struct before 'sret', if necessary.
2007   bool IsThisCall =
2008       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2009   ABIArgInfo &Ret = FI.getReturnInfo();
2010   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2011       isArgInAlloca(I->info)) {
2012     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2013     ++I;
2014   }
2015 
2016   // Put the sret parameter into the inalloca struct if it's in memory.
2017   if (Ret.isIndirect() && !Ret.getInReg()) {
2018     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2019     // On Windows, the hidden sret parameter is always returned in eax.
2020     Ret.setInAllocaSRet(IsWin32StructABI);
2021   }
2022 
2023   // Skip the 'this' parameter in ecx.
2024   if (IsThisCall)
2025     ++I;
2026 
2027   // Put arguments passed in memory into the struct.
2028   for (; I != E; ++I) {
2029     if (isArgInAlloca(I->info))
2030       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2031   }
2032 
2033   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2034                                         /*isPacked=*/true),
2035                   StackAlign);
2036 }
2037 
2038 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2039                                  Address VAListAddr, QualType Ty) const {
2040 
2041   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2042 
2043   // x86-32 changes the alignment of certain arguments on the stack.
2044   //
2045   // Just messing with TypeInfo like this works because we never pass
2046   // anything indirectly.
2047   TypeInfo.second = CharUnits::fromQuantity(
2048                 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
2049 
2050   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2051                           TypeInfo, CharUnits::fromQuantity(4),
2052                           /*AllowHigherAlign*/ true);
2053 }
2054 
2055 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2056     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2057   assert(Triple.getArch() == llvm::Triple::x86);
2058 
2059   switch (Opts.getStructReturnConvention()) {
2060   case CodeGenOptions::SRCK_Default:
2061     break;
2062   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2063     return false;
2064   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2065     return true;
2066   }
2067 
2068   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2069     return true;
2070 
2071   switch (Triple.getOS()) {
2072   case llvm::Triple::DragonFly:
2073   case llvm::Triple::FreeBSD:
2074   case llvm::Triple::OpenBSD:
2075   case llvm::Triple::Win32:
2076     return true;
2077   default:
2078     return false;
2079   }
2080 }
2081 
2082 void X86_32TargetCodeGenInfo::setTargetAttributes(
2083     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2084   if (GV->isDeclaration())
2085     return;
2086   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2087     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2088       llvm::Function *Fn = cast<llvm::Function>(GV);
2089       Fn->addFnAttr("stackrealign");
2090     }
2091     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2092       llvm::Function *Fn = cast<llvm::Function>(GV);
2093       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2094     }
2095   }
2096 }
2097 
2098 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2099                                                CodeGen::CodeGenFunction &CGF,
2100                                                llvm::Value *Address) const {
2101   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2102 
2103   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2104 
2105   // 0-7 are the eight integer registers;  the order is different
2106   //   on Darwin (for EH), but the range is the same.
2107   // 8 is %eip.
2108   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2109 
2110   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2111     // 12-16 are st(0..4).  Not sure why we stop at 4.
2112     // These have size 16, which is sizeof(long double) on
2113     // platforms with 8-byte alignment for that type.
2114     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2115     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2116 
2117   } else {
2118     // 9 is %eflags, which doesn't get a size on Darwin for some
2119     // reason.
2120     Builder.CreateAlignedStore(
2121         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2122                                CharUnits::One());
2123 
2124     // 11-16 are st(0..5).  Not sure why we stop at 5.
2125     // These have size 12, which is sizeof(long double) on
2126     // platforms with 4-byte alignment for that type.
2127     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2128     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2129   }
2130 
2131   return false;
2132 }
2133 
2134 //===----------------------------------------------------------------------===//
2135 // X86-64 ABI Implementation
2136 //===----------------------------------------------------------------------===//
2137 
2138 
2139 namespace {
2140 /// The AVX ABI level for X86 targets.
2141 enum class X86AVXABILevel {
2142   None,
2143   AVX,
2144   AVX512
2145 };
2146 
2147 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2148 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2149   switch (AVXLevel) {
2150   case X86AVXABILevel::AVX512:
2151     return 512;
2152   case X86AVXABILevel::AVX:
2153     return 256;
2154   case X86AVXABILevel::None:
2155     return 128;
2156   }
2157   llvm_unreachable("Unknown AVXLevel");
2158 }
2159 
2160 /// X86_64ABIInfo - The X86_64 ABI information.
2161 class X86_64ABIInfo : public SwiftABIInfo {
2162   enum Class {
2163     Integer = 0,
2164     SSE,
2165     SSEUp,
2166     X87,
2167     X87Up,
2168     ComplexX87,
2169     NoClass,
2170     Memory
2171   };
2172 
2173   /// merge - Implement the X86_64 ABI merging algorithm.
2174   ///
2175   /// Merge an accumulating classification \arg Accum with a field
2176   /// classification \arg Field.
2177   ///
2178   /// \param Accum - The accumulating classification. This should
2179   /// always be either NoClass or the result of a previous merge
2180   /// call. In addition, this should never be Memory (the caller
2181   /// should just return Memory for the aggregate).
2182   static Class merge(Class Accum, Class Field);
2183 
2184   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2185   ///
2186   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2187   /// final MEMORY or SSE classes when necessary.
2188   ///
2189   /// \param AggregateSize - The size of the current aggregate in
2190   /// the classification process.
2191   ///
2192   /// \param Lo - The classification for the parts of the type
2193   /// residing in the low word of the containing object.
2194   ///
2195   /// \param Hi - The classification for the parts of the type
2196   /// residing in the higher words of the containing object.
2197   ///
2198   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2199 
2200   /// classify - Determine the x86_64 register classes in which the
2201   /// given type T should be passed.
2202   ///
2203   /// \param Lo - The classification for the parts of the type
2204   /// residing in the low word of the containing object.
2205   ///
2206   /// \param Hi - The classification for the parts of the type
2207   /// residing in the high word of the containing object.
2208   ///
2209   /// \param OffsetBase - The bit offset of this type in the
2210   /// containing object.  Some parameters are classified different
2211   /// depending on whether they straddle an eightbyte boundary.
2212   ///
2213   /// \param isNamedArg - Whether the argument in question is a "named"
2214   /// argument, as used in AMD64-ABI 3.5.7.
2215   ///
2216   /// If a word is unused its result will be NoClass; if a type should
2217   /// be passed in Memory then at least the classification of \arg Lo
2218   /// will be Memory.
2219   ///
2220   /// The \arg Lo class will be NoClass iff the argument is ignored.
2221   ///
2222   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2223   /// also be ComplexX87.
2224   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2225                 bool isNamedArg) const;
2226 
2227   llvm::Type *GetByteVectorType(QualType Ty) const;
2228   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2229                                  unsigned IROffset, QualType SourceTy,
2230                                  unsigned SourceOffset) const;
2231   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2232                                      unsigned IROffset, QualType SourceTy,
2233                                      unsigned SourceOffset) const;
2234 
2235   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2236   /// such that the argument will be returned in memory.
2237   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2238 
2239   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2240   /// such that the argument will be passed in memory.
2241   ///
2242   /// \param freeIntRegs - The number of free integer registers remaining
2243   /// available.
2244   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2245 
2246   ABIArgInfo classifyReturnType(QualType RetTy) const;
2247 
2248   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2249                                   unsigned &neededInt, unsigned &neededSSE,
2250                                   bool isNamedArg) const;
2251 
2252   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2253                                        unsigned &NeededSSE) const;
2254 
2255   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2256                                            unsigned &NeededSSE) const;
2257 
2258   bool IsIllegalVectorType(QualType Ty) const;
2259 
2260   /// The 0.98 ABI revision clarified a lot of ambiguities,
2261   /// unfortunately in ways that were not always consistent with
2262   /// certain previous compilers.  In particular, platforms which
2263   /// required strict binary compatibility with older versions of GCC
2264   /// may need to exempt themselves.
2265   bool honorsRevision0_98() const {
2266     return !getTarget().getTriple().isOSDarwin();
2267   }
2268 
2269   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2270   /// classify it as INTEGER (for compatibility with older clang compilers).
2271   bool classifyIntegerMMXAsSSE() const {
2272     // Clang <= 3.8 did not do this.
2273     if (getContext().getLangOpts().getClangABICompat() <=
2274         LangOptions::ClangABI::Ver3_8)
2275       return false;
2276 
2277     const llvm::Triple &Triple = getTarget().getTriple();
2278     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2279       return false;
2280     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2281       return false;
2282     return true;
2283   }
2284 
2285   // GCC classifies vectors of __int128 as memory.
2286   bool passInt128VectorsInMem() const {
2287     // Clang <= 9.0 did not do this.
2288     if (getContext().getLangOpts().getClangABICompat() <=
2289         LangOptions::ClangABI::Ver9)
2290       return false;
2291 
2292     const llvm::Triple &T = getTarget().getTriple();
2293     return T.isOSLinux() || T.isOSNetBSD();
2294   }
2295 
2296   X86AVXABILevel AVXLevel;
2297   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2298   // 64-bit hardware.
2299   bool Has64BitPointers;
2300 
2301 public:
2302   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2303       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2304       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2305   }
2306 
2307   bool isPassedUsingAVXType(QualType type) const {
2308     unsigned neededInt, neededSSE;
2309     // The freeIntRegs argument doesn't matter here.
2310     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2311                                            /*isNamedArg*/true);
2312     if (info.isDirect()) {
2313       llvm::Type *ty = info.getCoerceToType();
2314       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2315         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2316     }
2317     return false;
2318   }
2319 
2320   void computeInfo(CGFunctionInfo &FI) const override;
2321 
2322   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2323                     QualType Ty) const override;
2324   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2325                       QualType Ty) const override;
2326 
2327   bool has64BitPointers() const {
2328     return Has64BitPointers;
2329   }
2330 
2331   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2332                                     bool asReturnValue) const override {
2333     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2334   }
2335   bool isSwiftErrorInRegister() const override {
2336     return true;
2337   }
2338 };
2339 
2340 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2341 class WinX86_64ABIInfo : public SwiftABIInfo {
2342 public:
2343   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2344       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2345         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2346 
2347   void computeInfo(CGFunctionInfo &FI) const override;
2348 
2349   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2350                     QualType Ty) const override;
2351 
2352   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2353     // FIXME: Assumes vectorcall is in use.
2354     return isX86VectorTypeForVectorCall(getContext(), Ty);
2355   }
2356 
2357   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2358                                          uint64_t NumMembers) const override {
2359     // FIXME: Assumes vectorcall is in use.
2360     return isX86VectorCallAggregateSmallEnough(NumMembers);
2361   }
2362 
2363   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2364                                     bool asReturnValue) const override {
2365     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2366   }
2367 
2368   bool isSwiftErrorInRegister() const override {
2369     return true;
2370   }
2371 
2372 private:
2373   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2374                       bool IsVectorCall, bool IsRegCall) const;
2375   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2376                                       const ABIArgInfo &current) const;
2377   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2378                              bool IsVectorCall, bool IsRegCall) const;
2379 
2380   X86AVXABILevel AVXLevel;
2381 
2382   bool IsMingw64;
2383 };
2384 
2385 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2386 public:
2387   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2388       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2389 
2390   const X86_64ABIInfo &getABIInfo() const {
2391     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2392   }
2393 
2394   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2395   /// the autoreleaseRV/retainRV optimization.
2396   bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2397     return true;
2398   }
2399 
2400   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2401     return 7;
2402   }
2403 
2404   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2405                                llvm::Value *Address) const override {
2406     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2407 
2408     // 0-15 are the 16 integer registers.
2409     // 16 is %rip.
2410     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2411     return false;
2412   }
2413 
2414   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2415                                   StringRef Constraint,
2416                                   llvm::Type* Ty) const override {
2417     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2418   }
2419 
2420   bool isNoProtoCallVariadic(const CallArgList &args,
2421                              const FunctionNoProtoType *fnType) const override {
2422     // The default CC on x86-64 sets %al to the number of SSA
2423     // registers used, and GCC sets this when calling an unprototyped
2424     // function, so we override the default behavior.  However, don't do
2425     // that when AVX types are involved: the ABI explicitly states it is
2426     // undefined, and it doesn't work in practice because of how the ABI
2427     // defines varargs anyway.
2428     if (fnType->getCallConv() == CC_C) {
2429       bool HasAVXType = false;
2430       for (CallArgList::const_iterator
2431              it = args.begin(), ie = args.end(); it != ie; ++it) {
2432         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2433           HasAVXType = true;
2434           break;
2435         }
2436       }
2437 
2438       if (!HasAVXType)
2439         return true;
2440     }
2441 
2442     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2443   }
2444 
2445   llvm::Constant *
2446   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2447     unsigned Sig = (0xeb << 0) | // jmp rel8
2448                    (0x06 << 8) | //           .+0x08
2449                    ('v' << 16) |
2450                    ('2' << 24);
2451     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2452   }
2453 
2454   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2455                            CodeGen::CodeGenModule &CGM) const override {
2456     if (GV->isDeclaration())
2457       return;
2458     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2459       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2460         llvm::Function *Fn = cast<llvm::Function>(GV);
2461         Fn->addFnAttr("stackrealign");
2462       }
2463       if (FD->hasAttr<AnyX86InterruptAttr>()) {
2464         llvm::Function *Fn = cast<llvm::Function>(GV);
2465         Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2466       }
2467     }
2468   }
2469 };
2470 
2471 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2472   // If the argument does not end in .lib, automatically add the suffix.
2473   // If the argument contains a space, enclose it in quotes.
2474   // This matches the behavior of MSVC.
2475   bool Quote = (Lib.find(" ") != StringRef::npos);
2476   std::string ArgStr = Quote ? "\"" : "";
2477   ArgStr += Lib;
2478   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2479     ArgStr += ".lib";
2480   ArgStr += Quote ? "\"" : "";
2481   return ArgStr;
2482 }
2483 
2484 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2485 public:
2486   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2487         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2488         unsigned NumRegisterParameters)
2489     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2490         Win32StructABI, NumRegisterParameters, false) {}
2491 
2492   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2493                            CodeGen::CodeGenModule &CGM) const override;
2494 
2495   void getDependentLibraryOption(llvm::StringRef Lib,
2496                                  llvm::SmallString<24> &Opt) const override {
2497     Opt = "/DEFAULTLIB:";
2498     Opt += qualifyWindowsLibrary(Lib);
2499   }
2500 
2501   void getDetectMismatchOption(llvm::StringRef Name,
2502                                llvm::StringRef Value,
2503                                llvm::SmallString<32> &Opt) const override {
2504     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2505   }
2506 };
2507 
2508 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2509                                           CodeGen::CodeGenModule &CGM) {
2510   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2511 
2512     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2513       Fn->addFnAttr("stack-probe-size",
2514                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2515     if (CGM.getCodeGenOpts().NoStackArgProbe)
2516       Fn->addFnAttr("no-stack-arg-probe");
2517   }
2518 }
2519 
2520 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2521     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2522   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2523   if (GV->isDeclaration())
2524     return;
2525   addStackProbeTargetAttributes(D, GV, CGM);
2526 }
2527 
2528 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2529 public:
2530   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2531                              X86AVXABILevel AVXLevel)
2532       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2533 
2534   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2535                            CodeGen::CodeGenModule &CGM) const override;
2536 
2537   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2538     return 7;
2539   }
2540 
2541   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2542                                llvm::Value *Address) const override {
2543     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2544 
2545     // 0-15 are the 16 integer registers.
2546     // 16 is %rip.
2547     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2548     return false;
2549   }
2550 
2551   void getDependentLibraryOption(llvm::StringRef Lib,
2552                                  llvm::SmallString<24> &Opt) const override {
2553     Opt = "/DEFAULTLIB:";
2554     Opt += qualifyWindowsLibrary(Lib);
2555   }
2556 
2557   void getDetectMismatchOption(llvm::StringRef Name,
2558                                llvm::StringRef Value,
2559                                llvm::SmallString<32> &Opt) const override {
2560     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2561   }
2562 };
2563 
2564 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2565     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2566   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2567   if (GV->isDeclaration())
2568     return;
2569   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2570     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2571       llvm::Function *Fn = cast<llvm::Function>(GV);
2572       Fn->addFnAttr("stackrealign");
2573     }
2574     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2575       llvm::Function *Fn = cast<llvm::Function>(GV);
2576       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2577     }
2578   }
2579 
2580   addStackProbeTargetAttributes(D, GV, CGM);
2581 }
2582 }
2583 
2584 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2585                               Class &Hi) const {
2586   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2587   //
2588   // (a) If one of the classes is Memory, the whole argument is passed in
2589   //     memory.
2590   //
2591   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2592   //     memory.
2593   //
2594   // (c) If the size of the aggregate exceeds two eightbytes and the first
2595   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2596   //     argument is passed in memory. NOTE: This is necessary to keep the
2597   //     ABI working for processors that don't support the __m256 type.
2598   //
2599   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2600   //
2601   // Some of these are enforced by the merging logic.  Others can arise
2602   // only with unions; for example:
2603   //   union { _Complex double; unsigned; }
2604   //
2605   // Note that clauses (b) and (c) were added in 0.98.
2606   //
2607   if (Hi == Memory)
2608     Lo = Memory;
2609   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2610     Lo = Memory;
2611   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2612     Lo = Memory;
2613   if (Hi == SSEUp && Lo != SSE)
2614     Hi = SSE;
2615 }
2616 
2617 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2618   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2619   // classified recursively so that always two fields are
2620   // considered. The resulting class is calculated according to
2621   // the classes of the fields in the eightbyte:
2622   //
2623   // (a) If both classes are equal, this is the resulting class.
2624   //
2625   // (b) If one of the classes is NO_CLASS, the resulting class is
2626   // the other class.
2627   //
2628   // (c) If one of the classes is MEMORY, the result is the MEMORY
2629   // class.
2630   //
2631   // (d) If one of the classes is INTEGER, the result is the
2632   // INTEGER.
2633   //
2634   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2635   // MEMORY is used as class.
2636   //
2637   // (f) Otherwise class SSE is used.
2638 
2639   // Accum should never be memory (we should have returned) or
2640   // ComplexX87 (because this cannot be passed in a structure).
2641   assert((Accum != Memory && Accum != ComplexX87) &&
2642          "Invalid accumulated classification during merge.");
2643   if (Accum == Field || Field == NoClass)
2644     return Accum;
2645   if (Field == Memory)
2646     return Memory;
2647   if (Accum == NoClass)
2648     return Field;
2649   if (Accum == Integer || Field == Integer)
2650     return Integer;
2651   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2652       Accum == X87 || Accum == X87Up)
2653     return Memory;
2654   return SSE;
2655 }
2656 
2657 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2658                              Class &Lo, Class &Hi, bool isNamedArg) const {
2659   // FIXME: This code can be simplified by introducing a simple value class for
2660   // Class pairs with appropriate constructor methods for the various
2661   // situations.
2662 
2663   // FIXME: Some of the split computations are wrong; unaligned vectors
2664   // shouldn't be passed in registers for example, so there is no chance they
2665   // can straddle an eightbyte. Verify & simplify.
2666 
2667   Lo = Hi = NoClass;
2668 
2669   Class &Current = OffsetBase < 64 ? Lo : Hi;
2670   Current = Memory;
2671 
2672   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2673     BuiltinType::Kind k = BT->getKind();
2674 
2675     if (k == BuiltinType::Void) {
2676       Current = NoClass;
2677     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2678       Lo = Integer;
2679       Hi = Integer;
2680     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2681       Current = Integer;
2682     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2683       Current = SSE;
2684     } else if (k == BuiltinType::LongDouble) {
2685       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2686       if (LDF == &llvm::APFloat::IEEEquad()) {
2687         Lo = SSE;
2688         Hi = SSEUp;
2689       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2690         Lo = X87;
2691         Hi = X87Up;
2692       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2693         Current = SSE;
2694       } else
2695         llvm_unreachable("unexpected long double representation!");
2696     }
2697     // FIXME: _Decimal32 and _Decimal64 are SSE.
2698     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2699     return;
2700   }
2701 
2702   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2703     // Classify the underlying integer type.
2704     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2705     return;
2706   }
2707 
2708   if (Ty->hasPointerRepresentation()) {
2709     Current = Integer;
2710     return;
2711   }
2712 
2713   if (Ty->isMemberPointerType()) {
2714     if (Ty->isMemberFunctionPointerType()) {
2715       if (Has64BitPointers) {
2716         // If Has64BitPointers, this is an {i64, i64}, so classify both
2717         // Lo and Hi now.
2718         Lo = Hi = Integer;
2719       } else {
2720         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2721         // straddles an eightbyte boundary, Hi should be classified as well.
2722         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2723         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2724         if (EB_FuncPtr != EB_ThisAdj) {
2725           Lo = Hi = Integer;
2726         } else {
2727           Current = Integer;
2728         }
2729       }
2730     } else {
2731       Current = Integer;
2732     }
2733     return;
2734   }
2735 
2736   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2737     uint64_t Size = getContext().getTypeSize(VT);
2738     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2739       // gcc passes the following as integer:
2740       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2741       // 2 bytes - <2 x char>, <1 x short>
2742       // 1 byte  - <1 x char>
2743       Current = Integer;
2744 
2745       // If this type crosses an eightbyte boundary, it should be
2746       // split.
2747       uint64_t EB_Lo = (OffsetBase) / 64;
2748       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2749       if (EB_Lo != EB_Hi)
2750         Hi = Lo;
2751     } else if (Size == 64) {
2752       QualType ElementType = VT->getElementType();
2753 
2754       // gcc passes <1 x double> in memory. :(
2755       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2756         return;
2757 
2758       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2759       // pass them as integer.  For platforms where clang is the de facto
2760       // platform compiler, we must continue to use integer.
2761       if (!classifyIntegerMMXAsSSE() &&
2762           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2763            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2764            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2765            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2766         Current = Integer;
2767       else
2768         Current = SSE;
2769 
2770       // If this type crosses an eightbyte boundary, it should be
2771       // split.
2772       if (OffsetBase && OffsetBase != 64)
2773         Hi = Lo;
2774     } else if (Size == 128 ||
2775                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2776       QualType ElementType = VT->getElementType();
2777 
2778       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2779       if (passInt128VectorsInMem() && Size != 128 &&
2780           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2781            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2782         return;
2783 
2784       // Arguments of 256-bits are split into four eightbyte chunks. The
2785       // least significant one belongs to class SSE and all the others to class
2786       // SSEUP. The original Lo and Hi design considers that types can't be
2787       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2788       // This design isn't correct for 256-bits, but since there're no cases
2789       // where the upper parts would need to be inspected, avoid adding
2790       // complexity and just consider Hi to match the 64-256 part.
2791       //
2792       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2793       // registers if they are "named", i.e. not part of the "..." of a
2794       // variadic function.
2795       //
2796       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2797       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2798       Lo = SSE;
2799       Hi = SSEUp;
2800     }
2801     return;
2802   }
2803 
2804   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2805     QualType ET = getContext().getCanonicalType(CT->getElementType());
2806 
2807     uint64_t Size = getContext().getTypeSize(Ty);
2808     if (ET->isIntegralOrEnumerationType()) {
2809       if (Size <= 64)
2810         Current = Integer;
2811       else if (Size <= 128)
2812         Lo = Hi = Integer;
2813     } else if (ET == getContext().FloatTy) {
2814       Current = SSE;
2815     } else if (ET == getContext().DoubleTy) {
2816       Lo = Hi = SSE;
2817     } else if (ET == getContext().LongDoubleTy) {
2818       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2819       if (LDF == &llvm::APFloat::IEEEquad())
2820         Current = Memory;
2821       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2822         Current = ComplexX87;
2823       else if (LDF == &llvm::APFloat::IEEEdouble())
2824         Lo = Hi = SSE;
2825       else
2826         llvm_unreachable("unexpected long double representation!");
2827     }
2828 
2829     // If this complex type crosses an eightbyte boundary then it
2830     // should be split.
2831     uint64_t EB_Real = (OffsetBase) / 64;
2832     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2833     if (Hi == NoClass && EB_Real != EB_Imag)
2834       Hi = Lo;
2835 
2836     return;
2837   }
2838 
2839   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2840     if (EITy->getNumBits() <= 64)
2841       Current = Integer;
2842     else if (EITy->getNumBits() <= 128)
2843       Lo = Hi = Integer;
2844     // Larger values need to get passed in memory.
2845     return;
2846   }
2847 
2848   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2849     // Arrays are treated like structures.
2850 
2851     uint64_t Size = getContext().getTypeSize(Ty);
2852 
2853     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2854     // than eight eightbytes, ..., it has class MEMORY.
2855     if (Size > 512)
2856       return;
2857 
2858     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2859     // fields, it has class MEMORY.
2860     //
2861     // Only need to check alignment of array base.
2862     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2863       return;
2864 
2865     // Otherwise implement simplified merge. We could be smarter about
2866     // this, but it isn't worth it and would be harder to verify.
2867     Current = NoClass;
2868     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2869     uint64_t ArraySize = AT->getSize().getZExtValue();
2870 
2871     // The only case a 256-bit wide vector could be used is when the array
2872     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2873     // to work for sizes wider than 128, early check and fallback to memory.
2874     //
2875     if (Size > 128 &&
2876         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2877       return;
2878 
2879     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2880       Class FieldLo, FieldHi;
2881       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2882       Lo = merge(Lo, FieldLo);
2883       Hi = merge(Hi, FieldHi);
2884       if (Lo == Memory || Hi == Memory)
2885         break;
2886     }
2887 
2888     postMerge(Size, Lo, Hi);
2889     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2890     return;
2891   }
2892 
2893   if (const RecordType *RT = Ty->getAs<RecordType>()) {
2894     uint64_t Size = getContext().getTypeSize(Ty);
2895 
2896     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2897     // than eight eightbytes, ..., it has class MEMORY.
2898     if (Size > 512)
2899       return;
2900 
2901     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2902     // copy constructor or a non-trivial destructor, it is passed by invisible
2903     // reference.
2904     if (getRecordArgABI(RT, getCXXABI()))
2905       return;
2906 
2907     const RecordDecl *RD = RT->getDecl();
2908 
2909     // Assume variable sized types are passed in memory.
2910     if (RD->hasFlexibleArrayMember())
2911       return;
2912 
2913     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2914 
2915     // Reset Lo class, this will be recomputed.
2916     Current = NoClass;
2917 
2918     // If this is a C++ record, classify the bases first.
2919     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2920       for (const auto &I : CXXRD->bases()) {
2921         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2922                "Unexpected base class!");
2923         const auto *Base =
2924             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2925 
2926         // Classify this field.
2927         //
2928         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2929         // single eightbyte, each is classified separately. Each eightbyte gets
2930         // initialized to class NO_CLASS.
2931         Class FieldLo, FieldHi;
2932         uint64_t Offset =
2933           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2934         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2935         Lo = merge(Lo, FieldLo);
2936         Hi = merge(Hi, FieldHi);
2937         if (Lo == Memory || Hi == Memory) {
2938           postMerge(Size, Lo, Hi);
2939           return;
2940         }
2941       }
2942     }
2943 
2944     // Classify the fields one at a time, merging the results.
2945     unsigned idx = 0;
2946     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2947            i != e; ++i, ++idx) {
2948       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2949       bool BitField = i->isBitField();
2950 
2951       // Ignore padding bit-fields.
2952       if (BitField && i->isUnnamedBitfield())
2953         continue;
2954 
2955       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2956       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2957       //
2958       // The only case a 256-bit wide vector could be used is when the struct
2959       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2960       // to work for sizes wider than 128, early check and fallback to memory.
2961       //
2962       if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2963                          Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2964         Lo = Memory;
2965         postMerge(Size, Lo, Hi);
2966         return;
2967       }
2968       // Note, skip this test for bit-fields, see below.
2969       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2970         Lo = Memory;
2971         postMerge(Size, Lo, Hi);
2972         return;
2973       }
2974 
2975       // Classify this field.
2976       //
2977       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2978       // exceeds a single eightbyte, each is classified
2979       // separately. Each eightbyte gets initialized to class
2980       // NO_CLASS.
2981       Class FieldLo, FieldHi;
2982 
2983       // Bit-fields require special handling, they do not force the
2984       // structure to be passed in memory even if unaligned, and
2985       // therefore they can straddle an eightbyte.
2986       if (BitField) {
2987         assert(!i->isUnnamedBitfield());
2988         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2989         uint64_t Size = i->getBitWidthValue(getContext());
2990 
2991         uint64_t EB_Lo = Offset / 64;
2992         uint64_t EB_Hi = (Offset + Size - 1) / 64;
2993 
2994         if (EB_Lo) {
2995           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2996           FieldLo = NoClass;
2997           FieldHi = Integer;
2998         } else {
2999           FieldLo = Integer;
3000           FieldHi = EB_Hi ? Integer : NoClass;
3001         }
3002       } else
3003         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3004       Lo = merge(Lo, FieldLo);
3005       Hi = merge(Hi, FieldHi);
3006       if (Lo == Memory || Hi == Memory)
3007         break;
3008     }
3009 
3010     postMerge(Size, Lo, Hi);
3011   }
3012 }
3013 
3014 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3015   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3016   // place naturally.
3017   if (!isAggregateTypeForABI(Ty)) {
3018     // Treat an enum type as its underlying type.
3019     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3020       Ty = EnumTy->getDecl()->getIntegerType();
3021 
3022     if (Ty->isExtIntType())
3023       return getNaturalAlignIndirect(Ty);
3024 
3025     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3026                                               : ABIArgInfo::getDirect());
3027   }
3028 
3029   return getNaturalAlignIndirect(Ty);
3030 }
3031 
3032 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3033   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3034     uint64_t Size = getContext().getTypeSize(VecTy);
3035     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3036     if (Size <= 64 || Size > LargestVector)
3037       return true;
3038     QualType EltTy = VecTy->getElementType();
3039     if (passInt128VectorsInMem() &&
3040         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3041          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3042       return true;
3043   }
3044 
3045   return false;
3046 }
3047 
3048 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3049                                             unsigned freeIntRegs) const {
3050   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3051   // place naturally.
3052   //
3053   // This assumption is optimistic, as there could be free registers available
3054   // when we need to pass this argument in memory, and LLVM could try to pass
3055   // the argument in the free register. This does not seem to happen currently,
3056   // but this code would be much safer if we could mark the argument with
3057   // 'onstack'. See PR12193.
3058   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3059       !Ty->isExtIntType()) {
3060     // Treat an enum type as its underlying type.
3061     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3062       Ty = EnumTy->getDecl()->getIntegerType();
3063 
3064     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3065                                               : ABIArgInfo::getDirect());
3066   }
3067 
3068   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3069     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3070 
3071   // Compute the byval alignment. We specify the alignment of the byval in all
3072   // cases so that the mid-level optimizer knows the alignment of the byval.
3073   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3074 
3075   // Attempt to avoid passing indirect results using byval when possible. This
3076   // is important for good codegen.
3077   //
3078   // We do this by coercing the value into a scalar type which the backend can
3079   // handle naturally (i.e., without using byval).
3080   //
3081   // For simplicity, we currently only do this when we have exhausted all of the
3082   // free integer registers. Doing this when there are free integer registers
3083   // would require more care, as we would have to ensure that the coerced value
3084   // did not claim the unused register. That would require either reording the
3085   // arguments to the function (so that any subsequent inreg values came first),
3086   // or only doing this optimization when there were no following arguments that
3087   // might be inreg.
3088   //
3089   // We currently expect it to be rare (particularly in well written code) for
3090   // arguments to be passed on the stack when there are still free integer
3091   // registers available (this would typically imply large structs being passed
3092   // by value), so this seems like a fair tradeoff for now.
3093   //
3094   // We can revisit this if the backend grows support for 'onstack' parameter
3095   // attributes. See PR12193.
3096   if (freeIntRegs == 0) {
3097     uint64_t Size = getContext().getTypeSize(Ty);
3098 
3099     // If this type fits in an eightbyte, coerce it into the matching integral
3100     // type, which will end up on the stack (with alignment 8).
3101     if (Align == 8 && Size <= 64)
3102       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3103                                                           Size));
3104   }
3105 
3106   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3107 }
3108 
3109 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3110 /// register. Pick an LLVM IR type that will be passed as a vector register.
3111 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3112   // Wrapper structs/arrays that only contain vectors are passed just like
3113   // vectors; strip them off if present.
3114   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3115     Ty = QualType(InnerTy, 0);
3116 
3117   llvm::Type *IRType = CGT.ConvertType(Ty);
3118   if (isa<llvm::VectorType>(IRType)) {
3119     // Don't pass vXi128 vectors in their native type, the backend can't
3120     // legalize them.
3121     if (passInt128VectorsInMem() &&
3122         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3123       // Use a vXi64 vector.
3124       uint64_t Size = getContext().getTypeSize(Ty);
3125       return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3126                                    Size / 64);
3127     }
3128 
3129     return IRType;
3130   }
3131 
3132   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3133     return IRType;
3134 
3135   // We couldn't find the preferred IR vector type for 'Ty'.
3136   uint64_t Size = getContext().getTypeSize(Ty);
3137   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3138 
3139 
3140   // Return a LLVM IR vector type based on the size of 'Ty'.
3141   return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3142                                Size / 64);
3143 }
3144 
3145 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3146 /// is known to either be off the end of the specified type or being in
3147 /// alignment padding.  The user type specified is known to be at most 128 bits
3148 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3149 /// classification that put one of the two halves in the INTEGER class.
3150 ///
3151 /// It is conservatively correct to return false.
3152 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3153                                   unsigned EndBit, ASTContext &Context) {
3154   // If the bytes being queried are off the end of the type, there is no user
3155   // data hiding here.  This handles analysis of builtins, vectors and other
3156   // types that don't contain interesting padding.
3157   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3158   if (TySize <= StartBit)
3159     return true;
3160 
3161   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3162     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3163     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3164 
3165     // Check each element to see if the element overlaps with the queried range.
3166     for (unsigned i = 0; i != NumElts; ++i) {
3167       // If the element is after the span we care about, then we're done..
3168       unsigned EltOffset = i*EltSize;
3169       if (EltOffset >= EndBit) break;
3170 
3171       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3172       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3173                                  EndBit-EltOffset, Context))
3174         return false;
3175     }
3176     // If it overlaps no elements, then it is safe to process as padding.
3177     return true;
3178   }
3179 
3180   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3181     const RecordDecl *RD = RT->getDecl();
3182     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3183 
3184     // If this is a C++ record, check the bases first.
3185     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3186       for (const auto &I : CXXRD->bases()) {
3187         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3188                "Unexpected base class!");
3189         const auto *Base =
3190             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3191 
3192         // If the base is after the span we care about, ignore it.
3193         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3194         if (BaseOffset >= EndBit) continue;
3195 
3196         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3197         if (!BitsContainNoUserData(I.getType(), BaseStart,
3198                                    EndBit-BaseOffset, Context))
3199           return false;
3200       }
3201     }
3202 
3203     // Verify that no field has data that overlaps the region of interest.  Yes
3204     // this could be sped up a lot by being smarter about queried fields,
3205     // however we're only looking at structs up to 16 bytes, so we don't care
3206     // much.
3207     unsigned idx = 0;
3208     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3209          i != e; ++i, ++idx) {
3210       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3211 
3212       // If we found a field after the region we care about, then we're done.
3213       if (FieldOffset >= EndBit) break;
3214 
3215       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3216       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3217                                  Context))
3218         return false;
3219     }
3220 
3221     // If nothing in this record overlapped the area of interest, then we're
3222     // clean.
3223     return true;
3224   }
3225 
3226   return false;
3227 }
3228 
3229 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3230 /// float member at the specified offset.  For example, {int,{float}} has a
3231 /// float at offset 4.  It is conservatively correct for this routine to return
3232 /// false.
3233 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3234                                   const llvm::DataLayout &TD) {
3235   // Base case if we find a float.
3236   if (IROffset == 0 && IRType->isFloatTy())
3237     return true;
3238 
3239   // If this is a struct, recurse into the field at the specified offset.
3240   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3241     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3242     unsigned Elt = SL->getElementContainingOffset(IROffset);
3243     IROffset -= SL->getElementOffset(Elt);
3244     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3245   }
3246 
3247   // If this is an array, recurse into the field at the specified offset.
3248   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3249     llvm::Type *EltTy = ATy->getElementType();
3250     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3251     IROffset -= IROffset/EltSize*EltSize;
3252     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3253   }
3254 
3255   return false;
3256 }
3257 
3258 
3259 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3260 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3261 llvm::Type *X86_64ABIInfo::
3262 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3263                    QualType SourceTy, unsigned SourceOffset) const {
3264   // The only three choices we have are either double, <2 x float>, or float. We
3265   // pass as float if the last 4 bytes is just padding.  This happens for
3266   // structs that contain 3 floats.
3267   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3268                             SourceOffset*8+64, getContext()))
3269     return llvm::Type::getFloatTy(getVMContext());
3270 
3271   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3272   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3273   // case.
3274   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3275       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3276     return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3277 
3278   return llvm::Type::getDoubleTy(getVMContext());
3279 }
3280 
3281 
3282 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3283 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3284 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3285 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3286 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3287 /// etc).
3288 ///
3289 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3290 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3291 /// the 8-byte value references.  PrefType may be null.
3292 ///
3293 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3294 /// an offset into this that we're processing (which is always either 0 or 8).
3295 ///
3296 llvm::Type *X86_64ABIInfo::
3297 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3298                        QualType SourceTy, unsigned SourceOffset) const {
3299   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3300   // returning an 8-byte unit starting with it.  See if we can safely use it.
3301   if (IROffset == 0) {
3302     // Pointers and int64's always fill the 8-byte unit.
3303     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3304         IRType->isIntegerTy(64))
3305       return IRType;
3306 
3307     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3308     // goodness in the source type is just tail padding.  This is allowed to
3309     // kick in for struct {double,int} on the int, but not on
3310     // struct{double,int,int} because we wouldn't return the second int.  We
3311     // have to do this analysis on the source type because we can't depend on
3312     // unions being lowered a specific way etc.
3313     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3314         IRType->isIntegerTy(32) ||
3315         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3316       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3317           cast<llvm::IntegerType>(IRType)->getBitWidth();
3318 
3319       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3320                                 SourceOffset*8+64, getContext()))
3321         return IRType;
3322     }
3323   }
3324 
3325   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3326     // If this is a struct, recurse into the field at the specified offset.
3327     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3328     if (IROffset < SL->getSizeInBytes()) {
3329       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3330       IROffset -= SL->getElementOffset(FieldIdx);
3331 
3332       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3333                                     SourceTy, SourceOffset);
3334     }
3335   }
3336 
3337   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3338     llvm::Type *EltTy = ATy->getElementType();
3339     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3340     unsigned EltOffset = IROffset/EltSize*EltSize;
3341     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3342                                   SourceOffset);
3343   }
3344 
3345   // Okay, we don't have any better idea of what to pass, so we pass this in an
3346   // integer register that isn't too big to fit the rest of the struct.
3347   unsigned TySizeInBytes =
3348     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3349 
3350   assert(TySizeInBytes != SourceOffset && "Empty field?");
3351 
3352   // It is always safe to classify this as an integer type up to i64 that
3353   // isn't larger than the structure.
3354   return llvm::IntegerType::get(getVMContext(),
3355                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3356 }
3357 
3358 
3359 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3360 /// be used as elements of a two register pair to pass or return, return a
3361 /// first class aggregate to represent them.  For example, if the low part of
3362 /// a by-value argument should be passed as i32* and the high part as float,
3363 /// return {i32*, float}.
3364 static llvm::Type *
3365 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3366                            const llvm::DataLayout &TD) {
3367   // In order to correctly satisfy the ABI, we need to the high part to start
3368   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3369   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3370   // the second element at offset 8.  Check for this:
3371   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3372   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3373   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3374   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3375 
3376   // To handle this, we have to increase the size of the low part so that the
3377   // second element will start at an 8 byte offset.  We can't increase the size
3378   // of the second element because it might make us access off the end of the
3379   // struct.
3380   if (HiStart != 8) {
3381     // There are usually two sorts of types the ABI generation code can produce
3382     // for the low part of a pair that aren't 8 bytes in size: float or
3383     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3384     // NaCl).
3385     // Promote these to a larger type.
3386     if (Lo->isFloatTy())
3387       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3388     else {
3389       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3390              && "Invalid/unknown lo type");
3391       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3392     }
3393   }
3394 
3395   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3396 
3397   // Verify that the second element is at an 8-byte offset.
3398   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3399          "Invalid x86-64 argument pair!");
3400   return Result;
3401 }
3402 
3403 ABIArgInfo X86_64ABIInfo::
3404 classifyReturnType(QualType RetTy) const {
3405   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3406   // classification algorithm.
3407   X86_64ABIInfo::Class Lo, Hi;
3408   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3409 
3410   // Check some invariants.
3411   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3412   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3413 
3414   llvm::Type *ResType = nullptr;
3415   switch (Lo) {
3416   case NoClass:
3417     if (Hi == NoClass)
3418       return ABIArgInfo::getIgnore();
3419     // If the low part is just padding, it takes no register, leave ResType
3420     // null.
3421     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3422            "Unknown missing lo part");
3423     break;
3424 
3425   case SSEUp:
3426   case X87Up:
3427     llvm_unreachable("Invalid classification for lo word.");
3428 
3429     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3430     // hidden argument.
3431   case Memory:
3432     return getIndirectReturnResult(RetTy);
3433 
3434     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3435     // available register of the sequence %rax, %rdx is used.
3436   case Integer:
3437     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3438 
3439     // If we have a sign or zero extended integer, make sure to return Extend
3440     // so that the parameter gets the right LLVM IR attributes.
3441     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3442       // Treat an enum type as its underlying type.
3443       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3444         RetTy = EnumTy->getDecl()->getIntegerType();
3445 
3446       if (RetTy->isIntegralOrEnumerationType() &&
3447           isPromotableIntegerTypeForABI(RetTy))
3448         return ABIArgInfo::getExtend(RetTy);
3449     }
3450     break;
3451 
3452     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3453     // available SSE register of the sequence %xmm0, %xmm1 is used.
3454   case SSE:
3455     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3456     break;
3457 
3458     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3459     // returned on the X87 stack in %st0 as 80-bit x87 number.
3460   case X87:
3461     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3462     break;
3463 
3464     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3465     // part of the value is returned in %st0 and the imaginary part in
3466     // %st1.
3467   case ComplexX87:
3468     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3469     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3470                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3471     break;
3472   }
3473 
3474   llvm::Type *HighPart = nullptr;
3475   switch (Hi) {
3476     // Memory was handled previously and X87 should
3477     // never occur as a hi class.
3478   case Memory:
3479   case X87:
3480     llvm_unreachable("Invalid classification for hi word.");
3481 
3482   case ComplexX87: // Previously handled.
3483   case NoClass:
3484     break;
3485 
3486   case Integer:
3487     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3488     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3489       return ABIArgInfo::getDirect(HighPart, 8);
3490     break;
3491   case SSE:
3492     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3493     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3494       return ABIArgInfo::getDirect(HighPart, 8);
3495     break;
3496 
3497     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3498     // is passed in the next available eightbyte chunk if the last used
3499     // vector register.
3500     //
3501     // SSEUP should always be preceded by SSE, just widen.
3502   case SSEUp:
3503     assert(Lo == SSE && "Unexpected SSEUp classification.");
3504     ResType = GetByteVectorType(RetTy);
3505     break;
3506 
3507     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3508     // returned together with the previous X87 value in %st0.
3509   case X87Up:
3510     // If X87Up is preceded by X87, we don't need to do
3511     // anything. However, in some cases with unions it may not be
3512     // preceded by X87. In such situations we follow gcc and pass the
3513     // extra bits in an SSE reg.
3514     if (Lo != X87) {
3515       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3516       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3517         return ABIArgInfo::getDirect(HighPart, 8);
3518     }
3519     break;
3520   }
3521 
3522   // If a high part was specified, merge it together with the low part.  It is
3523   // known to pass in the high eightbyte of the result.  We do this by forming a
3524   // first class struct aggregate with the high and low part: {low, high}
3525   if (HighPart)
3526     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3527 
3528   return ABIArgInfo::getDirect(ResType);
3529 }
3530 
3531 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3532   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3533   bool isNamedArg)
3534   const
3535 {
3536   Ty = useFirstFieldIfTransparentUnion(Ty);
3537 
3538   X86_64ABIInfo::Class Lo, Hi;
3539   classify(Ty, 0, Lo, Hi, isNamedArg);
3540 
3541   // Check some invariants.
3542   // FIXME: Enforce these by construction.
3543   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3544   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3545 
3546   neededInt = 0;
3547   neededSSE = 0;
3548   llvm::Type *ResType = nullptr;
3549   switch (Lo) {
3550   case NoClass:
3551     if (Hi == NoClass)
3552       return ABIArgInfo::getIgnore();
3553     // If the low part is just padding, it takes no register, leave ResType
3554     // null.
3555     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3556            "Unknown missing lo part");
3557     break;
3558 
3559     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3560     // on the stack.
3561   case Memory:
3562 
3563     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3564     // COMPLEX_X87, it is passed in memory.
3565   case X87:
3566   case ComplexX87:
3567     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3568       ++neededInt;
3569     return getIndirectResult(Ty, freeIntRegs);
3570 
3571   case SSEUp:
3572   case X87Up:
3573     llvm_unreachable("Invalid classification for lo word.");
3574 
3575     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3576     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3577     // and %r9 is used.
3578   case Integer:
3579     ++neededInt;
3580 
3581     // Pick an 8-byte type based on the preferred type.
3582     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3583 
3584     // If we have a sign or zero extended integer, make sure to return Extend
3585     // so that the parameter gets the right LLVM IR attributes.
3586     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3587       // Treat an enum type as its underlying type.
3588       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3589         Ty = EnumTy->getDecl()->getIntegerType();
3590 
3591       if (Ty->isIntegralOrEnumerationType() &&
3592           isPromotableIntegerTypeForABI(Ty))
3593         return ABIArgInfo::getExtend(Ty);
3594     }
3595 
3596     break;
3597 
3598     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3599     // available SSE register is used, the registers are taken in the
3600     // order from %xmm0 to %xmm7.
3601   case SSE: {
3602     llvm::Type *IRType = CGT.ConvertType(Ty);
3603     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3604     ++neededSSE;
3605     break;
3606   }
3607   }
3608 
3609   llvm::Type *HighPart = nullptr;
3610   switch (Hi) {
3611     // Memory was handled previously, ComplexX87 and X87 should
3612     // never occur as hi classes, and X87Up must be preceded by X87,
3613     // which is passed in memory.
3614   case Memory:
3615   case X87:
3616   case ComplexX87:
3617     llvm_unreachable("Invalid classification for hi word.");
3618 
3619   case NoClass: break;
3620 
3621   case Integer:
3622     ++neededInt;
3623     // Pick an 8-byte type based on the preferred type.
3624     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3625 
3626     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3627       return ABIArgInfo::getDirect(HighPart, 8);
3628     break;
3629 
3630     // X87Up generally doesn't occur here (long double is passed in
3631     // memory), except in situations involving unions.
3632   case X87Up:
3633   case SSE:
3634     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3635 
3636     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3637       return ABIArgInfo::getDirect(HighPart, 8);
3638 
3639     ++neededSSE;
3640     break;
3641 
3642     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3643     // eightbyte is passed in the upper half of the last used SSE
3644     // register.  This only happens when 128-bit vectors are passed.
3645   case SSEUp:
3646     assert(Lo == SSE && "Unexpected SSEUp classification");
3647     ResType = GetByteVectorType(Ty);
3648     break;
3649   }
3650 
3651   // If a high part was specified, merge it together with the low part.  It is
3652   // known to pass in the high eightbyte of the result.  We do this by forming a
3653   // first class struct aggregate with the high and low part: {low, high}
3654   if (HighPart)
3655     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3656 
3657   return ABIArgInfo::getDirect(ResType);
3658 }
3659 
3660 ABIArgInfo
3661 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3662                                              unsigned &NeededSSE) const {
3663   auto RT = Ty->getAs<RecordType>();
3664   assert(RT && "classifyRegCallStructType only valid with struct types");
3665 
3666   if (RT->getDecl()->hasFlexibleArrayMember())
3667     return getIndirectReturnResult(Ty);
3668 
3669   // Sum up bases
3670   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3671     if (CXXRD->isDynamicClass()) {
3672       NeededInt = NeededSSE = 0;
3673       return getIndirectReturnResult(Ty);
3674     }
3675 
3676     for (const auto &I : CXXRD->bases())
3677       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3678               .isIndirect()) {
3679         NeededInt = NeededSSE = 0;
3680         return getIndirectReturnResult(Ty);
3681       }
3682   }
3683 
3684   // Sum up members
3685   for (const auto *FD : RT->getDecl()->fields()) {
3686     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3687       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3688               .isIndirect()) {
3689         NeededInt = NeededSSE = 0;
3690         return getIndirectReturnResult(Ty);
3691       }
3692     } else {
3693       unsigned LocalNeededInt, LocalNeededSSE;
3694       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3695                                LocalNeededSSE, true)
3696               .isIndirect()) {
3697         NeededInt = NeededSSE = 0;
3698         return getIndirectReturnResult(Ty);
3699       }
3700       NeededInt += LocalNeededInt;
3701       NeededSSE += LocalNeededSSE;
3702     }
3703   }
3704 
3705   return ABIArgInfo::getDirect();
3706 }
3707 
3708 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3709                                                     unsigned &NeededInt,
3710                                                     unsigned &NeededSSE) const {
3711 
3712   NeededInt = 0;
3713   NeededSSE = 0;
3714 
3715   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3716 }
3717 
3718 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3719 
3720   const unsigned CallingConv = FI.getCallingConvention();
3721   // It is possible to force Win64 calling convention on any x86_64 target by
3722   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3723   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3724   if (CallingConv == llvm::CallingConv::Win64) {
3725     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3726     Win64ABIInfo.computeInfo(FI);
3727     return;
3728   }
3729 
3730   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3731 
3732   // Keep track of the number of assigned registers.
3733   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3734   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3735   unsigned NeededInt, NeededSSE;
3736 
3737   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3738     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3739         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3740       FI.getReturnInfo() =
3741           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3742       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3743         FreeIntRegs -= NeededInt;
3744         FreeSSERegs -= NeededSSE;
3745       } else {
3746         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3747       }
3748     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3749       // Complex Long Double Type is passed in Memory when Regcall
3750       // calling convention is used.
3751       const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3752       if (getContext().getCanonicalType(CT->getElementType()) ==
3753           getContext().LongDoubleTy)
3754         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3755     } else
3756       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3757   }
3758 
3759   // If the return value is indirect, then the hidden argument is consuming one
3760   // integer register.
3761   if (FI.getReturnInfo().isIndirect())
3762     --FreeIntRegs;
3763 
3764   // The chain argument effectively gives us another free register.
3765   if (FI.isChainCall())
3766     ++FreeIntRegs;
3767 
3768   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3769   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3770   // get assigned (in left-to-right order) for passing as follows...
3771   unsigned ArgNo = 0;
3772   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3773        it != ie; ++it, ++ArgNo) {
3774     bool IsNamedArg = ArgNo < NumRequiredArgs;
3775 
3776     if (IsRegCall && it->type->isStructureOrClassType())
3777       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3778     else
3779       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3780                                       NeededSSE, IsNamedArg);
3781 
3782     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3783     // eightbyte of an argument, the whole argument is passed on the
3784     // stack. If registers have already been assigned for some
3785     // eightbytes of such an argument, the assignments get reverted.
3786     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3787       FreeIntRegs -= NeededInt;
3788       FreeSSERegs -= NeededSSE;
3789     } else {
3790       it->info = getIndirectResult(it->type, FreeIntRegs);
3791     }
3792   }
3793 }
3794 
3795 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3796                                          Address VAListAddr, QualType Ty) {
3797   Address overflow_arg_area_p =
3798       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3799   llvm::Value *overflow_arg_area =
3800     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3801 
3802   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3803   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3804   // It isn't stated explicitly in the standard, but in practice we use
3805   // alignment greater than 16 where necessary.
3806   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3807   if (Align > CharUnits::fromQuantity(8)) {
3808     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3809                                                       Align);
3810   }
3811 
3812   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3813   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3814   llvm::Value *Res =
3815     CGF.Builder.CreateBitCast(overflow_arg_area,
3816                               llvm::PointerType::getUnqual(LTy));
3817 
3818   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3819   // l->overflow_arg_area + sizeof(type).
3820   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3821   // an 8 byte boundary.
3822 
3823   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3824   llvm::Value *Offset =
3825       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3826   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3827                                             "overflow_arg_area.next");
3828   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3829 
3830   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3831   return Address(Res, Align);
3832 }
3833 
3834 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3835                                  QualType Ty) const {
3836   // Assume that va_list type is correct; should be pointer to LLVM type:
3837   // struct {
3838   //   i32 gp_offset;
3839   //   i32 fp_offset;
3840   //   i8* overflow_arg_area;
3841   //   i8* reg_save_area;
3842   // };
3843   unsigned neededInt, neededSSE;
3844 
3845   Ty = getContext().getCanonicalType(Ty);
3846   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3847                                        /*isNamedArg*/false);
3848 
3849   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3850   // in the registers. If not go to step 7.
3851   if (!neededInt && !neededSSE)
3852     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3853 
3854   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3855   // general purpose registers needed to pass type and num_fp to hold
3856   // the number of floating point registers needed.
3857 
3858   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3859   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3860   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3861   //
3862   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3863   // register save space).
3864 
3865   llvm::Value *InRegs = nullptr;
3866   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3867   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3868   if (neededInt) {
3869     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3870     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3871     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3872     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3873   }
3874 
3875   if (neededSSE) {
3876     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3877     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3878     llvm::Value *FitsInFP =
3879       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3880     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3881     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3882   }
3883 
3884   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3885   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3886   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3887   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3888 
3889   // Emit code to load the value if it was passed in registers.
3890 
3891   CGF.EmitBlock(InRegBlock);
3892 
3893   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3894   // an offset of l->gp_offset and/or l->fp_offset. This may require
3895   // copying to a temporary location in case the parameter is passed
3896   // in different register classes or requires an alignment greater
3897   // than 8 for general purpose registers and 16 for XMM registers.
3898   //
3899   // FIXME: This really results in shameful code when we end up needing to
3900   // collect arguments from different places; often what should result in a
3901   // simple assembling of a structure from scattered addresses has many more
3902   // loads than necessary. Can we clean this up?
3903   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3904   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3905       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3906 
3907   Address RegAddr = Address::invalid();
3908   if (neededInt && neededSSE) {
3909     // FIXME: Cleanup.
3910     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3911     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3912     Address Tmp = CGF.CreateMemTemp(Ty);
3913     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3914     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3915     llvm::Type *TyLo = ST->getElementType(0);
3916     llvm::Type *TyHi = ST->getElementType(1);
3917     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3918            "Unexpected ABI info for mixed regs");
3919     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3920     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3921     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3922     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3923     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3924     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3925 
3926     // Copy the first element.
3927     // FIXME: Our choice of alignment here and below is probably pessimistic.
3928     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3929         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3930         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3931     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3932 
3933     // Copy the second element.
3934     V = CGF.Builder.CreateAlignedLoad(
3935         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3936         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3937     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3938 
3939     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3940   } else if (neededInt) {
3941     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3942                       CharUnits::fromQuantity(8));
3943     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3944 
3945     // Copy to a temporary if necessary to ensure the appropriate alignment.
3946     std::pair<CharUnits, CharUnits> SizeAlign =
3947         getContext().getTypeInfoInChars(Ty);
3948     uint64_t TySize = SizeAlign.first.getQuantity();
3949     CharUnits TyAlign = SizeAlign.second;
3950 
3951     // Copy into a temporary if the type is more aligned than the
3952     // register save area.
3953     if (TyAlign.getQuantity() > 8) {
3954       Address Tmp = CGF.CreateMemTemp(Ty);
3955       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3956       RegAddr = Tmp;
3957     }
3958 
3959   } else if (neededSSE == 1) {
3960     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3961                       CharUnits::fromQuantity(16));
3962     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3963   } else {
3964     assert(neededSSE == 2 && "Invalid number of needed registers!");
3965     // SSE registers are spaced 16 bytes apart in the register save
3966     // area, we need to collect the two eightbytes together.
3967     // The ABI isn't explicit about this, but it seems reasonable
3968     // to assume that the slots are 16-byte aligned, since the stack is
3969     // naturally 16-byte aligned and the prologue is expected to store
3970     // all the SSE registers to the RSA.
3971     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3972                                 CharUnits::fromQuantity(16));
3973     Address RegAddrHi =
3974       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3975                                              CharUnits::fromQuantity(16));
3976     llvm::Type *ST = AI.canHaveCoerceToType()
3977                          ? AI.getCoerceToType()
3978                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3979     llvm::Value *V;
3980     Address Tmp = CGF.CreateMemTemp(Ty);
3981     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3982     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3983         RegAddrLo, ST->getStructElementType(0)));
3984     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3985     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3986         RegAddrHi, ST->getStructElementType(1)));
3987     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3988 
3989     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3990   }
3991 
3992   // AMD64-ABI 3.5.7p5: Step 5. Set:
3993   // l->gp_offset = l->gp_offset + num_gp * 8
3994   // l->fp_offset = l->fp_offset + num_fp * 16.
3995   if (neededInt) {
3996     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3997     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3998                             gp_offset_p);
3999   }
4000   if (neededSSE) {
4001     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4002     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4003                             fp_offset_p);
4004   }
4005   CGF.EmitBranch(ContBlock);
4006 
4007   // Emit code to load the value if it was passed in memory.
4008 
4009   CGF.EmitBlock(InMemBlock);
4010   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4011 
4012   // Return the appropriate result.
4013 
4014   CGF.EmitBlock(ContBlock);
4015   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4016                                  "vaarg.addr");
4017   return ResAddr;
4018 }
4019 
4020 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4021                                    QualType Ty) const {
4022   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4023                           CGF.getContext().getTypeInfoInChars(Ty),
4024                           CharUnits::fromQuantity(8),
4025                           /*allowHigherAlign*/ false);
4026 }
4027 
4028 ABIArgInfo
4029 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
4030                                     const ABIArgInfo &current) const {
4031   // Assumes vectorCall calling convention.
4032   const Type *Base = nullptr;
4033   uint64_t NumElts = 0;
4034 
4035   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4036       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4037     FreeSSERegs -= NumElts;
4038     return getDirectX86Hva();
4039   }
4040   return current;
4041 }
4042 
4043 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4044                                       bool IsReturnType, bool IsVectorCall,
4045                                       bool IsRegCall) const {
4046 
4047   if (Ty->isVoidType())
4048     return ABIArgInfo::getIgnore();
4049 
4050   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4051     Ty = EnumTy->getDecl()->getIntegerType();
4052 
4053   TypeInfo Info = getContext().getTypeInfo(Ty);
4054   uint64_t Width = Info.Width;
4055   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4056 
4057   const RecordType *RT = Ty->getAs<RecordType>();
4058   if (RT) {
4059     if (!IsReturnType) {
4060       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4061         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4062     }
4063 
4064     if (RT->getDecl()->hasFlexibleArrayMember())
4065       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4066 
4067   }
4068 
4069   const Type *Base = nullptr;
4070   uint64_t NumElts = 0;
4071   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4072   // other targets.
4073   if ((IsVectorCall || IsRegCall) &&
4074       isHomogeneousAggregate(Ty, Base, NumElts)) {
4075     if (IsRegCall) {
4076       if (FreeSSERegs >= NumElts) {
4077         FreeSSERegs -= NumElts;
4078         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4079           return ABIArgInfo::getDirect();
4080         return ABIArgInfo::getExpand();
4081       }
4082       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4083     } else if (IsVectorCall) {
4084       if (FreeSSERegs >= NumElts &&
4085           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4086         FreeSSERegs -= NumElts;
4087         return ABIArgInfo::getDirect();
4088       } else if (IsReturnType) {
4089         return ABIArgInfo::getExpand();
4090       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4091         // HVAs are delayed and reclassified in the 2nd step.
4092         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4093       }
4094     }
4095   }
4096 
4097   if (Ty->isMemberPointerType()) {
4098     // If the member pointer is represented by an LLVM int or ptr, pass it
4099     // directly.
4100     llvm::Type *LLTy = CGT.ConvertType(Ty);
4101     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4102       return ABIArgInfo::getDirect();
4103   }
4104 
4105   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4106     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4107     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4108     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4109       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4110 
4111     // Otherwise, coerce it to a small integer.
4112     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4113   }
4114 
4115   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4116     switch (BT->getKind()) {
4117     case BuiltinType::Bool:
4118       // Bool type is always extended to the ABI, other builtin types are not
4119       // extended.
4120       return ABIArgInfo::getExtend(Ty);
4121 
4122     case BuiltinType::LongDouble:
4123       // Mingw64 GCC uses the old 80 bit extended precision floating point
4124       // unit. It passes them indirectly through memory.
4125       if (IsMingw64) {
4126         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4127         if (LDF == &llvm::APFloat::x87DoubleExtended())
4128           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4129       }
4130       break;
4131 
4132     case BuiltinType::Int128:
4133     case BuiltinType::UInt128:
4134       // If it's a parameter type, the normal ABI rule is that arguments larger
4135       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4136       // even though it isn't particularly efficient.
4137       if (!IsReturnType)
4138         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4139 
4140       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4141       // Clang matches them for compatibility.
4142       return ABIArgInfo::getDirect(
4143           llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
4144 
4145     default:
4146       break;
4147     }
4148   }
4149 
4150   if (Ty->isExtIntType()) {
4151     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4152     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4153     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4154     // anyway as long is it fits in them, so we don't have to check the power of
4155     // 2.
4156     if (Width <= 64)
4157       return ABIArgInfo::getDirect();
4158     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4159   }
4160 
4161   return ABIArgInfo::getDirect();
4162 }
4163 
4164 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4165                                              unsigned FreeSSERegs,
4166                                              bool IsVectorCall,
4167                                              bool IsRegCall) const {
4168   unsigned Count = 0;
4169   for (auto &I : FI.arguments()) {
4170     // Vectorcall in x64 only permits the first 6 arguments to be passed
4171     // as XMM/YMM registers.
4172     if (Count < VectorcallMaxParamNumAsReg)
4173       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4174     else {
4175       // Since these cannot be passed in registers, pretend no registers
4176       // are left.
4177       unsigned ZeroSSERegsAvail = 0;
4178       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4179                         IsVectorCall, IsRegCall);
4180     }
4181     ++Count;
4182   }
4183 
4184   for (auto &I : FI.arguments()) {
4185     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4186   }
4187 }
4188 
4189 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4190   const unsigned CC = FI.getCallingConvention();
4191   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4192   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4193 
4194   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4195   // classification rules.
4196   if (CC == llvm::CallingConv::X86_64_SysV) {
4197     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4198     SysVABIInfo.computeInfo(FI);
4199     return;
4200   }
4201 
4202   unsigned FreeSSERegs = 0;
4203   if (IsVectorCall) {
4204     // We can use up to 4 SSE return registers with vectorcall.
4205     FreeSSERegs = 4;
4206   } else if (IsRegCall) {
4207     // RegCall gives us 16 SSE registers.
4208     FreeSSERegs = 16;
4209   }
4210 
4211   if (!getCXXABI().classifyReturnType(FI))
4212     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4213                                   IsVectorCall, IsRegCall);
4214 
4215   if (IsVectorCall) {
4216     // We can use up to 6 SSE register parameters with vectorcall.
4217     FreeSSERegs = 6;
4218   } else if (IsRegCall) {
4219     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4220     FreeSSERegs = 16;
4221   }
4222 
4223   if (IsVectorCall) {
4224     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4225   } else {
4226     for (auto &I : FI.arguments())
4227       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4228   }
4229 
4230 }
4231 
4232 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4233                                     QualType Ty) const {
4234 
4235   bool IsIndirect = false;
4236 
4237   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4238   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4239   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4240     uint64_t Width = getContext().getTypeSize(Ty);
4241     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4242   }
4243 
4244   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4245                           CGF.getContext().getTypeInfoInChars(Ty),
4246                           CharUnits::fromQuantity(8),
4247                           /*allowHigherAlign*/ false);
4248 }
4249 
4250 // PowerPC-32
4251 namespace {
4252 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4253 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4254   bool IsSoftFloatABI;
4255   bool IsRetSmallStructInRegABI;
4256 
4257   CharUnits getParamTypeAlignment(QualType Ty) const;
4258 
4259 public:
4260   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4261                      bool RetSmallStructInRegABI)
4262       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4263         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4264 
4265   ABIArgInfo classifyReturnType(QualType RetTy) const;
4266 
4267   void computeInfo(CGFunctionInfo &FI) const override {
4268     if (!getCXXABI().classifyReturnType(FI))
4269       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4270     for (auto &I : FI.arguments())
4271       I.info = classifyArgumentType(I.type);
4272   }
4273 
4274   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4275                     QualType Ty) const override;
4276 };
4277 
4278 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4279 public:
4280   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4281                          bool RetSmallStructInRegABI)
4282       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4283             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4284 
4285   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4286                                      const CodeGenOptions &Opts);
4287 
4288   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4289     // This is recovered from gcc output.
4290     return 1; // r1 is the dedicated stack pointer
4291   }
4292 
4293   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4294                                llvm::Value *Address) const override;
4295 };
4296 }
4297 
4298 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4299   // Complex types are passed just like their elements.
4300   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4301     Ty = CTy->getElementType();
4302 
4303   if (Ty->isVectorType())
4304     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4305                                                                        : 4);
4306 
4307   // For single-element float/vector structs, we consider the whole type
4308   // to have the same alignment requirements as its single element.
4309   const Type *AlignTy = nullptr;
4310   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4311     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4312     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4313         (BT && BT->isFloatingPoint()))
4314       AlignTy = EltType;
4315   }
4316 
4317   if (AlignTy)
4318     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4319   return CharUnits::fromQuantity(4);
4320 }
4321 
4322 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4323   uint64_t Size;
4324 
4325   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4326   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4327       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4328     // System V ABI (1995), page 3-22, specified:
4329     // > A structure or union whose size is less than or equal to 8 bytes
4330     // > shall be returned in r3 and r4, as if it were first stored in the
4331     // > 8-byte aligned memory area and then the low addressed word were
4332     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4333     // > the last member of the structure or union are not defined.
4334     //
4335     // GCC for big-endian PPC32 inserts the pad before the first member,
4336     // not "beyond the last member" of the struct.  To stay compatible
4337     // with GCC, we coerce the struct to an integer of the same size.
4338     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4339     if (Size == 0)
4340       return ABIArgInfo::getIgnore();
4341     else {
4342       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4343       return ABIArgInfo::getDirect(CoerceTy);
4344     }
4345   }
4346 
4347   return DefaultABIInfo::classifyReturnType(RetTy);
4348 }
4349 
4350 // TODO: this implementation is now likely redundant with
4351 // DefaultABIInfo::EmitVAArg.
4352 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4353                                       QualType Ty) const {
4354   if (getTarget().getTriple().isOSDarwin()) {
4355     auto TI = getContext().getTypeInfoInChars(Ty);
4356     TI.second = getParamTypeAlignment(Ty);
4357 
4358     CharUnits SlotSize = CharUnits::fromQuantity(4);
4359     return emitVoidPtrVAArg(CGF, VAList, Ty,
4360                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4361                             /*AllowHigherAlign=*/true);
4362   }
4363 
4364   const unsigned OverflowLimit = 8;
4365   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4366     // TODO: Implement this. For now ignore.
4367     (void)CTy;
4368     return Address::invalid(); // FIXME?
4369   }
4370 
4371   // struct __va_list_tag {
4372   //   unsigned char gpr;
4373   //   unsigned char fpr;
4374   //   unsigned short reserved;
4375   //   void *overflow_arg_area;
4376   //   void *reg_save_area;
4377   // };
4378 
4379   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4380   bool isInt =
4381       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4382   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4383 
4384   // All aggregates are passed indirectly?  That doesn't seem consistent
4385   // with the argument-lowering code.
4386   bool isIndirect = Ty->isAggregateType();
4387 
4388   CGBuilderTy &Builder = CGF.Builder;
4389 
4390   // The calling convention either uses 1-2 GPRs or 1 FPR.
4391   Address NumRegsAddr = Address::invalid();
4392   if (isInt || IsSoftFloatABI) {
4393     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4394   } else {
4395     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4396   }
4397 
4398   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4399 
4400   // "Align" the register count when TY is i64.
4401   if (isI64 || (isF64 && IsSoftFloatABI)) {
4402     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4403     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4404   }
4405 
4406   llvm::Value *CC =
4407       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4408 
4409   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4410   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4411   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4412 
4413   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4414 
4415   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4416   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4417 
4418   // Case 1: consume registers.
4419   Address RegAddr = Address::invalid();
4420   {
4421     CGF.EmitBlock(UsingRegs);
4422 
4423     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4424     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4425                       CharUnits::fromQuantity(8));
4426     assert(RegAddr.getElementType() == CGF.Int8Ty);
4427 
4428     // Floating-point registers start after the general-purpose registers.
4429     if (!(isInt || IsSoftFloatABI)) {
4430       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4431                                                    CharUnits::fromQuantity(32));
4432     }
4433 
4434     // Get the address of the saved value by scaling the number of
4435     // registers we've used by the number of
4436     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4437     llvm::Value *RegOffset =
4438       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4439     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4440                                             RegAddr.getPointer(), RegOffset),
4441                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4442     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4443 
4444     // Increase the used-register count.
4445     NumRegs =
4446       Builder.CreateAdd(NumRegs,
4447                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4448     Builder.CreateStore(NumRegs, NumRegsAddr);
4449 
4450     CGF.EmitBranch(Cont);
4451   }
4452 
4453   // Case 2: consume space in the overflow area.
4454   Address MemAddr = Address::invalid();
4455   {
4456     CGF.EmitBlock(UsingOverflow);
4457 
4458     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4459 
4460     // Everything in the overflow area is rounded up to a size of at least 4.
4461     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4462 
4463     CharUnits Size;
4464     if (!isIndirect) {
4465       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4466       Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4467     } else {
4468       Size = CGF.getPointerSize();
4469     }
4470 
4471     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4472     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4473                          OverflowAreaAlign);
4474     // Round up address of argument to alignment
4475     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4476     if (Align > OverflowAreaAlign) {
4477       llvm::Value *Ptr = OverflowArea.getPointer();
4478       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4479                                                            Align);
4480     }
4481 
4482     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4483 
4484     // Increase the overflow area.
4485     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4486     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4487     CGF.EmitBranch(Cont);
4488   }
4489 
4490   CGF.EmitBlock(Cont);
4491 
4492   // Merge the cases with a phi.
4493   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4494                                 "vaarg.addr");
4495 
4496   // Load the pointer if the argument was passed indirectly.
4497   if (isIndirect) {
4498     Result = Address(Builder.CreateLoad(Result, "aggr"),
4499                      getContext().getTypeAlignInChars(Ty));
4500   }
4501 
4502   return Result;
4503 }
4504 
4505 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4506     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4507   assert(Triple.getArch() == llvm::Triple::ppc);
4508 
4509   switch (Opts.getStructReturnConvention()) {
4510   case CodeGenOptions::SRCK_Default:
4511     break;
4512   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4513     return false;
4514   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4515     return true;
4516   }
4517 
4518   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4519     return true;
4520 
4521   return false;
4522 }
4523 
4524 bool
4525 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4526                                                 llvm::Value *Address) const {
4527   // This is calculated from the LLVM and GCC tables and verified
4528   // against gcc output.  AFAIK all ABIs use the same encoding.
4529 
4530   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4531 
4532   llvm::IntegerType *i8 = CGF.Int8Ty;
4533   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4534   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4535   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4536 
4537   // 0-31: r0-31, the 4-byte general-purpose registers
4538   AssignToArrayRange(Builder, Address, Four8, 0, 31);
4539 
4540   // 32-63: fp0-31, the 8-byte floating-point registers
4541   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4542 
4543   // 64-76 are various 4-byte special-purpose registers:
4544   // 64: mq
4545   // 65: lr
4546   // 66: ctr
4547   // 67: ap
4548   // 68-75 cr0-7
4549   // 76: xer
4550   AssignToArrayRange(Builder, Address, Four8, 64, 76);
4551 
4552   // 77-108: v0-31, the 16-byte vector registers
4553   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4554 
4555   // 109: vrsave
4556   // 110: vscr
4557   // 111: spe_acc
4558   // 112: spefscr
4559   // 113: sfp
4560   AssignToArrayRange(Builder, Address, Four8, 109, 113);
4561 
4562   return false;
4563 }
4564 
4565 // PowerPC-64
4566 
4567 namespace {
4568 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4569 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4570 public:
4571   enum ABIKind {
4572     ELFv1 = 0,
4573     ELFv2
4574   };
4575 
4576 private:
4577   static const unsigned GPRBits = 64;
4578   ABIKind Kind;
4579   bool HasQPX;
4580   bool IsSoftFloatABI;
4581 
4582   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4583   // will be passed in a QPX register.
4584   bool IsQPXVectorTy(const Type *Ty) const {
4585     if (!HasQPX)
4586       return false;
4587 
4588     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4589       unsigned NumElements = VT->getNumElements();
4590       if (NumElements == 1)
4591         return false;
4592 
4593       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4594         if (getContext().getTypeSize(Ty) <= 256)
4595           return true;
4596       } else if (VT->getElementType()->
4597                    isSpecificBuiltinType(BuiltinType::Float)) {
4598         if (getContext().getTypeSize(Ty) <= 128)
4599           return true;
4600       }
4601     }
4602 
4603     return false;
4604   }
4605 
4606   bool IsQPXVectorTy(QualType Ty) const {
4607     return IsQPXVectorTy(Ty.getTypePtr());
4608   }
4609 
4610 public:
4611   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4612                      bool SoftFloatABI)
4613       : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4614         IsSoftFloatABI(SoftFloatABI) {}
4615 
4616   bool isPromotableTypeForABI(QualType Ty) const;
4617   CharUnits getParamTypeAlignment(QualType Ty) const;
4618 
4619   ABIArgInfo classifyReturnType(QualType RetTy) const;
4620   ABIArgInfo classifyArgumentType(QualType Ty) const;
4621 
4622   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4623   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4624                                          uint64_t Members) const override;
4625 
4626   // TODO: We can add more logic to computeInfo to improve performance.
4627   // Example: For aggregate arguments that fit in a register, we could
4628   // use getDirectInReg (as is done below for structs containing a single
4629   // floating-point value) to avoid pushing them to memory on function
4630   // entry.  This would require changing the logic in PPCISelLowering
4631   // when lowering the parameters in the caller and args in the callee.
4632   void computeInfo(CGFunctionInfo &FI) const override {
4633     if (!getCXXABI().classifyReturnType(FI))
4634       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4635     for (auto &I : FI.arguments()) {
4636       // We rely on the default argument classification for the most part.
4637       // One exception:  An aggregate containing a single floating-point
4638       // or vector item must be passed in a register if one is available.
4639       const Type *T = isSingleElementStruct(I.type, getContext());
4640       if (T) {
4641         const BuiltinType *BT = T->getAs<BuiltinType>();
4642         if (IsQPXVectorTy(T) ||
4643             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4644             (BT && BT->isFloatingPoint())) {
4645           QualType QT(T, 0);
4646           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4647           continue;
4648         }
4649       }
4650       I.info = classifyArgumentType(I.type);
4651     }
4652   }
4653 
4654   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4655                     QualType Ty) const override;
4656 
4657   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4658                                     bool asReturnValue) const override {
4659     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4660   }
4661 
4662   bool isSwiftErrorInRegister() const override {
4663     return false;
4664   }
4665 };
4666 
4667 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4668 
4669 public:
4670   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4671                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4672                                bool SoftFloatABI)
4673       : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>(
4674             CGT, Kind, HasQPX, SoftFloatABI)) {}
4675 
4676   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4677     // This is recovered from gcc output.
4678     return 1; // r1 is the dedicated stack pointer
4679   }
4680 
4681   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4682                                llvm::Value *Address) const override;
4683 };
4684 
4685 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4686 public:
4687   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4688 
4689   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4690     // This is recovered from gcc output.
4691     return 1; // r1 is the dedicated stack pointer
4692   }
4693 
4694   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4695                                llvm::Value *Address) const override;
4696 };
4697 
4698 }
4699 
4700 // Return true if the ABI requires Ty to be passed sign- or zero-
4701 // extended to 64 bits.
4702 bool
4703 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4704   // Treat an enum type as its underlying type.
4705   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4706     Ty = EnumTy->getDecl()->getIntegerType();
4707 
4708   // Promotable integer types are required to be promoted by the ABI.
4709   if (isPromotableIntegerTypeForABI(Ty))
4710     return true;
4711 
4712   // In addition to the usual promotable integer types, we also need to
4713   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4714   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4715     switch (BT->getKind()) {
4716     case BuiltinType::Int:
4717     case BuiltinType::UInt:
4718       return true;
4719     default:
4720       break;
4721     }
4722 
4723   if (const auto *EIT = Ty->getAs<ExtIntType>())
4724     if (EIT->getNumBits() < 64)
4725       return true;
4726 
4727   return false;
4728 }
4729 
4730 /// isAlignedParamType - Determine whether a type requires 16-byte or
4731 /// higher alignment in the parameter area.  Always returns at least 8.
4732 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4733   // Complex types are passed just like their elements.
4734   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4735     Ty = CTy->getElementType();
4736 
4737   // Only vector types of size 16 bytes need alignment (larger types are
4738   // passed via reference, smaller types are not aligned).
4739   if (IsQPXVectorTy(Ty)) {
4740     if (getContext().getTypeSize(Ty) > 128)
4741       return CharUnits::fromQuantity(32);
4742 
4743     return CharUnits::fromQuantity(16);
4744   } else if (Ty->isVectorType()) {
4745     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4746   }
4747 
4748   // For single-element float/vector structs, we consider the whole type
4749   // to have the same alignment requirements as its single element.
4750   const Type *AlignAsType = nullptr;
4751   const Type *EltType = isSingleElementStruct(Ty, getContext());
4752   if (EltType) {
4753     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4754     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4755          getContext().getTypeSize(EltType) == 128) ||
4756         (BT && BT->isFloatingPoint()))
4757       AlignAsType = EltType;
4758   }
4759 
4760   // Likewise for ELFv2 homogeneous aggregates.
4761   const Type *Base = nullptr;
4762   uint64_t Members = 0;
4763   if (!AlignAsType && Kind == ELFv2 &&
4764       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4765     AlignAsType = Base;
4766 
4767   // With special case aggregates, only vector base types need alignment.
4768   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4769     if (getContext().getTypeSize(AlignAsType) > 128)
4770       return CharUnits::fromQuantity(32);
4771 
4772     return CharUnits::fromQuantity(16);
4773   } else if (AlignAsType) {
4774     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4775   }
4776 
4777   // Otherwise, we only need alignment for any aggregate type that
4778   // has an alignment requirement of >= 16 bytes.
4779   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4780     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4781       return CharUnits::fromQuantity(32);
4782     return CharUnits::fromQuantity(16);
4783   }
4784 
4785   return CharUnits::fromQuantity(8);
4786 }
4787 
4788 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4789 /// aggregate.  Base is set to the base element type, and Members is set
4790 /// to the number of base elements.
4791 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4792                                      uint64_t &Members) const {
4793   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4794     uint64_t NElements = AT->getSize().getZExtValue();
4795     if (NElements == 0)
4796       return false;
4797     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4798       return false;
4799     Members *= NElements;
4800   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4801     const RecordDecl *RD = RT->getDecl();
4802     if (RD->hasFlexibleArrayMember())
4803       return false;
4804 
4805     Members = 0;
4806 
4807     // If this is a C++ record, check the bases first.
4808     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4809       for (const auto &I : CXXRD->bases()) {
4810         // Ignore empty records.
4811         if (isEmptyRecord(getContext(), I.getType(), true))
4812           continue;
4813 
4814         uint64_t FldMembers;
4815         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4816           return false;
4817 
4818         Members += FldMembers;
4819       }
4820     }
4821 
4822     for (const auto *FD : RD->fields()) {
4823       // Ignore (non-zero arrays of) empty records.
4824       QualType FT = FD->getType();
4825       while (const ConstantArrayType *AT =
4826              getContext().getAsConstantArrayType(FT)) {
4827         if (AT->getSize().getZExtValue() == 0)
4828           return false;
4829         FT = AT->getElementType();
4830       }
4831       if (isEmptyRecord(getContext(), FT, true))
4832         continue;
4833 
4834       // For compatibility with GCC, ignore empty bitfields in C++ mode.
4835       if (getContext().getLangOpts().CPlusPlus &&
4836           FD->isZeroLengthBitField(getContext()))
4837         continue;
4838 
4839       uint64_t FldMembers;
4840       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4841         return false;
4842 
4843       Members = (RD->isUnion() ?
4844                  std::max(Members, FldMembers) : Members + FldMembers);
4845     }
4846 
4847     if (!Base)
4848       return false;
4849 
4850     // Ensure there is no padding.
4851     if (getContext().getTypeSize(Base) * Members !=
4852         getContext().getTypeSize(Ty))
4853       return false;
4854   } else {
4855     Members = 1;
4856     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4857       Members = 2;
4858       Ty = CT->getElementType();
4859     }
4860 
4861     // Most ABIs only support float, double, and some vector type widths.
4862     if (!isHomogeneousAggregateBaseType(Ty))
4863       return false;
4864 
4865     // The base type must be the same for all members.  Types that
4866     // agree in both total size and mode (float vs. vector) are
4867     // treated as being equivalent here.
4868     const Type *TyPtr = Ty.getTypePtr();
4869     if (!Base) {
4870       Base = TyPtr;
4871       // If it's a non-power-of-2 vector, its size is already a power-of-2,
4872       // so make sure to widen it explicitly.
4873       if (const VectorType *VT = Base->getAs<VectorType>()) {
4874         QualType EltTy = VT->getElementType();
4875         unsigned NumElements =
4876             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4877         Base = getContext()
4878                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
4879                    .getTypePtr();
4880       }
4881     }
4882 
4883     if (Base->isVectorType() != TyPtr->isVectorType() ||
4884         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4885       return false;
4886   }
4887   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4888 }
4889 
4890 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4891   // Homogeneous aggregates for ELFv2 must have base types of float,
4892   // double, long double, or 128-bit vectors.
4893   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4894     if (BT->getKind() == BuiltinType::Float ||
4895         BT->getKind() == BuiltinType::Double ||
4896         BT->getKind() == BuiltinType::LongDouble ||
4897         (getContext().getTargetInfo().hasFloat128Type() &&
4898           (BT->getKind() == BuiltinType::Float128))) {
4899       if (IsSoftFloatABI)
4900         return false;
4901       return true;
4902     }
4903   }
4904   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4905     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4906       return true;
4907   }
4908   return false;
4909 }
4910 
4911 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4912     const Type *Base, uint64_t Members) const {
4913   // Vector and fp128 types require one register, other floating point types
4914   // require one or two registers depending on their size.
4915   uint32_t NumRegs =
4916       ((getContext().getTargetInfo().hasFloat128Type() &&
4917           Base->isFloat128Type()) ||
4918         Base->isVectorType()) ? 1
4919                               : (getContext().getTypeSize(Base) + 63) / 64;
4920 
4921   // Homogeneous Aggregates may occupy at most 8 registers.
4922   return Members * NumRegs <= 8;
4923 }
4924 
4925 ABIArgInfo
4926 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4927   Ty = useFirstFieldIfTransparentUnion(Ty);
4928 
4929   if (Ty->isAnyComplexType())
4930     return ABIArgInfo::getDirect();
4931 
4932   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4933   // or via reference (larger than 16 bytes).
4934   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4935     uint64_t Size = getContext().getTypeSize(Ty);
4936     if (Size > 128)
4937       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4938     else if (Size < 128) {
4939       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4940       return ABIArgInfo::getDirect(CoerceTy);
4941     }
4942   }
4943 
4944   if (const auto *EIT = Ty->getAs<ExtIntType>())
4945     if (EIT->getNumBits() > 128)
4946       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
4947 
4948   if (isAggregateTypeForABI(Ty)) {
4949     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4950       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4951 
4952     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4953     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4954 
4955     // ELFv2 homogeneous aggregates are passed as array types.
4956     const Type *Base = nullptr;
4957     uint64_t Members = 0;
4958     if (Kind == ELFv2 &&
4959         isHomogeneousAggregate(Ty, Base, Members)) {
4960       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4961       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4962       return ABIArgInfo::getDirect(CoerceTy);
4963     }
4964 
4965     // If an aggregate may end up fully in registers, we do not
4966     // use the ByVal method, but pass the aggregate as array.
4967     // This is usually beneficial since we avoid forcing the
4968     // back-end to store the argument to memory.
4969     uint64_t Bits = getContext().getTypeSize(Ty);
4970     if (Bits > 0 && Bits <= 8 * GPRBits) {
4971       llvm::Type *CoerceTy;
4972 
4973       // Types up to 8 bytes are passed as integer type (which will be
4974       // properly aligned in the argument save area doubleword).
4975       if (Bits <= GPRBits)
4976         CoerceTy =
4977             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4978       // Larger types are passed as arrays, with the base type selected
4979       // according to the required alignment in the save area.
4980       else {
4981         uint64_t RegBits = ABIAlign * 8;
4982         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4983         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4984         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4985       }
4986 
4987       return ABIArgInfo::getDirect(CoerceTy);
4988     }
4989 
4990     // All other aggregates are passed ByVal.
4991     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4992                                    /*ByVal=*/true,
4993                                    /*Realign=*/TyAlign > ABIAlign);
4994   }
4995 
4996   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4997                                      : ABIArgInfo::getDirect());
4998 }
4999 
5000 ABIArgInfo
5001 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5002   if (RetTy->isVoidType())
5003     return ABIArgInfo::getIgnore();
5004 
5005   if (RetTy->isAnyComplexType())
5006     return ABIArgInfo::getDirect();
5007 
5008   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5009   // or via reference (larger than 16 bytes).
5010   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
5011     uint64_t Size = getContext().getTypeSize(RetTy);
5012     if (Size > 128)
5013       return getNaturalAlignIndirect(RetTy);
5014     else if (Size < 128) {
5015       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5016       return ABIArgInfo::getDirect(CoerceTy);
5017     }
5018   }
5019 
5020   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5021     if (EIT->getNumBits() > 128)
5022       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5023 
5024   if (isAggregateTypeForABI(RetTy)) {
5025     // ELFv2 homogeneous aggregates are returned as array types.
5026     const Type *Base = nullptr;
5027     uint64_t Members = 0;
5028     if (Kind == ELFv2 &&
5029         isHomogeneousAggregate(RetTy, Base, Members)) {
5030       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5031       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5032       return ABIArgInfo::getDirect(CoerceTy);
5033     }
5034 
5035     // ELFv2 small aggregates are returned in up to two registers.
5036     uint64_t Bits = getContext().getTypeSize(RetTy);
5037     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5038       if (Bits == 0)
5039         return ABIArgInfo::getIgnore();
5040 
5041       llvm::Type *CoerceTy;
5042       if (Bits > GPRBits) {
5043         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5044         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5045       } else
5046         CoerceTy =
5047             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5048       return ABIArgInfo::getDirect(CoerceTy);
5049     }
5050 
5051     // All other aggregates are returned indirectly.
5052     return getNaturalAlignIndirect(RetTy);
5053   }
5054 
5055   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5056                                         : ABIArgInfo::getDirect());
5057 }
5058 
5059 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5060 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5061                                       QualType Ty) const {
5062   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5063   TypeInfo.second = getParamTypeAlignment(Ty);
5064 
5065   CharUnits SlotSize = CharUnits::fromQuantity(8);
5066 
5067   // If we have a complex type and the base type is smaller than 8 bytes,
5068   // the ABI calls for the real and imaginary parts to be right-adjusted
5069   // in separate doublewords.  However, Clang expects us to produce a
5070   // pointer to a structure with the two parts packed tightly.  So generate
5071   // loads of the real and imaginary parts relative to the va_list pointer,
5072   // and store them to a temporary structure.
5073   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5074     CharUnits EltSize = TypeInfo.first / 2;
5075     if (EltSize < SlotSize) {
5076       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5077                                             SlotSize * 2, SlotSize,
5078                                             SlotSize, /*AllowHigher*/ true);
5079 
5080       Address RealAddr = Addr;
5081       Address ImagAddr = RealAddr;
5082       if (CGF.CGM.getDataLayout().isBigEndian()) {
5083         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5084                                                           SlotSize - EltSize);
5085         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5086                                                       2 * SlotSize - EltSize);
5087       } else {
5088         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5089       }
5090 
5091       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5092       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5093       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5094       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5095       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5096 
5097       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5098       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5099                              /*init*/ true);
5100       return Temp;
5101     }
5102   }
5103 
5104   // Otherwise, just use the general rule.
5105   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5106                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5107 }
5108 
5109 static bool
5110 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5111                               llvm::Value *Address) {
5112   // This is calculated from the LLVM and GCC tables and verified
5113   // against gcc output.  AFAIK all ABIs use the same encoding.
5114 
5115   CodeGen::CGBuilderTy &Builder = CGF.Builder;
5116 
5117   llvm::IntegerType *i8 = CGF.Int8Ty;
5118   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
5119   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
5120   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
5121 
5122   // 0-31: r0-31, the 8-byte general-purpose registers
5123   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
5124 
5125   // 32-63: fp0-31, the 8-byte floating-point registers
5126   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
5127 
5128   // 64-67 are various 8-byte special-purpose registers:
5129   // 64: mq
5130   // 65: lr
5131   // 66: ctr
5132   // 67: ap
5133   AssignToArrayRange(Builder, Address, Eight8, 64, 67);
5134 
5135   // 68-76 are various 4-byte special-purpose registers:
5136   // 68-75 cr0-7
5137   // 76: xer
5138   AssignToArrayRange(Builder, Address, Four8, 68, 76);
5139 
5140   // 77-108: v0-31, the 16-byte vector registers
5141   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
5142 
5143   // 109: vrsave
5144   // 110: vscr
5145   // 111: spe_acc
5146   // 112: spefscr
5147   // 113: sfp
5148   // 114: tfhar
5149   // 115: tfiar
5150   // 116: texasr
5151   AssignToArrayRange(Builder, Address, Eight8, 109, 116);
5152 
5153   return false;
5154 }
5155 
5156 bool
5157 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5158   CodeGen::CodeGenFunction &CGF,
5159   llvm::Value *Address) const {
5160 
5161   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5162 }
5163 
5164 bool
5165 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5166                                                 llvm::Value *Address) const {
5167 
5168   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5169 }
5170 
5171 //===----------------------------------------------------------------------===//
5172 // AArch64 ABI Implementation
5173 //===----------------------------------------------------------------------===//
5174 
5175 namespace {
5176 
5177 class AArch64ABIInfo : public SwiftABIInfo {
5178 public:
5179   enum ABIKind {
5180     AAPCS = 0,
5181     DarwinPCS,
5182     Win64
5183   };
5184 
5185 private:
5186   ABIKind Kind;
5187 
5188 public:
5189   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5190     : SwiftABIInfo(CGT), Kind(Kind) {}
5191 
5192 private:
5193   ABIKind getABIKind() const { return Kind; }
5194   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5195 
5196   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5197   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5198   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5199   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5200                                          uint64_t Members) const override;
5201 
5202   bool isIllegalVectorType(QualType Ty) const;
5203 
5204   void computeInfo(CGFunctionInfo &FI) const override {
5205     if (!::classifyReturnType(getCXXABI(), FI, *this))
5206       FI.getReturnInfo() =
5207           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5208 
5209     for (auto &it : FI.arguments())
5210       it.info = classifyArgumentType(it.type);
5211   }
5212 
5213   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5214                           CodeGenFunction &CGF) const;
5215 
5216   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5217                          CodeGenFunction &CGF) const;
5218 
5219   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5220                     QualType Ty) const override {
5221     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5222                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5223                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5224   }
5225 
5226   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5227                       QualType Ty) const override;
5228 
5229   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5230                                     bool asReturnValue) const override {
5231     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5232   }
5233   bool isSwiftErrorInRegister() const override {
5234     return true;
5235   }
5236 
5237   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5238                                  unsigned elts) const override;
5239 };
5240 
5241 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5242 public:
5243   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5244       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5245 
5246   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5247     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5248   }
5249 
5250   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5251     return 31;
5252   }
5253 
5254   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5255 
5256   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5257                            CodeGen::CodeGenModule &CGM) const override {
5258     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5259     if (!FD)
5260       return;
5261 
5262     LangOptions::SignReturnAddressScopeKind Scope =
5263         CGM.getLangOpts().getSignReturnAddressScope();
5264     LangOptions::SignReturnAddressKeyKind Key =
5265         CGM.getLangOpts().getSignReturnAddressKey();
5266     bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement;
5267     if (const auto *TA = FD->getAttr<TargetAttr>()) {
5268       ParsedTargetAttr Attr = TA->parse();
5269       if (!Attr.BranchProtection.empty()) {
5270         TargetInfo::BranchProtectionInfo BPI;
5271         StringRef Error;
5272         (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5273                                                        BPI, Error);
5274         assert(Error.empty());
5275         Scope = BPI.SignReturnAddr;
5276         Key = BPI.SignKey;
5277         BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5278       }
5279     }
5280 
5281     auto *Fn = cast<llvm::Function>(GV);
5282     if (Scope != LangOptions::SignReturnAddressScopeKind::None) {
5283       Fn->addFnAttr("sign-return-address",
5284                     Scope == LangOptions::SignReturnAddressScopeKind::All
5285                         ? "all"
5286                         : "non-leaf");
5287 
5288       Fn->addFnAttr("sign-return-address-key",
5289                     Key == LangOptions::SignReturnAddressKeyKind::AKey
5290                         ? "a_key"
5291                         : "b_key");
5292     }
5293 
5294     if (BranchTargetEnforcement)
5295       Fn->addFnAttr("branch-target-enforcement");
5296   }
5297 };
5298 
5299 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5300 public:
5301   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5302       : AArch64TargetCodeGenInfo(CGT, K) {}
5303 
5304   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5305                            CodeGen::CodeGenModule &CGM) const override;
5306 
5307   void getDependentLibraryOption(llvm::StringRef Lib,
5308                                  llvm::SmallString<24> &Opt) const override {
5309     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5310   }
5311 
5312   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5313                                llvm::SmallString<32> &Opt) const override {
5314     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5315   }
5316 };
5317 
5318 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5319     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5320   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5321   if (GV->isDeclaration())
5322     return;
5323   addStackProbeTargetAttributes(D, GV, CGM);
5324 }
5325 }
5326 
5327 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5328   Ty = useFirstFieldIfTransparentUnion(Ty);
5329 
5330   // Handle illegal vector types here.
5331   if (isIllegalVectorType(Ty)) {
5332     uint64_t Size = getContext().getTypeSize(Ty);
5333     // Android promotes <2 x i8> to i16, not i32
5334     if (isAndroid() && (Size <= 16)) {
5335       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5336       return ABIArgInfo::getDirect(ResType);
5337     }
5338     if (Size <= 32) {
5339       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5340       return ABIArgInfo::getDirect(ResType);
5341     }
5342     if (Size == 64) {
5343       llvm::Type *ResType =
5344           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5345       return ABIArgInfo::getDirect(ResType);
5346     }
5347     if (Size == 128) {
5348       llvm::Type *ResType =
5349           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5350       return ABIArgInfo::getDirect(ResType);
5351     }
5352     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5353   }
5354 
5355   if (!isAggregateTypeForABI(Ty)) {
5356     // Treat an enum type as its underlying type.
5357     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5358       Ty = EnumTy->getDecl()->getIntegerType();
5359 
5360     if (const auto *EIT = Ty->getAs<ExtIntType>())
5361       if (EIT->getNumBits() > 128)
5362         return getNaturalAlignIndirect(Ty);
5363 
5364     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5365                 ? ABIArgInfo::getExtend(Ty)
5366                 : ABIArgInfo::getDirect());
5367   }
5368 
5369   // Structures with either a non-trivial destructor or a non-trivial
5370   // copy constructor are always indirect.
5371   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5372     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5373                                      CGCXXABI::RAA_DirectInMemory);
5374   }
5375 
5376   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5377   // elsewhere for GNU compatibility.
5378   uint64_t Size = getContext().getTypeSize(Ty);
5379   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5380   if (IsEmpty || Size == 0) {
5381     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5382       return ABIArgInfo::getIgnore();
5383 
5384     // GNU C mode. The only argument that gets ignored is an empty one with size
5385     // 0.
5386     if (IsEmpty && Size == 0)
5387       return ABIArgInfo::getIgnore();
5388     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5389   }
5390 
5391   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5392   const Type *Base = nullptr;
5393   uint64_t Members = 0;
5394   if (isHomogeneousAggregate(Ty, Base, Members)) {
5395     return ABIArgInfo::getDirect(
5396         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5397   }
5398 
5399   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5400   if (Size <= 128) {
5401     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5402     // same size and alignment.
5403     if (getTarget().isRenderScriptTarget()) {
5404       return coerceToIntArray(Ty, getContext(), getVMContext());
5405     }
5406     unsigned Alignment;
5407     if (Kind == AArch64ABIInfo::AAPCS) {
5408       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5409       Alignment = Alignment < 128 ? 64 : 128;
5410     } else {
5411       Alignment = std::max(getContext().getTypeAlign(Ty),
5412                            (unsigned)getTarget().getPointerWidth(0));
5413     }
5414     Size = llvm::alignTo(Size, Alignment);
5415 
5416     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5417     // For aggregates with 16-byte alignment, we use i128.
5418     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5419     return ABIArgInfo::getDirect(
5420         Size == Alignment ? BaseTy
5421                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5422   }
5423 
5424   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5425 }
5426 
5427 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5428                                               bool IsVariadic) const {
5429   if (RetTy->isVoidType())
5430     return ABIArgInfo::getIgnore();
5431 
5432   // Large vector types should be returned via memory.
5433   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5434     return getNaturalAlignIndirect(RetTy);
5435 
5436   if (!isAggregateTypeForABI(RetTy)) {
5437     // Treat an enum type as its underlying type.
5438     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5439       RetTy = EnumTy->getDecl()->getIntegerType();
5440 
5441     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5442       if (EIT->getNumBits() > 128)
5443         return getNaturalAlignIndirect(RetTy);
5444 
5445     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5446                 ? ABIArgInfo::getExtend(RetTy)
5447                 : ABIArgInfo::getDirect());
5448   }
5449 
5450   uint64_t Size = getContext().getTypeSize(RetTy);
5451   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5452     return ABIArgInfo::getIgnore();
5453 
5454   const Type *Base = nullptr;
5455   uint64_t Members = 0;
5456   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5457       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5458         IsVariadic))
5459     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5460     return ABIArgInfo::getDirect();
5461 
5462   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5463   if (Size <= 128) {
5464     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5465     // same size and alignment.
5466     if (getTarget().isRenderScriptTarget()) {
5467       return coerceToIntArray(RetTy, getContext(), getVMContext());
5468     }
5469     unsigned Alignment = getContext().getTypeAlign(RetTy);
5470     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5471 
5472     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5473     // For aggregates with 16-byte alignment, we use i128.
5474     if (Alignment < 128 && Size == 128) {
5475       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5476       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5477     }
5478     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5479   }
5480 
5481   return getNaturalAlignIndirect(RetTy);
5482 }
5483 
5484 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5485 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5486   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5487     // Check whether VT is legal.
5488     unsigned NumElements = VT->getNumElements();
5489     uint64_t Size = getContext().getTypeSize(VT);
5490     // NumElements should be power of 2.
5491     if (!llvm::isPowerOf2_32(NumElements))
5492       return true;
5493 
5494     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5495     // vectors for some reason.
5496     llvm::Triple Triple = getTarget().getTriple();
5497     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5498         Triple.isOSBinFormatMachO())
5499       return Size <= 32;
5500 
5501     return Size != 64 && (Size != 128 || NumElements == 1);
5502   }
5503   return false;
5504 }
5505 
5506 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5507                                                llvm::Type *eltTy,
5508                                                unsigned elts) const {
5509   if (!llvm::isPowerOf2_32(elts))
5510     return false;
5511   if (totalSize.getQuantity() != 8 &&
5512       (totalSize.getQuantity() != 16 || elts == 1))
5513     return false;
5514   return true;
5515 }
5516 
5517 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5518   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5519   // point type or a short-vector type. This is the same as the 32-bit ABI,
5520   // but with the difference that any floating-point type is allowed,
5521   // including __fp16.
5522   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5523     if (BT->isFloatingPoint())
5524       return true;
5525   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5526     unsigned VecSize = getContext().getTypeSize(VT);
5527     if (VecSize == 64 || VecSize == 128)
5528       return true;
5529   }
5530   return false;
5531 }
5532 
5533 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5534                                                        uint64_t Members) const {
5535   return Members <= 4;
5536 }
5537 
5538 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5539                                             QualType Ty,
5540                                             CodeGenFunction &CGF) const {
5541   ABIArgInfo AI = classifyArgumentType(Ty);
5542   bool IsIndirect = AI.isIndirect();
5543 
5544   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5545   if (IsIndirect)
5546     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5547   else if (AI.getCoerceToType())
5548     BaseTy = AI.getCoerceToType();
5549 
5550   unsigned NumRegs = 1;
5551   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5552     BaseTy = ArrTy->getElementType();
5553     NumRegs = ArrTy->getNumElements();
5554   }
5555   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5556 
5557   // The AArch64 va_list type and handling is specified in the Procedure Call
5558   // Standard, section B.4:
5559   //
5560   // struct {
5561   //   void *__stack;
5562   //   void *__gr_top;
5563   //   void *__vr_top;
5564   //   int __gr_offs;
5565   //   int __vr_offs;
5566   // };
5567 
5568   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5569   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5570   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5571   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5572 
5573   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5574   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5575 
5576   Address reg_offs_p = Address::invalid();
5577   llvm::Value *reg_offs = nullptr;
5578   int reg_top_index;
5579   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5580   if (!IsFPR) {
5581     // 3 is the field number of __gr_offs
5582     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5583     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5584     reg_top_index = 1; // field number for __gr_top
5585     RegSize = llvm::alignTo(RegSize, 8);
5586   } else {
5587     // 4 is the field number of __vr_offs.
5588     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5589     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5590     reg_top_index = 2; // field number for __vr_top
5591     RegSize = 16 * NumRegs;
5592   }
5593 
5594   //=======================================
5595   // Find out where argument was passed
5596   //=======================================
5597 
5598   // If reg_offs >= 0 we're already using the stack for this type of
5599   // argument. We don't want to keep updating reg_offs (in case it overflows,
5600   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5601   // whatever they get).
5602   llvm::Value *UsingStack = nullptr;
5603   UsingStack = CGF.Builder.CreateICmpSGE(
5604       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5605 
5606   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5607 
5608   // Otherwise, at least some kind of argument could go in these registers, the
5609   // question is whether this particular type is too big.
5610   CGF.EmitBlock(MaybeRegBlock);
5611 
5612   // Integer arguments may need to correct register alignment (for example a
5613   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5614   // align __gr_offs to calculate the potential address.
5615   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5616     int Align = TyAlign.getQuantity();
5617 
5618     reg_offs = CGF.Builder.CreateAdd(
5619         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5620         "align_regoffs");
5621     reg_offs = CGF.Builder.CreateAnd(
5622         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5623         "aligned_regoffs");
5624   }
5625 
5626   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5627   // The fact that this is done unconditionally reflects the fact that
5628   // allocating an argument to the stack also uses up all the remaining
5629   // registers of the appropriate kind.
5630   llvm::Value *NewOffset = nullptr;
5631   NewOffset = CGF.Builder.CreateAdd(
5632       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5633   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5634 
5635   // Now we're in a position to decide whether this argument really was in
5636   // registers or not.
5637   llvm::Value *InRegs = nullptr;
5638   InRegs = CGF.Builder.CreateICmpSLE(
5639       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5640 
5641   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5642 
5643   //=======================================
5644   // Argument was in registers
5645   //=======================================
5646 
5647   // Now we emit the code for if the argument was originally passed in
5648   // registers. First start the appropriate block:
5649   CGF.EmitBlock(InRegBlock);
5650 
5651   llvm::Value *reg_top = nullptr;
5652   Address reg_top_p =
5653       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5654   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5655   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5656                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5657   Address RegAddr = Address::invalid();
5658   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5659 
5660   if (IsIndirect) {
5661     // If it's been passed indirectly (actually a struct), whatever we find from
5662     // stored registers or on the stack will actually be a struct **.
5663     MemTy = llvm::PointerType::getUnqual(MemTy);
5664   }
5665 
5666   const Type *Base = nullptr;
5667   uint64_t NumMembers = 0;
5668   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5669   if (IsHFA && NumMembers > 1) {
5670     // Homogeneous aggregates passed in registers will have their elements split
5671     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5672     // qN+1, ...). We reload and store into a temporary local variable
5673     // contiguously.
5674     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5675     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5676     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5677     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5678     Address Tmp = CGF.CreateTempAlloca(HFATy,
5679                                        std::max(TyAlign, BaseTyInfo.second));
5680 
5681     // On big-endian platforms, the value will be right-aligned in its slot.
5682     int Offset = 0;
5683     if (CGF.CGM.getDataLayout().isBigEndian() &&
5684         BaseTyInfo.first.getQuantity() < 16)
5685       Offset = 16 - BaseTyInfo.first.getQuantity();
5686 
5687     for (unsigned i = 0; i < NumMembers; ++i) {
5688       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5689       Address LoadAddr =
5690         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5691       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5692 
5693       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5694 
5695       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5696       CGF.Builder.CreateStore(Elem, StoreAddr);
5697     }
5698 
5699     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5700   } else {
5701     // Otherwise the object is contiguous in memory.
5702 
5703     // It might be right-aligned in its slot.
5704     CharUnits SlotSize = BaseAddr.getAlignment();
5705     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5706         (IsHFA || !isAggregateTypeForABI(Ty)) &&
5707         TySize < SlotSize) {
5708       CharUnits Offset = SlotSize - TySize;
5709       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5710     }
5711 
5712     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5713   }
5714 
5715   CGF.EmitBranch(ContBlock);
5716 
5717   //=======================================
5718   // Argument was on the stack
5719   //=======================================
5720   CGF.EmitBlock(OnStackBlock);
5721 
5722   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
5723   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5724 
5725   // Again, stack arguments may need realignment. In this case both integer and
5726   // floating-point ones might be affected.
5727   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5728     int Align = TyAlign.getQuantity();
5729 
5730     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5731 
5732     OnStackPtr = CGF.Builder.CreateAdd(
5733         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5734         "align_stack");
5735     OnStackPtr = CGF.Builder.CreateAnd(
5736         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5737         "align_stack");
5738 
5739     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5740   }
5741   Address OnStackAddr(OnStackPtr,
5742                       std::max(CharUnits::fromQuantity(8), TyAlign));
5743 
5744   // All stack slots are multiples of 8 bytes.
5745   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5746   CharUnits StackSize;
5747   if (IsIndirect)
5748     StackSize = StackSlotSize;
5749   else
5750     StackSize = TySize.alignTo(StackSlotSize);
5751 
5752   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5753   llvm::Value *NewStack =
5754       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5755 
5756   // Write the new value of __stack for the next call to va_arg
5757   CGF.Builder.CreateStore(NewStack, stack_p);
5758 
5759   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5760       TySize < StackSlotSize) {
5761     CharUnits Offset = StackSlotSize - TySize;
5762     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5763   }
5764 
5765   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5766 
5767   CGF.EmitBranch(ContBlock);
5768 
5769   //=======================================
5770   // Tidy up
5771   //=======================================
5772   CGF.EmitBlock(ContBlock);
5773 
5774   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5775                                  OnStackAddr, OnStackBlock, "vaargs.addr");
5776 
5777   if (IsIndirect)
5778     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5779                    TyAlign);
5780 
5781   return ResAddr;
5782 }
5783 
5784 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5785                                         CodeGenFunction &CGF) const {
5786   // The backend's lowering doesn't support va_arg for aggregates or
5787   // illegal vector types.  Lower VAArg here for these cases and use
5788   // the LLVM va_arg instruction for everything else.
5789   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5790     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5791 
5792   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
5793   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
5794 
5795   // Empty records are ignored for parameter passing purposes.
5796   if (isEmptyRecord(getContext(), Ty, true)) {
5797     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5798     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5799     return Addr;
5800   }
5801 
5802   // The size of the actual thing passed, which might end up just
5803   // being a pointer for indirect types.
5804   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5805 
5806   // Arguments bigger than 16 bytes which aren't homogeneous
5807   // aggregates should be passed indirectly.
5808   bool IsIndirect = false;
5809   if (TyInfo.first.getQuantity() > 16) {
5810     const Type *Base = nullptr;
5811     uint64_t Members = 0;
5812     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5813   }
5814 
5815   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5816                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5817 }
5818 
5819 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5820                                     QualType Ty) const {
5821   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5822                           CGF.getContext().getTypeInfoInChars(Ty),
5823                           CharUnits::fromQuantity(8),
5824                           /*allowHigherAlign*/ false);
5825 }
5826 
5827 //===----------------------------------------------------------------------===//
5828 // ARM ABI Implementation
5829 //===----------------------------------------------------------------------===//
5830 
5831 namespace {
5832 
5833 class ARMABIInfo : public SwiftABIInfo {
5834 public:
5835   enum ABIKind {
5836     APCS = 0,
5837     AAPCS = 1,
5838     AAPCS_VFP = 2,
5839     AAPCS16_VFP = 3,
5840   };
5841 
5842 private:
5843   ABIKind Kind;
5844 
5845 public:
5846   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5847       : SwiftABIInfo(CGT), Kind(_Kind) {
5848     setCCs();
5849   }
5850 
5851   bool isEABI() const {
5852     switch (getTarget().getTriple().getEnvironment()) {
5853     case llvm::Triple::Android:
5854     case llvm::Triple::EABI:
5855     case llvm::Triple::EABIHF:
5856     case llvm::Triple::GNUEABI:
5857     case llvm::Triple::GNUEABIHF:
5858     case llvm::Triple::MuslEABI:
5859     case llvm::Triple::MuslEABIHF:
5860       return true;
5861     default:
5862       return false;
5863     }
5864   }
5865 
5866   bool isEABIHF() const {
5867     switch (getTarget().getTriple().getEnvironment()) {
5868     case llvm::Triple::EABIHF:
5869     case llvm::Triple::GNUEABIHF:
5870     case llvm::Triple::MuslEABIHF:
5871       return true;
5872     default:
5873       return false;
5874     }
5875   }
5876 
5877   ABIKind getABIKind() const { return Kind; }
5878 
5879 private:
5880   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5881                                 unsigned functionCallConv) const;
5882   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5883                                   unsigned functionCallConv) const;
5884   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5885                                           uint64_t Members) const;
5886   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5887   bool isIllegalVectorType(QualType Ty) const;
5888   bool containsAnyFP16Vectors(QualType Ty) const;
5889 
5890   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5891   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5892                                          uint64_t Members) const override;
5893 
5894   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5895 
5896   void computeInfo(CGFunctionInfo &FI) const override;
5897 
5898   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5899                     QualType Ty) const override;
5900 
5901   llvm::CallingConv::ID getLLVMDefaultCC() const;
5902   llvm::CallingConv::ID getABIDefaultCC() const;
5903   void setCCs();
5904 
5905   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5906                                     bool asReturnValue) const override {
5907     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5908   }
5909   bool isSwiftErrorInRegister() const override {
5910     return true;
5911   }
5912   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5913                                  unsigned elts) const override;
5914 };
5915 
5916 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5917 public:
5918   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5919       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
5920 
5921   const ARMABIInfo &getABIInfo() const {
5922     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5923   }
5924 
5925   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5926     return 13;
5927   }
5928 
5929   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5930     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
5931   }
5932 
5933   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5934                                llvm::Value *Address) const override {
5935     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5936 
5937     // 0-15 are the 16 integer registers.
5938     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5939     return false;
5940   }
5941 
5942   unsigned getSizeOfUnwindException() const override {
5943     if (getABIInfo().isEABI()) return 88;
5944     return TargetCodeGenInfo::getSizeOfUnwindException();
5945   }
5946 
5947   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5948                            CodeGen::CodeGenModule &CGM) const override {
5949     if (GV->isDeclaration())
5950       return;
5951     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5952     if (!FD)
5953       return;
5954 
5955     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5956     if (!Attr)
5957       return;
5958 
5959     const char *Kind;
5960     switch (Attr->getInterrupt()) {
5961     case ARMInterruptAttr::Generic: Kind = ""; break;
5962     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
5963     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
5964     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
5965     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
5966     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
5967     }
5968 
5969     llvm::Function *Fn = cast<llvm::Function>(GV);
5970 
5971     Fn->addFnAttr("interrupt", Kind);
5972 
5973     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5974     if (ABI == ARMABIInfo::APCS)
5975       return;
5976 
5977     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5978     // however this is not necessarily true on taking any interrupt. Instruct
5979     // the backend to perform a realignment as part of the function prologue.
5980     llvm::AttrBuilder B;
5981     B.addStackAlignmentAttr(8);
5982     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5983   }
5984 };
5985 
5986 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5987 public:
5988   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5989       : ARMTargetCodeGenInfo(CGT, K) {}
5990 
5991   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5992                            CodeGen::CodeGenModule &CGM) const override;
5993 
5994   void getDependentLibraryOption(llvm::StringRef Lib,
5995                                  llvm::SmallString<24> &Opt) const override {
5996     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5997   }
5998 
5999   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6000                                llvm::SmallString<32> &Opt) const override {
6001     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6002   }
6003 };
6004 
6005 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6006     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6007   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6008   if (GV->isDeclaration())
6009     return;
6010   addStackProbeTargetAttributes(D, GV, CGM);
6011 }
6012 }
6013 
6014 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6015   if (!::classifyReturnType(getCXXABI(), FI, *this))
6016     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6017                                             FI.getCallingConvention());
6018 
6019   for (auto &I : FI.arguments())
6020     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6021                                   FI.getCallingConvention());
6022 
6023 
6024   // Always honor user-specified calling convention.
6025   if (FI.getCallingConvention() != llvm::CallingConv::C)
6026     return;
6027 
6028   llvm::CallingConv::ID cc = getRuntimeCC();
6029   if (cc != llvm::CallingConv::C)
6030     FI.setEffectiveCallingConvention(cc);
6031 }
6032 
6033 /// Return the default calling convention that LLVM will use.
6034 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6035   // The default calling convention that LLVM will infer.
6036   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6037     return llvm::CallingConv::ARM_AAPCS_VFP;
6038   else if (isEABI())
6039     return llvm::CallingConv::ARM_AAPCS;
6040   else
6041     return llvm::CallingConv::ARM_APCS;
6042 }
6043 
6044 /// Return the calling convention that our ABI would like us to use
6045 /// as the C calling convention.
6046 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6047   switch (getABIKind()) {
6048   case APCS: return llvm::CallingConv::ARM_APCS;
6049   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6050   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6051   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6052   }
6053   llvm_unreachable("bad ABI kind");
6054 }
6055 
6056 void ARMABIInfo::setCCs() {
6057   assert(getRuntimeCC() == llvm::CallingConv::C);
6058 
6059   // Don't muddy up the IR with a ton of explicit annotations if
6060   // they'd just match what LLVM will infer from the triple.
6061   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6062   if (abiCC != getLLVMDefaultCC())
6063     RuntimeCC = abiCC;
6064 }
6065 
6066 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6067   uint64_t Size = getContext().getTypeSize(Ty);
6068   if (Size <= 32) {
6069     llvm::Type *ResType =
6070         llvm::Type::getInt32Ty(getVMContext());
6071     return ABIArgInfo::getDirect(ResType);
6072   }
6073   if (Size == 64 || Size == 128) {
6074     llvm::Type *ResType = llvm::VectorType::get(
6075         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6076     return ABIArgInfo::getDirect(ResType);
6077   }
6078   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6079 }
6080 
6081 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6082                                                     const Type *Base,
6083                                                     uint64_t Members) const {
6084   assert(Base && "Base class should be set for homogeneous aggregate");
6085   // Base can be a floating-point or a vector.
6086   if (const VectorType *VT = Base->getAs<VectorType>()) {
6087     // FP16 vectors should be converted to integer vectors
6088     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6089       uint64_t Size = getContext().getTypeSize(VT);
6090       llvm::Type *NewVecTy = llvm::VectorType::get(
6091           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6092       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6093       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6094     }
6095   }
6096   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6097 }
6098 
6099 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6100                                             unsigned functionCallConv) const {
6101   // 6.1.2.1 The following argument types are VFP CPRCs:
6102   //   A single-precision floating-point type (including promoted
6103   //   half-precision types); A double-precision floating-point type;
6104   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6105   //   with a Base Type of a single- or double-precision floating-point type,
6106   //   64-bit containerized vectors or 128-bit containerized vectors with one
6107   //   to four Elements.
6108   // Variadic functions should always marshal to the base standard.
6109   bool IsAAPCS_VFP =
6110       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6111 
6112   Ty = useFirstFieldIfTransparentUnion(Ty);
6113 
6114   // Handle illegal vector types here.
6115   if (isIllegalVectorType(Ty))
6116     return coerceIllegalVector(Ty);
6117 
6118   // _Float16 and __fp16 get passed as if it were an int or float, but with
6119   // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6120   // half type natively, and does not need to interwork with AAPCS code.
6121   if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
6122       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6123     llvm::Type *ResType = IsAAPCS_VFP ?
6124       llvm::Type::getFloatTy(getVMContext()) :
6125       llvm::Type::getInt32Ty(getVMContext());
6126     return ABIArgInfo::getDirect(ResType);
6127   }
6128 
6129   if (!isAggregateTypeForABI(Ty)) {
6130     // Treat an enum type as its underlying type.
6131     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6132       Ty = EnumTy->getDecl()->getIntegerType();
6133     }
6134 
6135     if (const auto *EIT = Ty->getAs<ExtIntType>())
6136       if (EIT->getNumBits() > 64)
6137         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6138 
6139     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6140                                               : ABIArgInfo::getDirect());
6141   }
6142 
6143   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6144     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6145   }
6146 
6147   // Ignore empty records.
6148   if (isEmptyRecord(getContext(), Ty, true))
6149     return ABIArgInfo::getIgnore();
6150 
6151   if (IsAAPCS_VFP) {
6152     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6153     // into VFP registers.
6154     const Type *Base = nullptr;
6155     uint64_t Members = 0;
6156     if (isHomogeneousAggregate(Ty, Base, Members))
6157       return classifyHomogeneousAggregate(Ty, Base, Members);
6158   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6159     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6160     // this convention even for a variadic function: the backend will use GPRs
6161     // if needed.
6162     const Type *Base = nullptr;
6163     uint64_t Members = 0;
6164     if (isHomogeneousAggregate(Ty, Base, Members)) {
6165       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6166       llvm::Type *Ty =
6167         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6168       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6169     }
6170   }
6171 
6172   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6173       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6174     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6175     // bigger than 128-bits, they get placed in space allocated by the caller,
6176     // and a pointer is passed.
6177     return ABIArgInfo::getIndirect(
6178         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6179   }
6180 
6181   // Support byval for ARM.
6182   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6183   // most 8-byte. We realign the indirect argument if type alignment is bigger
6184   // than ABI alignment.
6185   uint64_t ABIAlign = 4;
6186   uint64_t TyAlign;
6187   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6188       getABIKind() == ARMABIInfo::AAPCS) {
6189     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6190     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6191   } else {
6192     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6193   }
6194   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6195     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6196     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6197                                    /*ByVal=*/true,
6198                                    /*Realign=*/TyAlign > ABIAlign);
6199   }
6200 
6201   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6202   // same size and alignment.
6203   if (getTarget().isRenderScriptTarget()) {
6204     return coerceToIntArray(Ty, getContext(), getVMContext());
6205   }
6206 
6207   // Otherwise, pass by coercing to a structure of the appropriate size.
6208   llvm::Type* ElemTy;
6209   unsigned SizeRegs;
6210   // FIXME: Try to match the types of the arguments more accurately where
6211   // we can.
6212   if (TyAlign <= 4) {
6213     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6214     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6215   } else {
6216     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6217     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6218   }
6219 
6220   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6221 }
6222 
6223 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6224                               llvm::LLVMContext &VMContext) {
6225   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6226   // is called integer-like if its size is less than or equal to one word, and
6227   // the offset of each of its addressable sub-fields is zero.
6228 
6229   uint64_t Size = Context.getTypeSize(Ty);
6230 
6231   // Check that the type fits in a word.
6232   if (Size > 32)
6233     return false;
6234 
6235   // FIXME: Handle vector types!
6236   if (Ty->isVectorType())
6237     return false;
6238 
6239   // Float types are never treated as "integer like".
6240   if (Ty->isRealFloatingType())
6241     return false;
6242 
6243   // If this is a builtin or pointer type then it is ok.
6244   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6245     return true;
6246 
6247   // Small complex integer types are "integer like".
6248   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6249     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6250 
6251   // Single element and zero sized arrays should be allowed, by the definition
6252   // above, but they are not.
6253 
6254   // Otherwise, it must be a record type.
6255   const RecordType *RT = Ty->getAs<RecordType>();
6256   if (!RT) return false;
6257 
6258   // Ignore records with flexible arrays.
6259   const RecordDecl *RD = RT->getDecl();
6260   if (RD->hasFlexibleArrayMember())
6261     return false;
6262 
6263   // Check that all sub-fields are at offset 0, and are themselves "integer
6264   // like".
6265   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6266 
6267   bool HadField = false;
6268   unsigned idx = 0;
6269   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6270        i != e; ++i, ++idx) {
6271     const FieldDecl *FD = *i;
6272 
6273     // Bit-fields are not addressable, we only need to verify they are "integer
6274     // like". We still have to disallow a subsequent non-bitfield, for example:
6275     //   struct { int : 0; int x }
6276     // is non-integer like according to gcc.
6277     if (FD->isBitField()) {
6278       if (!RD->isUnion())
6279         HadField = true;
6280 
6281       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6282         return false;
6283 
6284       continue;
6285     }
6286 
6287     // Check if this field is at offset 0.
6288     if (Layout.getFieldOffset(idx) != 0)
6289       return false;
6290 
6291     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6292       return false;
6293 
6294     // Only allow at most one field in a structure. This doesn't match the
6295     // wording above, but follows gcc in situations with a field following an
6296     // empty structure.
6297     if (!RD->isUnion()) {
6298       if (HadField)
6299         return false;
6300 
6301       HadField = true;
6302     }
6303   }
6304 
6305   return true;
6306 }
6307 
6308 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6309                                           unsigned functionCallConv) const {
6310 
6311   // Variadic functions should always marshal to the base standard.
6312   bool IsAAPCS_VFP =
6313       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6314 
6315   if (RetTy->isVoidType())
6316     return ABIArgInfo::getIgnore();
6317 
6318   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6319     // Large vector types should be returned via memory.
6320     if (getContext().getTypeSize(RetTy) > 128)
6321       return getNaturalAlignIndirect(RetTy);
6322     // FP16 vectors should be converted to integer vectors
6323     if (!getTarget().hasLegalHalfType() &&
6324         (VT->getElementType()->isFloat16Type() ||
6325          VT->getElementType()->isHalfType()))
6326       return coerceIllegalVector(RetTy);
6327   }
6328 
6329   // _Float16 and __fp16 get returned as if it were an int or float, but with
6330   // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6331   // half type natively, and does not need to interwork with AAPCS code.
6332   if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6333       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6334     llvm::Type *ResType = IsAAPCS_VFP ?
6335       llvm::Type::getFloatTy(getVMContext()) :
6336       llvm::Type::getInt32Ty(getVMContext());
6337     return ABIArgInfo::getDirect(ResType);
6338   }
6339 
6340   if (!isAggregateTypeForABI(RetTy)) {
6341     // Treat an enum type as its underlying type.
6342     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6343       RetTy = EnumTy->getDecl()->getIntegerType();
6344 
6345     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6346       if (EIT->getNumBits() > 64)
6347         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6348 
6349     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6350                                                 : ABIArgInfo::getDirect();
6351   }
6352 
6353   // Are we following APCS?
6354   if (getABIKind() == APCS) {
6355     if (isEmptyRecord(getContext(), RetTy, false))
6356       return ABIArgInfo::getIgnore();
6357 
6358     // Complex types are all returned as packed integers.
6359     //
6360     // FIXME: Consider using 2 x vector types if the back end handles them
6361     // correctly.
6362     if (RetTy->isAnyComplexType())
6363       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6364           getVMContext(), getContext().getTypeSize(RetTy)));
6365 
6366     // Integer like structures are returned in r0.
6367     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6368       // Return in the smallest viable integer type.
6369       uint64_t Size = getContext().getTypeSize(RetTy);
6370       if (Size <= 8)
6371         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6372       if (Size <= 16)
6373         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6374       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6375     }
6376 
6377     // Otherwise return in memory.
6378     return getNaturalAlignIndirect(RetTy);
6379   }
6380 
6381   // Otherwise this is an AAPCS variant.
6382 
6383   if (isEmptyRecord(getContext(), RetTy, true))
6384     return ABIArgInfo::getIgnore();
6385 
6386   // Check for homogeneous aggregates with AAPCS-VFP.
6387   if (IsAAPCS_VFP) {
6388     const Type *Base = nullptr;
6389     uint64_t Members = 0;
6390     if (isHomogeneousAggregate(RetTy, Base, Members))
6391       return classifyHomogeneousAggregate(RetTy, Base, Members);
6392   }
6393 
6394   // Aggregates <= 4 bytes are returned in r0; other aggregates
6395   // are returned indirectly.
6396   uint64_t Size = getContext().getTypeSize(RetTy);
6397   if (Size <= 32) {
6398     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6399     // same size and alignment.
6400     if (getTarget().isRenderScriptTarget()) {
6401       return coerceToIntArray(RetTy, getContext(), getVMContext());
6402     }
6403     if (getDataLayout().isBigEndian())
6404       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6405       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6406 
6407     // Return in the smallest viable integer type.
6408     if (Size <= 8)
6409       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6410     if (Size <= 16)
6411       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6412     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6413   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6414     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6415     llvm::Type *CoerceTy =
6416         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6417     return ABIArgInfo::getDirect(CoerceTy);
6418   }
6419 
6420   return getNaturalAlignIndirect(RetTy);
6421 }
6422 
6423 /// isIllegalVector - check whether Ty is an illegal vector type.
6424 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6425   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6426     // On targets that don't support FP16, FP16 is expanded into float, and we
6427     // don't want the ABI to depend on whether or not FP16 is supported in
6428     // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6429     if (!getTarget().hasLegalHalfType() &&
6430         (VT->getElementType()->isFloat16Type() ||
6431          VT->getElementType()->isHalfType()))
6432       return true;
6433     if (isAndroid()) {
6434       // Android shipped using Clang 3.1, which supported a slightly different
6435       // vector ABI. The primary differences were that 3-element vector types
6436       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6437       // accepts that legacy behavior for Android only.
6438       // Check whether VT is legal.
6439       unsigned NumElements = VT->getNumElements();
6440       // NumElements should be power of 2 or equal to 3.
6441       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6442         return true;
6443     } else {
6444       // Check whether VT is legal.
6445       unsigned NumElements = VT->getNumElements();
6446       uint64_t Size = getContext().getTypeSize(VT);
6447       // NumElements should be power of 2.
6448       if (!llvm::isPowerOf2_32(NumElements))
6449         return true;
6450       // Size should be greater than 32 bits.
6451       return Size <= 32;
6452     }
6453   }
6454   return false;
6455 }
6456 
6457 /// Return true if a type contains any 16-bit floating point vectors
6458 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6459   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6460     uint64_t NElements = AT->getSize().getZExtValue();
6461     if (NElements == 0)
6462       return false;
6463     return containsAnyFP16Vectors(AT->getElementType());
6464   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6465     const RecordDecl *RD = RT->getDecl();
6466 
6467     // If this is a C++ record, check the bases first.
6468     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6469       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6470             return containsAnyFP16Vectors(B.getType());
6471           }))
6472         return true;
6473 
6474     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6475           return FD && containsAnyFP16Vectors(FD->getType());
6476         }))
6477       return true;
6478 
6479     return false;
6480   } else {
6481     if (const VectorType *VT = Ty->getAs<VectorType>())
6482       return (VT->getElementType()->isFloat16Type() ||
6483               VT->getElementType()->isHalfType());
6484     return false;
6485   }
6486 }
6487 
6488 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6489                                            llvm::Type *eltTy,
6490                                            unsigned numElts) const {
6491   if (!llvm::isPowerOf2_32(numElts))
6492     return false;
6493   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6494   if (size > 64)
6495     return false;
6496   if (vectorSize.getQuantity() != 8 &&
6497       (vectorSize.getQuantity() != 16 || numElts == 1))
6498     return false;
6499   return true;
6500 }
6501 
6502 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6503   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6504   // double, or 64-bit or 128-bit vectors.
6505   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6506     if (BT->getKind() == BuiltinType::Float ||
6507         BT->getKind() == BuiltinType::Double ||
6508         BT->getKind() == BuiltinType::LongDouble)
6509       return true;
6510   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6511     unsigned VecSize = getContext().getTypeSize(VT);
6512     if (VecSize == 64 || VecSize == 128)
6513       return true;
6514   }
6515   return false;
6516 }
6517 
6518 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6519                                                    uint64_t Members) const {
6520   return Members <= 4;
6521 }
6522 
6523 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6524                                         bool acceptHalf) const {
6525   // Give precedence to user-specified calling conventions.
6526   if (callConvention != llvm::CallingConv::C)
6527     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6528   else
6529     return (getABIKind() == AAPCS_VFP) ||
6530            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6531 }
6532 
6533 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6534                               QualType Ty) const {
6535   CharUnits SlotSize = CharUnits::fromQuantity(4);
6536 
6537   // Empty records are ignored for parameter passing purposes.
6538   if (isEmptyRecord(getContext(), Ty, true)) {
6539     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6540     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6541     return Addr;
6542   }
6543 
6544   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6545   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6546 
6547   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6548   bool IsIndirect = false;
6549   const Type *Base = nullptr;
6550   uint64_t Members = 0;
6551   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6552     IsIndirect = true;
6553 
6554   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6555   // allocated by the caller.
6556   } else if (TySize > CharUnits::fromQuantity(16) &&
6557              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6558              !isHomogeneousAggregate(Ty, Base, Members)) {
6559     IsIndirect = true;
6560 
6561   // Otherwise, bound the type's ABI alignment.
6562   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6563   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6564   // Our callers should be prepared to handle an under-aligned address.
6565   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6566              getABIKind() == ARMABIInfo::AAPCS) {
6567     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6568     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6569   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6570     // ARMv7k allows type alignment up to 16 bytes.
6571     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6572     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6573   } else {
6574     TyAlignForABI = CharUnits::fromQuantity(4);
6575   }
6576 
6577   std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
6578   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6579                           SlotSize, /*AllowHigherAlign*/ true);
6580 }
6581 
6582 //===----------------------------------------------------------------------===//
6583 // NVPTX ABI Implementation
6584 //===----------------------------------------------------------------------===//
6585 
6586 namespace {
6587 
6588 class NVPTXTargetCodeGenInfo;
6589 
6590 class NVPTXABIInfo : public ABIInfo {
6591   NVPTXTargetCodeGenInfo &CGInfo;
6592 
6593 public:
6594   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6595       : ABIInfo(CGT), CGInfo(Info) {}
6596 
6597   ABIArgInfo classifyReturnType(QualType RetTy) const;
6598   ABIArgInfo classifyArgumentType(QualType Ty) const;
6599 
6600   void computeInfo(CGFunctionInfo &FI) const override;
6601   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6602                     QualType Ty) const override;
6603   bool isUnsupportedType(QualType T) const;
6604   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6605 };
6606 
6607 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6608 public:
6609   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6610       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6611 
6612   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6613                            CodeGen::CodeGenModule &M) const override;
6614   bool shouldEmitStaticExternCAliases() const override;
6615 
6616   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6617     // On the device side, surface reference is represented as an object handle
6618     // in 64-bit integer.
6619     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6620   }
6621 
6622   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6623     // On the device side, texture reference is represented as an object handle
6624     // in 64-bit integer.
6625     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6626   }
6627 
6628   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6629                                               LValue Src) const override {
6630     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6631     return true;
6632   }
6633 
6634   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6635                                               LValue Src) const override {
6636     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6637     return true;
6638   }
6639 
6640 private:
6641   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6642   // resulting MDNode to the nvvm.annotations MDNode.
6643   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6644                               int Operand);
6645 
6646   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6647                                            LValue Src) {
6648     llvm::Value *Handle = nullptr;
6649     llvm::Constant *C =
6650         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6651     // Lookup `addrspacecast` through the constant pointer if any.
6652     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6653       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6654     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6655       // Load the handle from the specific global variable using
6656       // `nvvm.texsurf.handle.internal` intrinsic.
6657       Handle = CGF.EmitRuntimeCall(
6658           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6659                                {GV->getType()}),
6660           {GV}, "texsurf_handle");
6661     } else
6662       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6663     CGF.EmitStoreOfScalar(Handle, Dst);
6664   }
6665 };
6666 
6667 /// Checks if the type is unsupported directly by the current target.
6668 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6669   ASTContext &Context = getContext();
6670   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6671     return true;
6672   if (!Context.getTargetInfo().hasFloat128Type() &&
6673       (T->isFloat128Type() ||
6674        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6675     return true;
6676   if (const auto *EIT = T->getAs<ExtIntType>())
6677     return EIT->getNumBits() >
6678            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6679   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6680       Context.getTypeSize(T) > 64U)
6681     return true;
6682   if (const auto *AT = T->getAsArrayTypeUnsafe())
6683     return isUnsupportedType(AT->getElementType());
6684   const auto *RT = T->getAs<RecordType>();
6685   if (!RT)
6686     return false;
6687   const RecordDecl *RD = RT->getDecl();
6688 
6689   // If this is a C++ record, check the bases first.
6690   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6691     for (const CXXBaseSpecifier &I : CXXRD->bases())
6692       if (isUnsupportedType(I.getType()))
6693         return true;
6694 
6695   for (const FieldDecl *I : RD->fields())
6696     if (isUnsupportedType(I->getType()))
6697       return true;
6698   return false;
6699 }
6700 
6701 /// Coerce the given type into an array with maximum allowed size of elements.
6702 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6703                                                    unsigned MaxSize) const {
6704   // Alignment and Size are measured in bits.
6705   const uint64_t Size = getContext().getTypeSize(Ty);
6706   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6707   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6708   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
6709   const uint64_t NumElements = (Size + Div - 1) / Div;
6710   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6711 }
6712 
6713 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6714   if (RetTy->isVoidType())
6715     return ABIArgInfo::getIgnore();
6716 
6717   if (getContext().getLangOpts().OpenMP &&
6718       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
6719     return coerceToIntArrayWithLimit(RetTy, 64);
6720 
6721   // note: this is different from default ABI
6722   if (!RetTy->isScalarType())
6723     return ABIArgInfo::getDirect();
6724 
6725   // Treat an enum type as its underlying type.
6726   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6727     RetTy = EnumTy->getDecl()->getIntegerType();
6728 
6729   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6730                                                : ABIArgInfo::getDirect());
6731 }
6732 
6733 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6734   // Treat an enum type as its underlying type.
6735   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6736     Ty = EnumTy->getDecl()->getIntegerType();
6737 
6738   // Return aggregates type as indirect by value
6739   if (isAggregateTypeForABI(Ty)) {
6740     // Under CUDA device compilation, tex/surf builtin types are replaced with
6741     // object types and passed directly.
6742     if (getContext().getLangOpts().CUDAIsDevice) {
6743       if (Ty->isCUDADeviceBuiltinSurfaceType())
6744         return ABIArgInfo::getDirect(
6745             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
6746       if (Ty->isCUDADeviceBuiltinTextureType())
6747         return ABIArgInfo::getDirect(
6748             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
6749     }
6750     return getNaturalAlignIndirect(Ty, /* byval */ true);
6751   }
6752 
6753   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
6754     if ((EIT->getNumBits() > 128) ||
6755         (!getContext().getTargetInfo().hasInt128Type() &&
6756          EIT->getNumBits() > 64))
6757       return getNaturalAlignIndirect(Ty, /* byval */ true);
6758   }
6759 
6760   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6761                                             : ABIArgInfo::getDirect());
6762 }
6763 
6764 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6765   if (!getCXXABI().classifyReturnType(FI))
6766     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6767   for (auto &I : FI.arguments())
6768     I.info = classifyArgumentType(I.type);
6769 
6770   // Always honor user-specified calling convention.
6771   if (FI.getCallingConvention() != llvm::CallingConv::C)
6772     return;
6773 
6774   FI.setEffectiveCallingConvention(getRuntimeCC());
6775 }
6776 
6777 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6778                                 QualType Ty) const {
6779   llvm_unreachable("NVPTX does not support varargs");
6780 }
6781 
6782 void NVPTXTargetCodeGenInfo::setTargetAttributes(
6783     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6784   if (GV->isDeclaration())
6785     return;
6786   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6787   if (VD) {
6788     if (M.getLangOpts().CUDA) {
6789       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
6790         addNVVMMetadata(GV, "surface", 1);
6791       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
6792         addNVVMMetadata(GV, "texture", 1);
6793       return;
6794     }
6795   }
6796 
6797   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6798   if (!FD) return;
6799 
6800   llvm::Function *F = cast<llvm::Function>(GV);
6801 
6802   // Perform special handling in OpenCL mode
6803   if (M.getLangOpts().OpenCL) {
6804     // Use OpenCL function attributes to check for kernel functions
6805     // By default, all functions are device functions
6806     if (FD->hasAttr<OpenCLKernelAttr>()) {
6807       // OpenCL __kernel functions get kernel metadata
6808       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6809       addNVVMMetadata(F, "kernel", 1);
6810       // And kernel functions are not subject to inlining
6811       F->addFnAttr(llvm::Attribute::NoInline);
6812     }
6813   }
6814 
6815   // Perform special handling in CUDA mode.
6816   if (M.getLangOpts().CUDA) {
6817     // CUDA __global__ functions get a kernel metadata entry.  Since
6818     // __global__ functions cannot be called from the device, we do not
6819     // need to set the noinline attribute.
6820     if (FD->hasAttr<CUDAGlobalAttr>()) {
6821       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6822       addNVVMMetadata(F, "kernel", 1);
6823     }
6824     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6825       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6826       llvm::APSInt MaxThreads(32);
6827       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6828       if (MaxThreads > 0)
6829         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6830 
6831       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6832       // not specified in __launch_bounds__ or if the user specified a 0 value,
6833       // we don't have to add a PTX directive.
6834       if (Attr->getMinBlocks()) {
6835         llvm::APSInt MinBlocks(32);
6836         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6837         if (MinBlocks > 0)
6838           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6839           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6840       }
6841     }
6842   }
6843 }
6844 
6845 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
6846                                              StringRef Name, int Operand) {
6847   llvm::Module *M = GV->getParent();
6848   llvm::LLVMContext &Ctx = M->getContext();
6849 
6850   // Get "nvvm.annotations" metadata node
6851   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6852 
6853   llvm::Metadata *MDVals[] = {
6854       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
6855       llvm::ConstantAsMetadata::get(
6856           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6857   // Append metadata to nvvm.annotations
6858   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6859 }
6860 
6861 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6862   return false;
6863 }
6864 }
6865 
6866 //===----------------------------------------------------------------------===//
6867 // SystemZ ABI Implementation
6868 //===----------------------------------------------------------------------===//
6869 
6870 namespace {
6871 
6872 class SystemZABIInfo : public SwiftABIInfo {
6873   bool HasVector;
6874   bool IsSoftFloatABI;
6875 
6876 public:
6877   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
6878     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
6879 
6880   bool isPromotableIntegerTypeForABI(QualType Ty) const;
6881   bool isCompoundType(QualType Ty) const;
6882   bool isVectorArgumentType(QualType Ty) const;
6883   bool isFPArgumentType(QualType Ty) const;
6884   QualType GetSingleElementType(QualType Ty) const;
6885 
6886   ABIArgInfo classifyReturnType(QualType RetTy) const;
6887   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6888 
6889   void computeInfo(CGFunctionInfo &FI) const override {
6890     if (!getCXXABI().classifyReturnType(FI))
6891       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6892     for (auto &I : FI.arguments())
6893       I.info = classifyArgumentType(I.type);
6894   }
6895 
6896   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6897                     QualType Ty) const override;
6898 
6899   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6900                                     bool asReturnValue) const override {
6901     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6902   }
6903   bool isSwiftErrorInRegister() const override {
6904     return false;
6905   }
6906 };
6907 
6908 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6909 public:
6910   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
6911       : TargetCodeGenInfo(
6912             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
6913 };
6914 
6915 }
6916 
6917 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
6918   // Treat an enum type as its underlying type.
6919   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6920     Ty = EnumTy->getDecl()->getIntegerType();
6921 
6922   // Promotable integer types are required to be promoted by the ABI.
6923   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
6924     return true;
6925 
6926   if (const auto *EIT = Ty->getAs<ExtIntType>())
6927     if (EIT->getNumBits() < 64)
6928       return true;
6929 
6930   // 32-bit values must also be promoted.
6931   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6932     switch (BT->getKind()) {
6933     case BuiltinType::Int:
6934     case BuiltinType::UInt:
6935       return true;
6936     default:
6937       return false;
6938     }
6939   return false;
6940 }
6941 
6942 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6943   return (Ty->isAnyComplexType() ||
6944           Ty->isVectorType() ||
6945           isAggregateTypeForABI(Ty));
6946 }
6947 
6948 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6949   return (HasVector &&
6950           Ty->isVectorType() &&
6951           getContext().getTypeSize(Ty) <= 128);
6952 }
6953 
6954 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6955   if (IsSoftFloatABI)
6956     return false;
6957 
6958   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6959     switch (BT->getKind()) {
6960     case BuiltinType::Float:
6961     case BuiltinType::Double:
6962       return true;
6963     default:
6964       return false;
6965     }
6966 
6967   return false;
6968 }
6969 
6970 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6971   if (const RecordType *RT = Ty->getAsStructureType()) {
6972     const RecordDecl *RD = RT->getDecl();
6973     QualType Found;
6974 
6975     // If this is a C++ record, check the bases first.
6976     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6977       for (const auto &I : CXXRD->bases()) {
6978         QualType Base = I.getType();
6979 
6980         // Empty bases don't affect things either way.
6981         if (isEmptyRecord(getContext(), Base, true))
6982           continue;
6983 
6984         if (!Found.isNull())
6985           return Ty;
6986         Found = GetSingleElementType(Base);
6987       }
6988 
6989     // Check the fields.
6990     for (const auto *FD : RD->fields()) {
6991       // For compatibility with GCC, ignore empty bitfields in C++ mode.
6992       // Unlike isSingleElementStruct(), empty structure and array fields
6993       // do count.  So do anonymous bitfields that aren't zero-sized.
6994       if (getContext().getLangOpts().CPlusPlus &&
6995           FD->isZeroLengthBitField(getContext()))
6996         continue;
6997 
6998       // Unlike isSingleElementStruct(), arrays do not count.
6999       // Nested structures still do though.
7000       if (!Found.isNull())
7001         return Ty;
7002       Found = GetSingleElementType(FD->getType());
7003     }
7004 
7005     // Unlike isSingleElementStruct(), trailing padding is allowed.
7006     // An 8-byte aligned struct s { float f; } is passed as a double.
7007     if (!Found.isNull())
7008       return Found;
7009   }
7010 
7011   return Ty;
7012 }
7013 
7014 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7015                                   QualType Ty) const {
7016   // Assume that va_list type is correct; should be pointer to LLVM type:
7017   // struct {
7018   //   i64 __gpr;
7019   //   i64 __fpr;
7020   //   i8 *__overflow_arg_area;
7021   //   i8 *__reg_save_area;
7022   // };
7023 
7024   // Every non-vector argument occupies 8 bytes and is passed by preference
7025   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7026   // always passed on the stack.
7027   Ty = getContext().getCanonicalType(Ty);
7028   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7029   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7030   llvm::Type *DirectTy = ArgTy;
7031   ABIArgInfo AI = classifyArgumentType(Ty);
7032   bool IsIndirect = AI.isIndirect();
7033   bool InFPRs = false;
7034   bool IsVector = false;
7035   CharUnits UnpaddedSize;
7036   CharUnits DirectAlign;
7037   if (IsIndirect) {
7038     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7039     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7040   } else {
7041     if (AI.getCoerceToType())
7042       ArgTy = AI.getCoerceToType();
7043     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7044     IsVector = ArgTy->isVectorTy();
7045     UnpaddedSize = TyInfo.first;
7046     DirectAlign = TyInfo.second;
7047   }
7048   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7049   if (IsVector && UnpaddedSize > PaddedSize)
7050     PaddedSize = CharUnits::fromQuantity(16);
7051   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7052 
7053   CharUnits Padding = (PaddedSize - UnpaddedSize);
7054 
7055   llvm::Type *IndexTy = CGF.Int64Ty;
7056   llvm::Value *PaddedSizeV =
7057     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7058 
7059   if (IsVector) {
7060     // Work out the address of a vector argument on the stack.
7061     // Vector arguments are always passed in the high bits of a
7062     // single (8 byte) or double (16 byte) stack slot.
7063     Address OverflowArgAreaPtr =
7064         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7065     Address OverflowArgArea =
7066       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7067               TyInfo.second);
7068     Address MemAddr =
7069       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7070 
7071     // Update overflow_arg_area_ptr pointer
7072     llvm::Value *NewOverflowArgArea =
7073       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7074                             "overflow_arg_area");
7075     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7076 
7077     return MemAddr;
7078   }
7079 
7080   assert(PaddedSize.getQuantity() == 8);
7081 
7082   unsigned MaxRegs, RegCountField, RegSaveIndex;
7083   CharUnits RegPadding;
7084   if (InFPRs) {
7085     MaxRegs = 4; // Maximum of 4 FPR arguments
7086     RegCountField = 1; // __fpr
7087     RegSaveIndex = 16; // save offset for f0
7088     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7089   } else {
7090     MaxRegs = 5; // Maximum of 5 GPR arguments
7091     RegCountField = 0; // __gpr
7092     RegSaveIndex = 2; // save offset for r2
7093     RegPadding = Padding; // values are passed in the low bits of a GPR
7094   }
7095 
7096   Address RegCountPtr =
7097       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7098   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7099   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7100   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7101                                                  "fits_in_regs");
7102 
7103   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7104   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7105   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7106   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7107 
7108   // Emit code to load the value if it was passed in registers.
7109   CGF.EmitBlock(InRegBlock);
7110 
7111   // Work out the address of an argument register.
7112   llvm::Value *ScaledRegCount =
7113     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7114   llvm::Value *RegBase =
7115     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7116                                       + RegPadding.getQuantity());
7117   llvm::Value *RegOffset =
7118     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7119   Address RegSaveAreaPtr =
7120       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7121   llvm::Value *RegSaveArea =
7122     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7123   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7124                                            "raw_reg_addr"),
7125                      PaddedSize);
7126   Address RegAddr =
7127     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7128 
7129   // Update the register count
7130   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7131   llvm::Value *NewRegCount =
7132     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7133   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7134   CGF.EmitBranch(ContBlock);
7135 
7136   // Emit code to load the value if it was passed in memory.
7137   CGF.EmitBlock(InMemBlock);
7138 
7139   // Work out the address of a stack argument.
7140   Address OverflowArgAreaPtr =
7141       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7142   Address OverflowArgArea =
7143     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7144             PaddedSize);
7145   Address RawMemAddr =
7146     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7147   Address MemAddr =
7148     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7149 
7150   // Update overflow_arg_area_ptr pointer
7151   llvm::Value *NewOverflowArgArea =
7152     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7153                           "overflow_arg_area");
7154   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7155   CGF.EmitBranch(ContBlock);
7156 
7157   // Return the appropriate result.
7158   CGF.EmitBlock(ContBlock);
7159   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7160                                  MemAddr, InMemBlock, "va_arg.addr");
7161 
7162   if (IsIndirect)
7163     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7164                       TyInfo.second);
7165 
7166   return ResAddr;
7167 }
7168 
7169 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7170   if (RetTy->isVoidType())
7171     return ABIArgInfo::getIgnore();
7172   if (isVectorArgumentType(RetTy))
7173     return ABIArgInfo::getDirect();
7174   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7175     return getNaturalAlignIndirect(RetTy);
7176   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7177                                                : ABIArgInfo::getDirect());
7178 }
7179 
7180 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7181   // Handle the generic C++ ABI.
7182   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7183     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7184 
7185   // Integers and enums are extended to full register width.
7186   if (isPromotableIntegerTypeForABI(Ty))
7187     return ABIArgInfo::getExtend(Ty);
7188 
7189   // Handle vector types and vector-like structure types.  Note that
7190   // as opposed to float-like structure types, we do not allow any
7191   // padding for vector-like structures, so verify the sizes match.
7192   uint64_t Size = getContext().getTypeSize(Ty);
7193   QualType SingleElementTy = GetSingleElementType(Ty);
7194   if (isVectorArgumentType(SingleElementTy) &&
7195       getContext().getTypeSize(SingleElementTy) == Size)
7196     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7197 
7198   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7199   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7200     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7201 
7202   // Handle small structures.
7203   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7204     // Structures with flexible arrays have variable length, so really
7205     // fail the size test above.
7206     const RecordDecl *RD = RT->getDecl();
7207     if (RD->hasFlexibleArrayMember())
7208       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7209 
7210     // The structure is passed as an unextended integer, a float, or a double.
7211     llvm::Type *PassTy;
7212     if (isFPArgumentType(SingleElementTy)) {
7213       assert(Size == 32 || Size == 64);
7214       if (Size == 32)
7215         PassTy = llvm::Type::getFloatTy(getVMContext());
7216       else
7217         PassTy = llvm::Type::getDoubleTy(getVMContext());
7218     } else
7219       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7220     return ABIArgInfo::getDirect(PassTy);
7221   }
7222 
7223   // Non-structure compounds are passed indirectly.
7224   if (isCompoundType(Ty))
7225     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7226 
7227   return ABIArgInfo::getDirect(nullptr);
7228 }
7229 
7230 //===----------------------------------------------------------------------===//
7231 // MSP430 ABI Implementation
7232 //===----------------------------------------------------------------------===//
7233 
7234 namespace {
7235 
7236 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7237 public:
7238   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7239       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
7240   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7241                            CodeGen::CodeGenModule &M) const override;
7242 };
7243 
7244 }
7245 
7246 void MSP430TargetCodeGenInfo::setTargetAttributes(
7247     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7248   if (GV->isDeclaration())
7249     return;
7250   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7251     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7252     if (!InterruptAttr)
7253       return;
7254 
7255     // Handle 'interrupt' attribute:
7256     llvm::Function *F = cast<llvm::Function>(GV);
7257 
7258     // Step 1: Set ISR calling convention.
7259     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7260 
7261     // Step 2: Add attributes goodness.
7262     F->addFnAttr(llvm::Attribute::NoInline);
7263     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7264   }
7265 }
7266 
7267 //===----------------------------------------------------------------------===//
7268 // MIPS ABI Implementation.  This works for both little-endian and
7269 // big-endian variants.
7270 //===----------------------------------------------------------------------===//
7271 
7272 namespace {
7273 class MipsABIInfo : public ABIInfo {
7274   bool IsO32;
7275   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7276   void CoerceToIntArgs(uint64_t TySize,
7277                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7278   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7279   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7280   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7281 public:
7282   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7283     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7284     StackAlignInBytes(IsO32 ? 8 : 16) {}
7285 
7286   ABIArgInfo classifyReturnType(QualType RetTy) const;
7287   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7288   void computeInfo(CGFunctionInfo &FI) const override;
7289   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7290                     QualType Ty) const override;
7291   ABIArgInfo extendType(QualType Ty) const;
7292 };
7293 
7294 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7295   unsigned SizeOfUnwindException;
7296 public:
7297   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7298       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7299         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7300 
7301   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7302     return 29;
7303   }
7304 
7305   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7306                            CodeGen::CodeGenModule &CGM) const override {
7307     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7308     if (!FD) return;
7309     llvm::Function *Fn = cast<llvm::Function>(GV);
7310 
7311     if (FD->hasAttr<MipsLongCallAttr>())
7312       Fn->addFnAttr("long-call");
7313     else if (FD->hasAttr<MipsShortCallAttr>())
7314       Fn->addFnAttr("short-call");
7315 
7316     // Other attributes do not have a meaning for declarations.
7317     if (GV->isDeclaration())
7318       return;
7319 
7320     if (FD->hasAttr<Mips16Attr>()) {
7321       Fn->addFnAttr("mips16");
7322     }
7323     else if (FD->hasAttr<NoMips16Attr>()) {
7324       Fn->addFnAttr("nomips16");
7325     }
7326 
7327     if (FD->hasAttr<MicroMipsAttr>())
7328       Fn->addFnAttr("micromips");
7329     else if (FD->hasAttr<NoMicroMipsAttr>())
7330       Fn->addFnAttr("nomicromips");
7331 
7332     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7333     if (!Attr)
7334       return;
7335 
7336     const char *Kind;
7337     switch (Attr->getInterrupt()) {
7338     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7339     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7340     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7341     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7342     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7343     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7344     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7345     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7346     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7347     }
7348 
7349     Fn->addFnAttr("interrupt", Kind);
7350 
7351   }
7352 
7353   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7354                                llvm::Value *Address) const override;
7355 
7356   unsigned getSizeOfUnwindException() const override {
7357     return SizeOfUnwindException;
7358   }
7359 };
7360 }
7361 
7362 void MipsABIInfo::CoerceToIntArgs(
7363     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7364   llvm::IntegerType *IntTy =
7365     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7366 
7367   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7368   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7369     ArgList.push_back(IntTy);
7370 
7371   // If necessary, add one more integer type to ArgList.
7372   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7373 
7374   if (R)
7375     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7376 }
7377 
7378 // In N32/64, an aligned double precision floating point field is passed in
7379 // a register.
7380 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7381   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7382 
7383   if (IsO32) {
7384     CoerceToIntArgs(TySize, ArgList);
7385     return llvm::StructType::get(getVMContext(), ArgList);
7386   }
7387 
7388   if (Ty->isComplexType())
7389     return CGT.ConvertType(Ty);
7390 
7391   const RecordType *RT = Ty->getAs<RecordType>();
7392 
7393   // Unions/vectors are passed in integer registers.
7394   if (!RT || !RT->isStructureOrClassType()) {
7395     CoerceToIntArgs(TySize, ArgList);
7396     return llvm::StructType::get(getVMContext(), ArgList);
7397   }
7398 
7399   const RecordDecl *RD = RT->getDecl();
7400   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7401   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7402 
7403   uint64_t LastOffset = 0;
7404   unsigned idx = 0;
7405   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7406 
7407   // Iterate over fields in the struct/class and check if there are any aligned
7408   // double fields.
7409   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7410        i != e; ++i, ++idx) {
7411     const QualType Ty = i->getType();
7412     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7413 
7414     if (!BT || BT->getKind() != BuiltinType::Double)
7415       continue;
7416 
7417     uint64_t Offset = Layout.getFieldOffset(idx);
7418     if (Offset % 64) // Ignore doubles that are not aligned.
7419       continue;
7420 
7421     // Add ((Offset - LastOffset) / 64) args of type i64.
7422     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7423       ArgList.push_back(I64);
7424 
7425     // Add double type.
7426     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7427     LastOffset = Offset + 64;
7428   }
7429 
7430   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7431   ArgList.append(IntArgList.begin(), IntArgList.end());
7432 
7433   return llvm::StructType::get(getVMContext(), ArgList);
7434 }
7435 
7436 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7437                                         uint64_t Offset) const {
7438   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7439     return nullptr;
7440 
7441   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7442 }
7443 
7444 ABIArgInfo
7445 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7446   Ty = useFirstFieldIfTransparentUnion(Ty);
7447 
7448   uint64_t OrigOffset = Offset;
7449   uint64_t TySize = getContext().getTypeSize(Ty);
7450   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7451 
7452   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7453                    (uint64_t)StackAlignInBytes);
7454   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7455   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7456 
7457   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7458     // Ignore empty aggregates.
7459     if (TySize == 0)
7460       return ABIArgInfo::getIgnore();
7461 
7462     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7463       Offset = OrigOffset + MinABIStackAlignInBytes;
7464       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7465     }
7466 
7467     // If we have reached here, aggregates are passed directly by coercing to
7468     // another structure type. Padding is inserted if the offset of the
7469     // aggregate is unaligned.
7470     ABIArgInfo ArgInfo =
7471         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7472                               getPaddingType(OrigOffset, CurrOffset));
7473     ArgInfo.setInReg(true);
7474     return ArgInfo;
7475   }
7476 
7477   // Treat an enum type as its underlying type.
7478   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7479     Ty = EnumTy->getDecl()->getIntegerType();
7480 
7481   // Make sure we pass indirectly things that are too large.
7482   if (const auto *EIT = Ty->getAs<ExtIntType>())
7483     if (EIT->getNumBits() > 128 ||
7484         (EIT->getNumBits() > 64 &&
7485          !getContext().getTargetInfo().hasInt128Type()))
7486       return getNaturalAlignIndirect(Ty);
7487 
7488   // All integral types are promoted to the GPR width.
7489   if (Ty->isIntegralOrEnumerationType())
7490     return extendType(Ty);
7491 
7492   return ABIArgInfo::getDirect(
7493       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7494 }
7495 
7496 llvm::Type*
7497 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7498   const RecordType *RT = RetTy->getAs<RecordType>();
7499   SmallVector<llvm::Type*, 8> RTList;
7500 
7501   if (RT && RT->isStructureOrClassType()) {
7502     const RecordDecl *RD = RT->getDecl();
7503     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7504     unsigned FieldCnt = Layout.getFieldCount();
7505 
7506     // N32/64 returns struct/classes in floating point registers if the
7507     // following conditions are met:
7508     // 1. The size of the struct/class is no larger than 128-bit.
7509     // 2. The struct/class has one or two fields all of which are floating
7510     //    point types.
7511     // 3. The offset of the first field is zero (this follows what gcc does).
7512     //
7513     // Any other composite results are returned in integer registers.
7514     //
7515     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7516       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7517       for (; b != e; ++b) {
7518         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7519 
7520         if (!BT || !BT->isFloatingPoint())
7521           break;
7522 
7523         RTList.push_back(CGT.ConvertType(b->getType()));
7524       }
7525 
7526       if (b == e)
7527         return llvm::StructType::get(getVMContext(), RTList,
7528                                      RD->hasAttr<PackedAttr>());
7529 
7530       RTList.clear();
7531     }
7532   }
7533 
7534   CoerceToIntArgs(Size, RTList);
7535   return llvm::StructType::get(getVMContext(), RTList);
7536 }
7537 
7538 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7539   uint64_t Size = getContext().getTypeSize(RetTy);
7540 
7541   if (RetTy->isVoidType())
7542     return ABIArgInfo::getIgnore();
7543 
7544   // O32 doesn't treat zero-sized structs differently from other structs.
7545   // However, N32/N64 ignores zero sized return values.
7546   if (!IsO32 && Size == 0)
7547     return ABIArgInfo::getIgnore();
7548 
7549   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7550     if (Size <= 128) {
7551       if (RetTy->isAnyComplexType())
7552         return ABIArgInfo::getDirect();
7553 
7554       // O32 returns integer vectors in registers and N32/N64 returns all small
7555       // aggregates in registers.
7556       if (!IsO32 ||
7557           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7558         ABIArgInfo ArgInfo =
7559             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7560         ArgInfo.setInReg(true);
7561         return ArgInfo;
7562       }
7563     }
7564 
7565     return getNaturalAlignIndirect(RetTy);
7566   }
7567 
7568   // Treat an enum type as its underlying type.
7569   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7570     RetTy = EnumTy->getDecl()->getIntegerType();
7571 
7572   // Make sure we pass indirectly things that are too large.
7573   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7574     if (EIT->getNumBits() > 128 ||
7575         (EIT->getNumBits() > 64 &&
7576          !getContext().getTargetInfo().hasInt128Type()))
7577       return getNaturalAlignIndirect(RetTy);
7578 
7579   if (isPromotableIntegerTypeForABI(RetTy))
7580     return ABIArgInfo::getExtend(RetTy);
7581 
7582   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7583       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7584     return ABIArgInfo::getSignExtend(RetTy);
7585 
7586   return ABIArgInfo::getDirect();
7587 }
7588 
7589 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7590   ABIArgInfo &RetInfo = FI.getReturnInfo();
7591   if (!getCXXABI().classifyReturnType(FI))
7592     RetInfo = classifyReturnType(FI.getReturnType());
7593 
7594   // Check if a pointer to an aggregate is passed as a hidden argument.
7595   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7596 
7597   for (auto &I : FI.arguments())
7598     I.info = classifyArgumentType(I.type, Offset);
7599 }
7600 
7601 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7602                                QualType OrigTy) const {
7603   QualType Ty = OrigTy;
7604 
7605   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7606   // Pointers are also promoted in the same way but this only matters for N32.
7607   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7608   unsigned PtrWidth = getTarget().getPointerWidth(0);
7609   bool DidPromote = false;
7610   if ((Ty->isIntegerType() &&
7611           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7612       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7613     DidPromote = true;
7614     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7615                                             Ty->isSignedIntegerType());
7616   }
7617 
7618   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7619 
7620   // The alignment of things in the argument area is never larger than
7621   // StackAlignInBytes.
7622   TyInfo.second =
7623     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7624 
7625   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7626   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7627 
7628   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7629                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7630 
7631 
7632   // If there was a promotion, "unpromote" into a temporary.
7633   // TODO: can we just use a pointer into a subset of the original slot?
7634   if (DidPromote) {
7635     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7636     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7637 
7638     // Truncate down to the right width.
7639     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7640                                                  : CGF.IntPtrTy);
7641     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7642     if (OrigTy->isPointerType())
7643       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7644 
7645     CGF.Builder.CreateStore(V, Temp);
7646     Addr = Temp;
7647   }
7648 
7649   return Addr;
7650 }
7651 
7652 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7653   int TySize = getContext().getTypeSize(Ty);
7654 
7655   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7656   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7657     return ABIArgInfo::getSignExtend(Ty);
7658 
7659   return ABIArgInfo::getExtend(Ty);
7660 }
7661 
7662 bool
7663 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7664                                                llvm::Value *Address) const {
7665   // This information comes from gcc's implementation, which seems to
7666   // as canonical as it gets.
7667 
7668   // Everything on MIPS is 4 bytes.  Double-precision FP registers
7669   // are aliased to pairs of single-precision FP registers.
7670   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7671 
7672   // 0-31 are the general purpose registers, $0 - $31.
7673   // 32-63 are the floating-point registers, $f0 - $f31.
7674   // 64 and 65 are the multiply/divide registers, $hi and $lo.
7675   // 66 is the (notional, I think) register for signal-handler return.
7676   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7677 
7678   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7679   // They are one bit wide and ignored here.
7680 
7681   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7682   // (coprocessor 1 is the FP unit)
7683   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7684   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7685   // 176-181 are the DSP accumulator registers.
7686   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7687   return false;
7688 }
7689 
7690 //===----------------------------------------------------------------------===//
7691 // AVR ABI Implementation.
7692 //===----------------------------------------------------------------------===//
7693 
7694 namespace {
7695 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7696 public:
7697   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7698       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
7699 
7700   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7701                            CodeGen::CodeGenModule &CGM) const override {
7702     if (GV->isDeclaration())
7703       return;
7704     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7705     if (!FD) return;
7706     auto *Fn = cast<llvm::Function>(GV);
7707 
7708     if (FD->getAttr<AVRInterruptAttr>())
7709       Fn->addFnAttr("interrupt");
7710 
7711     if (FD->getAttr<AVRSignalAttr>())
7712       Fn->addFnAttr("signal");
7713   }
7714 };
7715 }
7716 
7717 //===----------------------------------------------------------------------===//
7718 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
7719 // Currently subclassed only to implement custom OpenCL C function attribute
7720 // handling.
7721 //===----------------------------------------------------------------------===//
7722 
7723 namespace {
7724 
7725 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7726 public:
7727   TCETargetCodeGenInfo(CodeGenTypes &CGT)
7728     : DefaultTargetCodeGenInfo(CGT) {}
7729 
7730   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7731                            CodeGen::CodeGenModule &M) const override;
7732 };
7733 
7734 void TCETargetCodeGenInfo::setTargetAttributes(
7735     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7736   if (GV->isDeclaration())
7737     return;
7738   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7739   if (!FD) return;
7740 
7741   llvm::Function *F = cast<llvm::Function>(GV);
7742 
7743   if (M.getLangOpts().OpenCL) {
7744     if (FD->hasAttr<OpenCLKernelAttr>()) {
7745       // OpenCL C Kernel functions are not subject to inlining
7746       F->addFnAttr(llvm::Attribute::NoInline);
7747       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7748       if (Attr) {
7749         // Convert the reqd_work_group_size() attributes to metadata.
7750         llvm::LLVMContext &Context = F->getContext();
7751         llvm::NamedMDNode *OpenCLMetadata =
7752             M.getModule().getOrInsertNamedMetadata(
7753                 "opencl.kernel_wg_size_info");
7754 
7755         SmallVector<llvm::Metadata *, 5> Operands;
7756         Operands.push_back(llvm::ConstantAsMetadata::get(F));
7757 
7758         Operands.push_back(
7759             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7760                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7761         Operands.push_back(
7762             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7763                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7764         Operands.push_back(
7765             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7766                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7767 
7768         // Add a boolean constant operand for "required" (true) or "hint"
7769         // (false) for implementing the work_group_size_hint attr later.
7770         // Currently always true as the hint is not yet implemented.
7771         Operands.push_back(
7772             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7773         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7774       }
7775     }
7776   }
7777 }
7778 
7779 }
7780 
7781 //===----------------------------------------------------------------------===//
7782 // Hexagon ABI Implementation
7783 //===----------------------------------------------------------------------===//
7784 
7785 namespace {
7786 
7787 class HexagonABIInfo : public DefaultABIInfo {
7788 public:
7789   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7790 
7791 private:
7792   ABIArgInfo classifyReturnType(QualType RetTy) const;
7793   ABIArgInfo classifyArgumentType(QualType RetTy) const;
7794   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
7795 
7796   void computeInfo(CGFunctionInfo &FI) const override;
7797 
7798   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7799                     QualType Ty) const override;
7800   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
7801                               QualType Ty) const;
7802   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
7803                               QualType Ty) const;
7804   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
7805                                    QualType Ty) const;
7806 };
7807 
7808 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7809 public:
7810   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7811       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
7812 
7813   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7814     return 29;
7815   }
7816 
7817   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7818                            CodeGen::CodeGenModule &GCM) const override {
7819     if (GV->isDeclaration())
7820       return;
7821     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7822     if (!FD)
7823       return;
7824   }
7825 };
7826 
7827 } // namespace
7828 
7829 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7830   unsigned RegsLeft = 6;
7831   if (!getCXXABI().classifyReturnType(FI))
7832     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7833   for (auto &I : FI.arguments())
7834     I.info = classifyArgumentType(I.type, &RegsLeft);
7835 }
7836 
7837 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
7838   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
7839                        " through registers");
7840 
7841   if (*RegsLeft == 0)
7842     return false;
7843 
7844   if (Size <= 32) {
7845     (*RegsLeft)--;
7846     return true;
7847   }
7848 
7849   if (2 <= (*RegsLeft & (~1U))) {
7850     *RegsLeft = (*RegsLeft & (~1U)) - 2;
7851     return true;
7852   }
7853 
7854   // Next available register was r5 but candidate was greater than 32-bits so it
7855   // has to go on the stack. However we still consume r5
7856   if (*RegsLeft == 1)
7857     *RegsLeft = 0;
7858 
7859   return false;
7860 }
7861 
7862 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
7863                                                 unsigned *RegsLeft) const {
7864   if (!isAggregateTypeForABI(Ty)) {
7865     // Treat an enum type as its underlying type.
7866     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7867       Ty = EnumTy->getDecl()->getIntegerType();
7868 
7869     uint64_t Size = getContext().getTypeSize(Ty);
7870     if (Size <= 64)
7871       HexagonAdjustRegsLeft(Size, RegsLeft);
7872 
7873     if (Size > 64 && Ty->isExtIntType())
7874       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7875 
7876     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7877                                              : ABIArgInfo::getDirect();
7878   }
7879 
7880   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7881     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7882 
7883   // Ignore empty records.
7884   if (isEmptyRecord(getContext(), Ty, true))
7885     return ABIArgInfo::getIgnore();
7886 
7887   uint64_t Size = getContext().getTypeSize(Ty);
7888   unsigned Align = getContext().getTypeAlign(Ty);
7889 
7890   if (Size > 64)
7891     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7892 
7893   if (HexagonAdjustRegsLeft(Size, RegsLeft))
7894     Align = Size <= 32 ? 32 : 64;
7895   if (Size <= Align) {
7896     // Pass in the smallest viable integer type.
7897     if (!llvm::isPowerOf2_64(Size))
7898       Size = llvm::NextPowerOf2(Size);
7899     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
7900   }
7901   return DefaultABIInfo::classifyArgumentType(Ty);
7902 }
7903 
7904 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7905   if (RetTy->isVoidType())
7906     return ABIArgInfo::getIgnore();
7907 
7908   const TargetInfo &T = CGT.getTarget();
7909   uint64_t Size = getContext().getTypeSize(RetTy);
7910 
7911   if (RetTy->getAs<VectorType>()) {
7912     // HVX vectors are returned in vector registers or register pairs.
7913     if (T.hasFeature("hvx")) {
7914       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
7915       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
7916       if (Size == VecSize || Size == 2*VecSize)
7917         return ABIArgInfo::getDirectInReg();
7918     }
7919     // Large vector types should be returned via memory.
7920     if (Size > 64)
7921       return getNaturalAlignIndirect(RetTy);
7922   }
7923 
7924   if (!isAggregateTypeForABI(RetTy)) {
7925     // Treat an enum type as its underlying type.
7926     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7927       RetTy = EnumTy->getDecl()->getIntegerType();
7928 
7929     if (Size > 64 && RetTy->isExtIntType())
7930       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
7931 
7932     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7933                                                 : ABIArgInfo::getDirect();
7934   }
7935 
7936   if (isEmptyRecord(getContext(), RetTy, true))
7937     return ABIArgInfo::getIgnore();
7938 
7939   // Aggregates <= 8 bytes are returned in registers, other aggregates
7940   // are returned indirectly.
7941   if (Size <= 64) {
7942     // Return in the smallest viable integer type.
7943     if (!llvm::isPowerOf2_64(Size))
7944       Size = llvm::NextPowerOf2(Size);
7945     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
7946   }
7947   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7948 }
7949 
7950 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
7951                                             Address VAListAddr,
7952                                             QualType Ty) const {
7953   // Load the overflow area pointer.
7954   Address __overflow_area_pointer_p =
7955       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
7956   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
7957       __overflow_area_pointer_p, "__overflow_area_pointer");
7958 
7959   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
7960   if (Align > 4) {
7961     // Alignment should be a power of 2.
7962     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
7963 
7964     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
7965     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
7966 
7967     // Add offset to the current pointer to access the argument.
7968     __overflow_area_pointer =
7969         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
7970     llvm::Value *AsInt =
7971         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
7972 
7973     // Create a mask which should be "AND"ed
7974     // with (overflow_arg_area + align - 1)
7975     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
7976     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
7977         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
7978         "__overflow_area_pointer.align");
7979   }
7980 
7981   // Get the type of the argument from memory and bitcast
7982   // overflow area pointer to the argument type.
7983   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
7984   Address AddrTyped = CGF.Builder.CreateBitCast(
7985       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
7986       llvm::PointerType::getUnqual(PTy));
7987 
7988   // Round up to the minimum stack alignment for varargs which is 4 bytes.
7989   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
7990 
7991   __overflow_area_pointer = CGF.Builder.CreateGEP(
7992       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
7993       "__overflow_area_pointer.next");
7994   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
7995 
7996   return AddrTyped;
7997 }
7998 
7999 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8000                                             Address VAListAddr,
8001                                             QualType Ty) const {
8002   // FIXME: Need to handle alignment
8003   llvm::Type *BP = CGF.Int8PtrTy;
8004   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8005   CGBuilderTy &Builder = CGF.Builder;
8006   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8007   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8008   // Handle address alignment for type alignment > 32 bits
8009   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8010   if (TyAlign > 4) {
8011     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8012     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8013     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8014     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8015     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8016   }
8017   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8018   Address AddrTyped = Builder.CreateBitCast(
8019       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8020 
8021   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8022   llvm::Value *NextAddr = Builder.CreateGEP(
8023       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8024   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8025 
8026   return AddrTyped;
8027 }
8028 
8029 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8030                                                  Address VAListAddr,
8031                                                  QualType Ty) const {
8032   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8033 
8034   if (ArgSize > 8)
8035     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8036 
8037   // Here we have check if the argument is in register area or
8038   // in overflow area.
8039   // If the saved register area pointer + argsize rounded up to alignment >
8040   // saved register area end pointer, argument is in overflow area.
8041   unsigned RegsLeft = 6;
8042   Ty = CGF.getContext().getCanonicalType(Ty);
8043   (void)classifyArgumentType(Ty, &RegsLeft);
8044 
8045   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8046   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8047   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8048   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8049 
8050   // Get rounded size of the argument.GCC does not allow vararg of
8051   // size < 4 bytes. We follow the same logic here.
8052   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8053   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8054 
8055   // Argument may be in saved register area
8056   CGF.EmitBlock(MaybeRegBlock);
8057 
8058   // Load the current saved register area pointer.
8059   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8060       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8061   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8062       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8063 
8064   // Load the saved register area end pointer.
8065   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8066       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8067   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8068       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8069 
8070   // If the size of argument is > 4 bytes, check if the stack
8071   // location is aligned to 8 bytes
8072   if (ArgAlign > 4) {
8073 
8074     llvm::Value *__current_saved_reg_area_pointer_int =
8075         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8076                                    CGF.Int32Ty);
8077 
8078     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8079         __current_saved_reg_area_pointer_int,
8080         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8081         "align_current_saved_reg_area_pointer");
8082 
8083     __current_saved_reg_area_pointer_int =
8084         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8085                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8086                               "align_current_saved_reg_area_pointer");
8087 
8088     __current_saved_reg_area_pointer =
8089         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8090                                    __current_saved_reg_area_pointer->getType(),
8091                                    "align_current_saved_reg_area_pointer");
8092   }
8093 
8094   llvm::Value *__new_saved_reg_area_pointer =
8095       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8096                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8097                             "__new_saved_reg_area_pointer");
8098 
8099   llvm::Value *UsingStack = 0;
8100   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8101                                          __saved_reg_area_end_pointer);
8102 
8103   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8104 
8105   // Argument in saved register area
8106   // Implement the block where argument is in register saved area
8107   CGF.EmitBlock(InRegBlock);
8108 
8109   llvm::Type *PTy = CGF.ConvertType(Ty);
8110   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8111       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8112 
8113   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8114                           __current_saved_reg_area_pointer_p);
8115 
8116   CGF.EmitBranch(ContBlock);
8117 
8118   // Argument in overflow area
8119   // Implement the block where the argument is in overflow area.
8120   CGF.EmitBlock(OnStackBlock);
8121 
8122   // Load the overflow area pointer
8123   Address __overflow_area_pointer_p =
8124       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8125   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8126       __overflow_area_pointer_p, "__overflow_area_pointer");
8127 
8128   // Align the overflow area pointer according to the alignment of the argument
8129   if (ArgAlign > 4) {
8130     llvm::Value *__overflow_area_pointer_int =
8131         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8132 
8133     __overflow_area_pointer_int =
8134         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8135                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8136                               "align_overflow_area_pointer");
8137 
8138     __overflow_area_pointer_int =
8139         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8140                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8141                               "align_overflow_area_pointer");
8142 
8143     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8144         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8145         "align_overflow_area_pointer");
8146   }
8147 
8148   // Get the pointer for next argument in overflow area and store it
8149   // to overflow area pointer.
8150   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8151       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8152       "__overflow_area_pointer.next");
8153 
8154   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8155                           __overflow_area_pointer_p);
8156 
8157   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8158                           __current_saved_reg_area_pointer_p);
8159 
8160   // Bitcast the overflow area pointer to the type of argument.
8161   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8162   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8163       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8164 
8165   CGF.EmitBranch(ContBlock);
8166 
8167   // Get the correct pointer to load the variable argument
8168   // Implement the ContBlock
8169   CGF.EmitBlock(ContBlock);
8170 
8171   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8172   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8173   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8174   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8175 
8176   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8177 }
8178 
8179 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8180                                   QualType Ty) const {
8181 
8182   if (getTarget().getTriple().isMusl())
8183     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8184 
8185   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8186 }
8187 
8188 //===----------------------------------------------------------------------===//
8189 // Lanai ABI Implementation
8190 //===----------------------------------------------------------------------===//
8191 
8192 namespace {
8193 class LanaiABIInfo : public DefaultABIInfo {
8194 public:
8195   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8196 
8197   bool shouldUseInReg(QualType Ty, CCState &State) const;
8198 
8199   void computeInfo(CGFunctionInfo &FI) const override {
8200     CCState State(FI);
8201     // Lanai uses 4 registers to pass arguments unless the function has the
8202     // regparm attribute set.
8203     if (FI.getHasRegParm()) {
8204       State.FreeRegs = FI.getRegParm();
8205     } else {
8206       State.FreeRegs = 4;
8207     }
8208 
8209     if (!getCXXABI().classifyReturnType(FI))
8210       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8211     for (auto &I : FI.arguments())
8212       I.info = classifyArgumentType(I.type, State);
8213   }
8214 
8215   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8216   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8217 };
8218 } // end anonymous namespace
8219 
8220 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8221   unsigned Size = getContext().getTypeSize(Ty);
8222   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8223 
8224   if (SizeInRegs == 0)
8225     return false;
8226 
8227   if (SizeInRegs > State.FreeRegs) {
8228     State.FreeRegs = 0;
8229     return false;
8230   }
8231 
8232   State.FreeRegs -= SizeInRegs;
8233 
8234   return true;
8235 }
8236 
8237 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8238                                            CCState &State) const {
8239   if (!ByVal) {
8240     if (State.FreeRegs) {
8241       --State.FreeRegs; // Non-byval indirects just use one pointer.
8242       return getNaturalAlignIndirectInReg(Ty);
8243     }
8244     return getNaturalAlignIndirect(Ty, false);
8245   }
8246 
8247   // Compute the byval alignment.
8248   const unsigned MinABIStackAlignInBytes = 4;
8249   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8250   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8251                                  /*Realign=*/TypeAlign >
8252                                      MinABIStackAlignInBytes);
8253 }
8254 
8255 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8256                                               CCState &State) const {
8257   // Check with the C++ ABI first.
8258   const RecordType *RT = Ty->getAs<RecordType>();
8259   if (RT) {
8260     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8261     if (RAA == CGCXXABI::RAA_Indirect) {
8262       return getIndirectResult(Ty, /*ByVal=*/false, State);
8263     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8264       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
8265     }
8266   }
8267 
8268   if (isAggregateTypeForABI(Ty)) {
8269     // Structures with flexible arrays are always indirect.
8270     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8271       return getIndirectResult(Ty, /*ByVal=*/true, State);
8272 
8273     // Ignore empty structs/unions.
8274     if (isEmptyRecord(getContext(), Ty, true))
8275       return ABIArgInfo::getIgnore();
8276 
8277     llvm::LLVMContext &LLVMContext = getVMContext();
8278     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8279     if (SizeInRegs <= State.FreeRegs) {
8280       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8281       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8282       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8283       State.FreeRegs -= SizeInRegs;
8284       return ABIArgInfo::getDirectInReg(Result);
8285     } else {
8286       State.FreeRegs = 0;
8287     }
8288     return getIndirectResult(Ty, true, State);
8289   }
8290 
8291   // Treat an enum type as its underlying type.
8292   if (const auto *EnumTy = Ty->getAs<EnumType>())
8293     Ty = EnumTy->getDecl()->getIntegerType();
8294 
8295   bool InReg = shouldUseInReg(Ty, State);
8296 
8297   // Don't pass >64 bit integers in registers.
8298   if (const auto *EIT = Ty->getAs<ExtIntType>())
8299     if (EIT->getNumBits() > 64)
8300       return getIndirectResult(Ty, /*ByVal=*/true, State);
8301 
8302   if (isPromotableIntegerTypeForABI(Ty)) {
8303     if (InReg)
8304       return ABIArgInfo::getDirectInReg();
8305     return ABIArgInfo::getExtend(Ty);
8306   }
8307   if (InReg)
8308     return ABIArgInfo::getDirectInReg();
8309   return ABIArgInfo::getDirect();
8310 }
8311 
8312 namespace {
8313 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8314 public:
8315   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8316       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8317 };
8318 }
8319 
8320 //===----------------------------------------------------------------------===//
8321 // AMDGPU ABI Implementation
8322 //===----------------------------------------------------------------------===//
8323 
8324 namespace {
8325 
8326 class AMDGPUABIInfo final : public DefaultABIInfo {
8327 private:
8328   static const unsigned MaxNumRegsForArgsRet = 16;
8329 
8330   unsigned numRegsForType(QualType Ty) const;
8331 
8332   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8333   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8334                                          uint64_t Members) const override;
8335 
8336   // Coerce HIP pointer arguments from generic pointers to global ones.
8337   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8338                                        unsigned ToAS) const {
8339     // Structure types.
8340     if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
8341       SmallVector<llvm::Type *, 8> EltTys;
8342       bool Changed = false;
8343       for (auto T : STy->elements()) {
8344         auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8345         EltTys.push_back(NT);
8346         Changed |= (NT != T);
8347       }
8348       // Skip if there is no change in element types.
8349       if (!Changed)
8350         return STy;
8351       if (STy->hasName())
8352         return llvm::StructType::create(
8353             EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
8354       return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
8355     }
8356     // Array types.
8357     if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
8358       auto T = ATy->getElementType();
8359       auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8360       // Skip if there is no change in that element type.
8361       if (NT == T)
8362         return ATy;
8363       return llvm::ArrayType::get(NT, ATy->getNumElements());
8364     }
8365     // Single value types.
8366     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8367       return llvm::PointerType::get(
8368           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8369     return Ty;
8370   }
8371 
8372 public:
8373   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8374     DefaultABIInfo(CGT) {}
8375 
8376   ABIArgInfo classifyReturnType(QualType RetTy) const;
8377   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8378   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8379 
8380   void computeInfo(CGFunctionInfo &FI) const override;
8381   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8382                     QualType Ty) const override;
8383 };
8384 
8385 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8386   return true;
8387 }
8388 
8389 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8390   const Type *Base, uint64_t Members) const {
8391   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8392 
8393   // Homogeneous Aggregates may occupy at most 16 registers.
8394   return Members * NumRegs <= MaxNumRegsForArgsRet;
8395 }
8396 
8397 /// Estimate number of registers the type will use when passed in registers.
8398 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8399   unsigned NumRegs = 0;
8400 
8401   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8402     // Compute from the number of elements. The reported size is based on the
8403     // in-memory size, which includes the padding 4th element for 3-vectors.
8404     QualType EltTy = VT->getElementType();
8405     unsigned EltSize = getContext().getTypeSize(EltTy);
8406 
8407     // 16-bit element vectors should be passed as packed.
8408     if (EltSize == 16)
8409       return (VT->getNumElements() + 1) / 2;
8410 
8411     unsigned EltNumRegs = (EltSize + 31) / 32;
8412     return EltNumRegs * VT->getNumElements();
8413   }
8414 
8415   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8416     const RecordDecl *RD = RT->getDecl();
8417     assert(!RD->hasFlexibleArrayMember());
8418 
8419     for (const FieldDecl *Field : RD->fields()) {
8420       QualType FieldTy = Field->getType();
8421       NumRegs += numRegsForType(FieldTy);
8422     }
8423 
8424     return NumRegs;
8425   }
8426 
8427   return (getContext().getTypeSize(Ty) + 31) / 32;
8428 }
8429 
8430 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8431   llvm::CallingConv::ID CC = FI.getCallingConvention();
8432 
8433   if (!getCXXABI().classifyReturnType(FI))
8434     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8435 
8436   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8437   for (auto &Arg : FI.arguments()) {
8438     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8439       Arg.info = classifyKernelArgumentType(Arg.type);
8440     } else {
8441       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8442     }
8443   }
8444 }
8445 
8446 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8447                                  QualType Ty) const {
8448   llvm_unreachable("AMDGPU does not support varargs");
8449 }
8450 
8451 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8452   if (isAggregateTypeForABI(RetTy)) {
8453     // Records with non-trivial destructors/copy-constructors should not be
8454     // returned by value.
8455     if (!getRecordArgABI(RetTy, getCXXABI())) {
8456       // Ignore empty structs/unions.
8457       if (isEmptyRecord(getContext(), RetTy, true))
8458         return ABIArgInfo::getIgnore();
8459 
8460       // Lower single-element structs to just return a regular value.
8461       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8462         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8463 
8464       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8465         const RecordDecl *RD = RT->getDecl();
8466         if (RD->hasFlexibleArrayMember())
8467           return DefaultABIInfo::classifyReturnType(RetTy);
8468       }
8469 
8470       // Pack aggregates <= 4 bytes into single VGPR or pair.
8471       uint64_t Size = getContext().getTypeSize(RetTy);
8472       if (Size <= 16)
8473         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8474 
8475       if (Size <= 32)
8476         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8477 
8478       if (Size <= 64) {
8479         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8480         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8481       }
8482 
8483       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8484         return ABIArgInfo::getDirect();
8485     }
8486   }
8487 
8488   // Otherwise just do the default thing.
8489   return DefaultABIInfo::classifyReturnType(RetTy);
8490 }
8491 
8492 /// For kernels all parameters are really passed in a special buffer. It doesn't
8493 /// make sense to pass anything byval, so everything must be direct.
8494 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8495   Ty = useFirstFieldIfTransparentUnion(Ty);
8496 
8497   // TODO: Can we omit empty structs?
8498 
8499   llvm::Type *LTy = nullptr;
8500   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8501     LTy = CGT.ConvertType(QualType(SeltTy, 0));
8502 
8503   if (getContext().getLangOpts().HIP) {
8504     if (!LTy)
8505       LTy = CGT.ConvertType(Ty);
8506     LTy = coerceKernelArgumentType(
8507         LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8508         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8509   }
8510 
8511   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8512   // individual elements, which confuses the Clover OpenCL backend; therefore we
8513   // have to set it to false here. Other args of getDirect() are just defaults.
8514   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8515 }
8516 
8517 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8518                                                unsigned &NumRegsLeft) const {
8519   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8520 
8521   Ty = useFirstFieldIfTransparentUnion(Ty);
8522 
8523   if (isAggregateTypeForABI(Ty)) {
8524     // Records with non-trivial destructors/copy-constructors should not be
8525     // passed by value.
8526     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8527       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8528 
8529     // Ignore empty structs/unions.
8530     if (isEmptyRecord(getContext(), Ty, true))
8531       return ABIArgInfo::getIgnore();
8532 
8533     // Lower single-element structs to just pass a regular value. TODO: We
8534     // could do reasonable-size multiple-element structs too, using getExpand(),
8535     // though watch out for things like bitfields.
8536     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8537       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8538 
8539     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8540       const RecordDecl *RD = RT->getDecl();
8541       if (RD->hasFlexibleArrayMember())
8542         return DefaultABIInfo::classifyArgumentType(Ty);
8543     }
8544 
8545     // Pack aggregates <= 8 bytes into single VGPR or pair.
8546     uint64_t Size = getContext().getTypeSize(Ty);
8547     if (Size <= 64) {
8548       unsigned NumRegs = (Size + 31) / 32;
8549       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8550 
8551       if (Size <= 16)
8552         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8553 
8554       if (Size <= 32)
8555         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8556 
8557       // XXX: Should this be i64 instead, and should the limit increase?
8558       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8559       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8560     }
8561 
8562     if (NumRegsLeft > 0) {
8563       unsigned NumRegs = numRegsForType(Ty);
8564       if (NumRegsLeft >= NumRegs) {
8565         NumRegsLeft -= NumRegs;
8566         return ABIArgInfo::getDirect();
8567       }
8568     }
8569   }
8570 
8571   // Otherwise just do the default thing.
8572   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8573   if (!ArgInfo.isIndirect()) {
8574     unsigned NumRegs = numRegsForType(Ty);
8575     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8576   }
8577 
8578   return ArgInfo;
8579 }
8580 
8581 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8582 public:
8583   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8584       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8585   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8586                            CodeGen::CodeGenModule &M) const override;
8587   unsigned getOpenCLKernelCallingConv() const override;
8588 
8589   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8590       llvm::PointerType *T, QualType QT) const override;
8591 
8592   LangAS getASTAllocaAddressSpace() const override {
8593     return getLangASFromTargetAS(
8594         getABIInfo().getDataLayout().getAllocaAddrSpace());
8595   }
8596   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8597                                   const VarDecl *D) const override;
8598   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8599                                          SyncScope Scope,
8600                                          llvm::AtomicOrdering Ordering,
8601                                          llvm::LLVMContext &Ctx) const override;
8602   llvm::Function *
8603   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8604                             llvm::Function *BlockInvokeFunc,
8605                             llvm::Value *BlockLiteral) const override;
8606   bool shouldEmitStaticExternCAliases() const override;
8607   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8608 };
8609 }
8610 
8611 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8612                                               llvm::GlobalValue *GV) {
8613   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8614     return false;
8615 
8616   return D->hasAttr<OpenCLKernelAttr>() ||
8617          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8618          (isa<VarDecl>(D) &&
8619           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8620            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8621            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8622 }
8623 
8624 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8625     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8626   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8627     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8628     GV->setDSOLocal(true);
8629   }
8630 
8631   if (GV->isDeclaration())
8632     return;
8633   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8634   if (!FD)
8635     return;
8636 
8637   llvm::Function *F = cast<llvm::Function>(GV);
8638 
8639   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8640     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8641 
8642 
8643   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8644                               FD->hasAttr<OpenCLKernelAttr>();
8645   const bool IsHIPKernel = M.getLangOpts().HIP &&
8646                            FD->hasAttr<CUDAGlobalAttr>();
8647   if ((IsOpenCLKernel || IsHIPKernel) &&
8648       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8649     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8650 
8651   if (IsHIPKernel)
8652     F->addFnAttr("uniform-work-group-size", "true");
8653 
8654 
8655   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8656   if (ReqdWGS || FlatWGS) {
8657     unsigned Min = 0;
8658     unsigned Max = 0;
8659     if (FlatWGS) {
8660       Min = FlatWGS->getMin()
8661                 ->EvaluateKnownConstInt(M.getContext())
8662                 .getExtValue();
8663       Max = FlatWGS->getMax()
8664                 ->EvaluateKnownConstInt(M.getContext())
8665                 .getExtValue();
8666     }
8667     if (ReqdWGS && Min == 0 && Max == 0)
8668       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8669 
8670     if (Min != 0) {
8671       assert(Min <= Max && "Min must be less than or equal Max");
8672 
8673       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8674       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8675     } else
8676       assert(Max == 0 && "Max must be zero");
8677   } else if (IsOpenCLKernel || IsHIPKernel) {
8678     // By default, restrict the maximum size to a value specified by
8679     // --gpu-max-threads-per-block=n or its default value.
8680     std::string AttrVal =
8681         std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
8682     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8683   }
8684 
8685   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
8686     unsigned Min =
8687         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8688     unsigned Max = Attr->getMax() ? Attr->getMax()
8689                                         ->EvaluateKnownConstInt(M.getContext())
8690                                         .getExtValue()
8691                                   : 0;
8692 
8693     if (Min != 0) {
8694       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8695 
8696       std::string AttrVal = llvm::utostr(Min);
8697       if (Max != 0)
8698         AttrVal = AttrVal + "," + llvm::utostr(Max);
8699       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
8700     } else
8701       assert(Max == 0 && "Max must be zero");
8702   }
8703 
8704   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
8705     unsigned NumSGPR = Attr->getNumSGPR();
8706 
8707     if (NumSGPR != 0)
8708       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
8709   }
8710 
8711   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
8712     uint32_t NumVGPR = Attr->getNumVGPR();
8713 
8714     if (NumVGPR != 0)
8715       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
8716   }
8717 }
8718 
8719 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8720   return llvm::CallingConv::AMDGPU_KERNEL;
8721 }
8722 
8723 // Currently LLVM assumes null pointers always have value 0,
8724 // which results in incorrectly transformed IR. Therefore, instead of
8725 // emitting null pointers in private and local address spaces, a null
8726 // pointer in generic address space is emitted which is casted to a
8727 // pointer in local or private address space.
8728 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
8729     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
8730     QualType QT) const {
8731   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
8732     return llvm::ConstantPointerNull::get(PT);
8733 
8734   auto &Ctx = CGM.getContext();
8735   auto NPT = llvm::PointerType::get(PT->getElementType(),
8736       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8737   return llvm::ConstantExpr::getAddrSpaceCast(
8738       llvm::ConstantPointerNull::get(NPT), PT);
8739 }
8740 
8741 LangAS
8742 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8743                                                   const VarDecl *D) const {
8744   assert(!CGM.getLangOpts().OpenCL &&
8745          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8746          "Address space agnostic languages only");
8747   LangAS DefaultGlobalAS = getLangASFromTargetAS(
8748       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
8749   if (!D)
8750     return DefaultGlobalAS;
8751 
8752   LangAS AddrSpace = D->getType().getAddressSpace();
8753   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
8754   if (AddrSpace != LangAS::Default)
8755     return AddrSpace;
8756 
8757   if (CGM.isTypeConstant(D->getType(), false)) {
8758     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8759       return ConstAS.getValue();
8760   }
8761   return DefaultGlobalAS;
8762 }
8763 
8764 llvm::SyncScope::ID
8765 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8766                                             SyncScope Scope,
8767                                             llvm::AtomicOrdering Ordering,
8768                                             llvm::LLVMContext &Ctx) const {
8769   std::string Name;
8770   switch (Scope) {
8771   case SyncScope::OpenCLWorkGroup:
8772     Name = "workgroup";
8773     break;
8774   case SyncScope::OpenCLDevice:
8775     Name = "agent";
8776     break;
8777   case SyncScope::OpenCLAllSVMDevices:
8778     Name = "";
8779     break;
8780   case SyncScope::OpenCLSubGroup:
8781     Name = "wavefront";
8782   }
8783 
8784   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8785     if (!Name.empty())
8786       Name = Twine(Twine(Name) + Twine("-")).str();
8787 
8788     Name = Twine(Twine(Name) + Twine("one-as")).str();
8789   }
8790 
8791   return Ctx.getOrInsertSyncScopeID(Name);
8792 }
8793 
8794 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8795   return false;
8796 }
8797 
8798 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
8799     const FunctionType *&FT) const {
8800   FT = getABIInfo().getContext().adjustFunctionType(
8801       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
8802 }
8803 
8804 //===----------------------------------------------------------------------===//
8805 // SPARC v8 ABI Implementation.
8806 // Based on the SPARC Compliance Definition version 2.4.1.
8807 //
8808 // Ensures that complex values are passed in registers.
8809 //
8810 namespace {
8811 class SparcV8ABIInfo : public DefaultABIInfo {
8812 public:
8813   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8814 
8815 private:
8816   ABIArgInfo classifyReturnType(QualType RetTy) const;
8817   void computeInfo(CGFunctionInfo &FI) const override;
8818 };
8819 } // end anonymous namespace
8820 
8821 
8822 ABIArgInfo
8823 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8824   if (Ty->isAnyComplexType()) {
8825     return ABIArgInfo::getDirect();
8826   }
8827   else {
8828     return DefaultABIInfo::classifyReturnType(Ty);
8829   }
8830 }
8831 
8832 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8833 
8834   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8835   for (auto &Arg : FI.arguments())
8836     Arg.info = classifyArgumentType(Arg.type);
8837 }
8838 
8839 namespace {
8840 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8841 public:
8842   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8843       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
8844 };
8845 } // end anonymous namespace
8846 
8847 //===----------------------------------------------------------------------===//
8848 // SPARC v9 ABI Implementation.
8849 // Based on the SPARC Compliance Definition version 2.4.1.
8850 //
8851 // Function arguments a mapped to a nominal "parameter array" and promoted to
8852 // registers depending on their type. Each argument occupies 8 or 16 bytes in
8853 // the array, structs larger than 16 bytes are passed indirectly.
8854 //
8855 // One case requires special care:
8856 //
8857 //   struct mixed {
8858 //     int i;
8859 //     float f;
8860 //   };
8861 //
8862 // When a struct mixed is passed by value, it only occupies 8 bytes in the
8863 // parameter array, but the int is passed in an integer register, and the float
8864 // is passed in a floating point register. This is represented as two arguments
8865 // with the LLVM IR inreg attribute:
8866 //
8867 //   declare void f(i32 inreg %i, float inreg %f)
8868 //
8869 // The code generator will only allocate 4 bytes from the parameter array for
8870 // the inreg arguments. All other arguments are allocated a multiple of 8
8871 // bytes.
8872 //
8873 namespace {
8874 class SparcV9ABIInfo : public ABIInfo {
8875 public:
8876   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8877 
8878 private:
8879   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
8880   void computeInfo(CGFunctionInfo &FI) const override;
8881   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8882                     QualType Ty) const override;
8883 
8884   // Coercion type builder for structs passed in registers. The coercion type
8885   // serves two purposes:
8886   //
8887   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8888   //    in registers.
8889   // 2. Expose aligned floating point elements as first-level elements, so the
8890   //    code generator knows to pass them in floating point registers.
8891   //
8892   // We also compute the InReg flag which indicates that the struct contains
8893   // aligned 32-bit floats.
8894   //
8895   struct CoerceBuilder {
8896     llvm::LLVMContext &Context;
8897     const llvm::DataLayout &DL;
8898     SmallVector<llvm::Type*, 8> Elems;
8899     uint64_t Size;
8900     bool InReg;
8901 
8902     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8903       : Context(c), DL(dl), Size(0), InReg(false) {}
8904 
8905     // Pad Elems with integers until Size is ToSize.
8906     void pad(uint64_t ToSize) {
8907       assert(ToSize >= Size && "Cannot remove elements");
8908       if (ToSize == Size)
8909         return;
8910 
8911       // Finish the current 64-bit word.
8912       uint64_t Aligned = llvm::alignTo(Size, 64);
8913       if (Aligned > Size && Aligned <= ToSize) {
8914         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8915         Size = Aligned;
8916       }
8917 
8918       // Add whole 64-bit words.
8919       while (Size + 64 <= ToSize) {
8920         Elems.push_back(llvm::Type::getInt64Ty(Context));
8921         Size += 64;
8922       }
8923 
8924       // Final in-word padding.
8925       if (Size < ToSize) {
8926         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8927         Size = ToSize;
8928       }
8929     }
8930 
8931     // Add a floating point element at Offset.
8932     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8933       // Unaligned floats are treated as integers.
8934       if (Offset % Bits)
8935         return;
8936       // The InReg flag is only required if there are any floats < 64 bits.
8937       if (Bits < 64)
8938         InReg = true;
8939       pad(Offset);
8940       Elems.push_back(Ty);
8941       Size = Offset + Bits;
8942     }
8943 
8944     // Add a struct type to the coercion type, starting at Offset (in bits).
8945     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8946       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8947       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8948         llvm::Type *ElemTy = StrTy->getElementType(i);
8949         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8950         switch (ElemTy->getTypeID()) {
8951         case llvm::Type::StructTyID:
8952           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8953           break;
8954         case llvm::Type::FloatTyID:
8955           addFloat(ElemOffset, ElemTy, 32);
8956           break;
8957         case llvm::Type::DoubleTyID:
8958           addFloat(ElemOffset, ElemTy, 64);
8959           break;
8960         case llvm::Type::FP128TyID:
8961           addFloat(ElemOffset, ElemTy, 128);
8962           break;
8963         case llvm::Type::PointerTyID:
8964           if (ElemOffset % 64 == 0) {
8965             pad(ElemOffset);
8966             Elems.push_back(ElemTy);
8967             Size += 64;
8968           }
8969           break;
8970         default:
8971           break;
8972         }
8973       }
8974     }
8975 
8976     // Check if Ty is a usable substitute for the coercion type.
8977     bool isUsableType(llvm::StructType *Ty) const {
8978       return llvm::makeArrayRef(Elems) == Ty->elements();
8979     }
8980 
8981     // Get the coercion type as a literal struct type.
8982     llvm::Type *getType() const {
8983       if (Elems.size() == 1)
8984         return Elems.front();
8985       else
8986         return llvm::StructType::get(Context, Elems);
8987     }
8988   };
8989 };
8990 } // end anonymous namespace
8991 
8992 ABIArgInfo
8993 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8994   if (Ty->isVoidType())
8995     return ABIArgInfo::getIgnore();
8996 
8997   uint64_t Size = getContext().getTypeSize(Ty);
8998 
8999   // Anything too big to fit in registers is passed with an explicit indirect
9000   // pointer / sret pointer.
9001   if (Size > SizeLimit)
9002     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9003 
9004   // Treat an enum type as its underlying type.
9005   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9006     Ty = EnumTy->getDecl()->getIntegerType();
9007 
9008   // Integer types smaller than a register are extended.
9009   if (Size < 64 && Ty->isIntegerType())
9010     return ABIArgInfo::getExtend(Ty);
9011 
9012   if (const auto *EIT = Ty->getAs<ExtIntType>())
9013     if (EIT->getNumBits() < 64)
9014       return ABIArgInfo::getExtend(Ty);
9015 
9016   // Other non-aggregates go in registers.
9017   if (!isAggregateTypeForABI(Ty))
9018     return ABIArgInfo::getDirect();
9019 
9020   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9021   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9022   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9023     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9024 
9025   // This is a small aggregate type that should be passed in registers.
9026   // Build a coercion type from the LLVM struct type.
9027   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9028   if (!StrTy)
9029     return ABIArgInfo::getDirect();
9030 
9031   CoerceBuilder CB(getVMContext(), getDataLayout());
9032   CB.addStruct(0, StrTy);
9033   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9034 
9035   // Try to use the original type for coercion.
9036   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9037 
9038   if (CB.InReg)
9039     return ABIArgInfo::getDirectInReg(CoerceTy);
9040   else
9041     return ABIArgInfo::getDirect(CoerceTy);
9042 }
9043 
9044 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9045                                   QualType Ty) const {
9046   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9047   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9048   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9049     AI.setCoerceToType(ArgTy);
9050 
9051   CharUnits SlotSize = CharUnits::fromQuantity(8);
9052 
9053   CGBuilderTy &Builder = CGF.Builder;
9054   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9055   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9056 
9057   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9058 
9059   Address ArgAddr = Address::invalid();
9060   CharUnits Stride;
9061   switch (AI.getKind()) {
9062   case ABIArgInfo::Expand:
9063   case ABIArgInfo::CoerceAndExpand:
9064   case ABIArgInfo::InAlloca:
9065     llvm_unreachable("Unsupported ABI kind for va_arg");
9066 
9067   case ABIArgInfo::Extend: {
9068     Stride = SlotSize;
9069     CharUnits Offset = SlotSize - TypeInfo.first;
9070     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9071     break;
9072   }
9073 
9074   case ABIArgInfo::Direct: {
9075     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9076     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9077     ArgAddr = Addr;
9078     break;
9079   }
9080 
9081   case ABIArgInfo::Indirect:
9082     Stride = SlotSize;
9083     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9084     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9085                       TypeInfo.second);
9086     break;
9087 
9088   case ABIArgInfo::Ignore:
9089     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
9090   }
9091 
9092   // Update VAList.
9093   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9094   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9095 
9096   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9097 }
9098 
9099 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9100   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9101   for (auto &I : FI.arguments())
9102     I.info = classifyType(I.type, 16 * 8);
9103 }
9104 
9105 namespace {
9106 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9107 public:
9108   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9109       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9110 
9111   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9112     return 14;
9113   }
9114 
9115   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9116                                llvm::Value *Address) const override;
9117 };
9118 } // end anonymous namespace
9119 
9120 bool
9121 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9122                                                 llvm::Value *Address) const {
9123   // This is calculated from the LLVM and GCC tables and verified
9124   // against gcc output.  AFAIK all ABIs use the same encoding.
9125 
9126   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9127 
9128   llvm::IntegerType *i8 = CGF.Int8Ty;
9129   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9130   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9131 
9132   // 0-31: the 8-byte general-purpose registers
9133   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9134 
9135   // 32-63: f0-31, the 4-byte floating-point registers
9136   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9137 
9138   //   Y   = 64
9139   //   PSR = 65
9140   //   WIM = 66
9141   //   TBR = 67
9142   //   PC  = 68
9143   //   NPC = 69
9144   //   FSR = 70
9145   //   CSR = 71
9146   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9147 
9148   // 72-87: d0-15, the 8-byte floating-point registers
9149   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9150 
9151   return false;
9152 }
9153 
9154 // ARC ABI implementation.
9155 namespace {
9156 
9157 class ARCABIInfo : public DefaultABIInfo {
9158 public:
9159   using DefaultABIInfo::DefaultABIInfo;
9160 
9161 private:
9162   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9163                     QualType Ty) const override;
9164 
9165   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9166     if (!State.FreeRegs)
9167       return;
9168     if (Info.isIndirect() && Info.getInReg())
9169       State.FreeRegs--;
9170     else if (Info.isDirect() && Info.getInReg()) {
9171       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9172       if (sz < State.FreeRegs)
9173         State.FreeRegs -= sz;
9174       else
9175         State.FreeRegs = 0;
9176     }
9177   }
9178 
9179   void computeInfo(CGFunctionInfo &FI) const override {
9180     CCState State(FI);
9181     // ARC uses 8 registers to pass arguments.
9182     State.FreeRegs = 8;
9183 
9184     if (!getCXXABI().classifyReturnType(FI))
9185       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9186     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9187     for (auto &I : FI.arguments()) {
9188       I.info = classifyArgumentType(I.type, State.FreeRegs);
9189       updateState(I.info, I.type, State);
9190     }
9191   }
9192 
9193   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9194   ABIArgInfo getIndirectByValue(QualType Ty) const;
9195   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9196   ABIArgInfo classifyReturnType(QualType RetTy) const;
9197 };
9198 
9199 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9200 public:
9201   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9202       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9203 };
9204 
9205 
9206 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9207   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9208                        getNaturalAlignIndirect(Ty, false);
9209 }
9210 
9211 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9212   // Compute the byval alignment.
9213   const unsigned MinABIStackAlignInBytes = 4;
9214   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9215   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9216                                  TypeAlign > MinABIStackAlignInBytes);
9217 }
9218 
9219 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9220                               QualType Ty) const {
9221   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9222                           getContext().getTypeInfoInChars(Ty),
9223                           CharUnits::fromQuantity(4), true);
9224 }
9225 
9226 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9227                                             uint8_t FreeRegs) const {
9228   // Handle the generic C++ ABI.
9229   const RecordType *RT = Ty->getAs<RecordType>();
9230   if (RT) {
9231     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9232     if (RAA == CGCXXABI::RAA_Indirect)
9233       return getIndirectByRef(Ty, FreeRegs > 0);
9234 
9235     if (RAA == CGCXXABI::RAA_DirectInMemory)
9236       return getIndirectByValue(Ty);
9237   }
9238 
9239   // Treat an enum type as its underlying type.
9240   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9241     Ty = EnumTy->getDecl()->getIntegerType();
9242 
9243   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9244 
9245   if (isAggregateTypeForABI(Ty)) {
9246     // Structures with flexible arrays are always indirect.
9247     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9248       return getIndirectByValue(Ty);
9249 
9250     // Ignore empty structs/unions.
9251     if (isEmptyRecord(getContext(), Ty, true))
9252       return ABIArgInfo::getIgnore();
9253 
9254     llvm::LLVMContext &LLVMContext = getVMContext();
9255 
9256     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9257     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9258     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9259 
9260     return FreeRegs >= SizeInRegs ?
9261         ABIArgInfo::getDirectInReg(Result) :
9262         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9263   }
9264 
9265   if (const auto *EIT = Ty->getAs<ExtIntType>())
9266     if (EIT->getNumBits() > 64)
9267       return getIndirectByValue(Ty);
9268 
9269   return isPromotableIntegerTypeForABI(Ty)
9270              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9271                                        : ABIArgInfo::getExtend(Ty))
9272              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9273                                        : ABIArgInfo::getDirect());
9274 }
9275 
9276 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9277   if (RetTy->isAnyComplexType())
9278     return ABIArgInfo::getDirectInReg();
9279 
9280   // Arguments of size > 4 registers are indirect.
9281   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9282   if (RetSize > 4)
9283     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9284 
9285   return DefaultABIInfo::classifyReturnType(RetTy);
9286 }
9287 
9288 } // End anonymous namespace.
9289 
9290 //===----------------------------------------------------------------------===//
9291 // XCore ABI Implementation
9292 //===----------------------------------------------------------------------===//
9293 
9294 namespace {
9295 
9296 /// A SmallStringEnc instance is used to build up the TypeString by passing
9297 /// it by reference between functions that append to it.
9298 typedef llvm::SmallString<128> SmallStringEnc;
9299 
9300 /// TypeStringCache caches the meta encodings of Types.
9301 ///
9302 /// The reason for caching TypeStrings is two fold:
9303 ///   1. To cache a type's encoding for later uses;
9304 ///   2. As a means to break recursive member type inclusion.
9305 ///
9306 /// A cache Entry can have a Status of:
9307 ///   NonRecursive:   The type encoding is not recursive;
9308 ///   Recursive:      The type encoding is recursive;
9309 ///   Incomplete:     An incomplete TypeString;
9310 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9311 ///                   Recursive type encoding.
9312 ///
9313 /// A NonRecursive entry will have all of its sub-members expanded as fully
9314 /// as possible. Whilst it may contain types which are recursive, the type
9315 /// itself is not recursive and thus its encoding may be safely used whenever
9316 /// the type is encountered.
9317 ///
9318 /// A Recursive entry will have all of its sub-members expanded as fully as
9319 /// possible. The type itself is recursive and it may contain other types which
9320 /// are recursive. The Recursive encoding must not be used during the expansion
9321 /// of a recursive type's recursive branch. For simplicity the code uses
9322 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9323 ///
9324 /// An Incomplete entry is always a RecordType and only encodes its
9325 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9326 /// are placed into the cache during type expansion as a means to identify and
9327 /// handle recursive inclusion of types as sub-members. If there is recursion
9328 /// the entry becomes IncompleteUsed.
9329 ///
9330 /// During the expansion of a RecordType's members:
9331 ///
9332 ///   If the cache contains a NonRecursive encoding for the member type, the
9333 ///   cached encoding is used;
9334 ///
9335 ///   If the cache contains a Recursive encoding for the member type, the
9336 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9337 ///
9338 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9339 ///   cache to break potential recursive inclusion of itself as a sub-member;
9340 ///
9341 ///   Once a member RecordType has been expanded, its temporary incomplete
9342 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9343 ///   it is swapped back in;
9344 ///
9345 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9346 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9347 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9348 ///
9349 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9350 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9351 ///   Else the member is part of a recursive type and thus the recursion has
9352 ///   been exited too soon for the encoding to be correct for the member.
9353 ///
9354 class TypeStringCache {
9355   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9356   struct Entry {
9357     std::string Str;     // The encoded TypeString for the type.
9358     enum Status State;   // Information about the encoding in 'Str'.
9359     std::string Swapped; // A temporary place holder for a Recursive encoding
9360                          // during the expansion of RecordType's members.
9361   };
9362   std::map<const IdentifierInfo *, struct Entry> Map;
9363   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9364   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9365 public:
9366   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9367   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9368   bool removeIncomplete(const IdentifierInfo *ID);
9369   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9370                      bool IsRecursive);
9371   StringRef lookupStr(const IdentifierInfo *ID);
9372 };
9373 
9374 /// TypeString encodings for enum & union fields must be order.
9375 /// FieldEncoding is a helper for this ordering process.
9376 class FieldEncoding {
9377   bool HasName;
9378   std::string Enc;
9379 public:
9380   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9381   StringRef str() { return Enc; }
9382   bool operator<(const FieldEncoding &rhs) const {
9383     if (HasName != rhs.HasName) return HasName;
9384     return Enc < rhs.Enc;
9385   }
9386 };
9387 
9388 class XCoreABIInfo : public DefaultABIInfo {
9389 public:
9390   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9391   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9392                     QualType Ty) const override;
9393 };
9394 
9395 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9396   mutable TypeStringCache TSC;
9397 public:
9398   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9399       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9400   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9401                     CodeGen::CodeGenModule &M) const override;
9402 };
9403 
9404 } // End anonymous namespace.
9405 
9406 // TODO: this implementation is likely now redundant with the default
9407 // EmitVAArg.
9408 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9409                                 QualType Ty) const {
9410   CGBuilderTy &Builder = CGF.Builder;
9411 
9412   // Get the VAList.
9413   CharUnits SlotSize = CharUnits::fromQuantity(4);
9414   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9415 
9416   // Handle the argument.
9417   ABIArgInfo AI = classifyArgumentType(Ty);
9418   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9419   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9420   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9421     AI.setCoerceToType(ArgTy);
9422   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9423 
9424   Address Val = Address::invalid();
9425   CharUnits ArgSize = CharUnits::Zero();
9426   switch (AI.getKind()) {
9427   case ABIArgInfo::Expand:
9428   case ABIArgInfo::CoerceAndExpand:
9429   case ABIArgInfo::InAlloca:
9430     llvm_unreachable("Unsupported ABI kind for va_arg");
9431   case ABIArgInfo::Ignore:
9432     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9433     ArgSize = CharUnits::Zero();
9434     break;
9435   case ABIArgInfo::Extend:
9436   case ABIArgInfo::Direct:
9437     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9438     ArgSize = CharUnits::fromQuantity(
9439                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9440     ArgSize = ArgSize.alignTo(SlotSize);
9441     break;
9442   case ABIArgInfo::Indirect:
9443     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9444     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9445     ArgSize = SlotSize;
9446     break;
9447   }
9448 
9449   // Increment the VAList.
9450   if (!ArgSize.isZero()) {
9451     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9452     Builder.CreateStore(APN.getPointer(), VAListAddr);
9453   }
9454 
9455   return Val;
9456 }
9457 
9458 /// During the expansion of a RecordType, an incomplete TypeString is placed
9459 /// into the cache as a means to identify and break recursion.
9460 /// If there is a Recursive encoding in the cache, it is swapped out and will
9461 /// be reinserted by removeIncomplete().
9462 /// All other types of encoding should have been used rather than arriving here.
9463 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9464                                     std::string StubEnc) {
9465   if (!ID)
9466     return;
9467   Entry &E = Map[ID];
9468   assert( (E.Str.empty() || E.State == Recursive) &&
9469          "Incorrectly use of addIncomplete");
9470   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9471   E.Swapped.swap(E.Str); // swap out the Recursive
9472   E.Str.swap(StubEnc);
9473   E.State = Incomplete;
9474   ++IncompleteCount;
9475 }
9476 
9477 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9478 /// must be removed from the cache.
9479 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9480 /// Returns true if the RecordType was defined recursively.
9481 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9482   if (!ID)
9483     return false;
9484   auto I = Map.find(ID);
9485   assert(I != Map.end() && "Entry not present");
9486   Entry &E = I->second;
9487   assert( (E.State == Incomplete ||
9488            E.State == IncompleteUsed) &&
9489          "Entry must be an incomplete type");
9490   bool IsRecursive = false;
9491   if (E.State == IncompleteUsed) {
9492     // We made use of our Incomplete encoding, thus we are recursive.
9493     IsRecursive = true;
9494     --IncompleteUsedCount;
9495   }
9496   if (E.Swapped.empty())
9497     Map.erase(I);
9498   else {
9499     // Swap the Recursive back.
9500     E.Swapped.swap(E.Str);
9501     E.Swapped.clear();
9502     E.State = Recursive;
9503   }
9504   --IncompleteCount;
9505   return IsRecursive;
9506 }
9507 
9508 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9509 /// Recursive (viz: all sub-members were expanded as fully as possible).
9510 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9511                                     bool IsRecursive) {
9512   if (!ID || IncompleteUsedCount)
9513     return; // No key or it is is an incomplete sub-type so don't add.
9514   Entry &E = Map[ID];
9515   if (IsRecursive && !E.Str.empty()) {
9516     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9517            "This is not the same Recursive entry");
9518     // The parent container was not recursive after all, so we could have used
9519     // this Recursive sub-member entry after all, but we assumed the worse when
9520     // we started viz: IncompleteCount!=0.
9521     return;
9522   }
9523   assert(E.Str.empty() && "Entry already present");
9524   E.Str = Str.str();
9525   E.State = IsRecursive? Recursive : NonRecursive;
9526 }
9527 
9528 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9529 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9530 /// encoding is Recursive, return an empty StringRef.
9531 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9532   if (!ID)
9533     return StringRef();   // We have no key.
9534   auto I = Map.find(ID);
9535   if (I == Map.end())
9536     return StringRef();   // We have no encoding.
9537   Entry &E = I->second;
9538   if (E.State == Recursive && IncompleteCount)
9539     return StringRef();   // We don't use Recursive encodings for member types.
9540 
9541   if (E.State == Incomplete) {
9542     // The incomplete type is being used to break out of recursion.
9543     E.State = IncompleteUsed;
9544     ++IncompleteUsedCount;
9545   }
9546   return E.Str;
9547 }
9548 
9549 /// The XCore ABI includes a type information section that communicates symbol
9550 /// type information to the linker. The linker uses this information to verify
9551 /// safety/correctness of things such as array bound and pointers et al.
9552 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9553 /// This type information (TypeString) is emitted into meta data for all global
9554 /// symbols: definitions, declarations, functions & variables.
9555 ///
9556 /// The TypeString carries type, qualifier, name, size & value details.
9557 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9558 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9559 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9560 ///
9561 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9562                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
9563 
9564 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9565 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9566                                           CodeGen::CodeGenModule &CGM) const {
9567   SmallStringEnc Enc;
9568   if (getTypeString(Enc, D, CGM, TSC)) {
9569     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9570     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9571                                 llvm::MDString::get(Ctx, Enc.str())};
9572     llvm::NamedMDNode *MD =
9573       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9574     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9575   }
9576 }
9577 
9578 //===----------------------------------------------------------------------===//
9579 // SPIR ABI Implementation
9580 //===----------------------------------------------------------------------===//
9581 
9582 namespace {
9583 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9584 public:
9585   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9586       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
9587   unsigned getOpenCLKernelCallingConv() const override;
9588 };
9589 
9590 } // End anonymous namespace.
9591 
9592 namespace clang {
9593 namespace CodeGen {
9594 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9595   DefaultABIInfo SPIRABI(CGM.getTypes());
9596   SPIRABI.computeInfo(FI);
9597 }
9598 }
9599 }
9600 
9601 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9602   return llvm::CallingConv::SPIR_KERNEL;
9603 }
9604 
9605 static bool appendType(SmallStringEnc &Enc, QualType QType,
9606                        const CodeGen::CodeGenModule &CGM,
9607                        TypeStringCache &TSC);
9608 
9609 /// Helper function for appendRecordType().
9610 /// Builds a SmallVector containing the encoded field types in declaration
9611 /// order.
9612 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9613                              const RecordDecl *RD,
9614                              const CodeGen::CodeGenModule &CGM,
9615                              TypeStringCache &TSC) {
9616   for (const auto *Field : RD->fields()) {
9617     SmallStringEnc Enc;
9618     Enc += "m(";
9619     Enc += Field->getName();
9620     Enc += "){";
9621     if (Field->isBitField()) {
9622       Enc += "b(";
9623       llvm::raw_svector_ostream OS(Enc);
9624       OS << Field->getBitWidthValue(CGM.getContext());
9625       Enc += ':';
9626     }
9627     if (!appendType(Enc, Field->getType(), CGM, TSC))
9628       return false;
9629     if (Field->isBitField())
9630       Enc += ')';
9631     Enc += '}';
9632     FE.emplace_back(!Field->getName().empty(), Enc);
9633   }
9634   return true;
9635 }
9636 
9637 /// Appends structure and union types to Enc and adds encoding to cache.
9638 /// Recursively calls appendType (via extractFieldType) for each field.
9639 /// Union types have their fields ordered according to the ABI.
9640 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9641                              const CodeGen::CodeGenModule &CGM,
9642                              TypeStringCache &TSC, const IdentifierInfo *ID) {
9643   // Append the cached TypeString if we have one.
9644   StringRef TypeString = TSC.lookupStr(ID);
9645   if (!TypeString.empty()) {
9646     Enc += TypeString;
9647     return true;
9648   }
9649 
9650   // Start to emit an incomplete TypeString.
9651   size_t Start = Enc.size();
9652   Enc += (RT->isUnionType()? 'u' : 's');
9653   Enc += '(';
9654   if (ID)
9655     Enc += ID->getName();
9656   Enc += "){";
9657 
9658   // We collect all encoded fields and order as necessary.
9659   bool IsRecursive = false;
9660   const RecordDecl *RD = RT->getDecl()->getDefinition();
9661   if (RD && !RD->field_empty()) {
9662     // An incomplete TypeString stub is placed in the cache for this RecordType
9663     // so that recursive calls to this RecordType will use it whilst building a
9664     // complete TypeString for this RecordType.
9665     SmallVector<FieldEncoding, 16> FE;
9666     std::string StubEnc(Enc.substr(Start).str());
9667     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
9668     TSC.addIncomplete(ID, std::move(StubEnc));
9669     if (!extractFieldType(FE, RD, CGM, TSC)) {
9670       (void) TSC.removeIncomplete(ID);
9671       return false;
9672     }
9673     IsRecursive = TSC.removeIncomplete(ID);
9674     // The ABI requires unions to be sorted but not structures.
9675     // See FieldEncoding::operator< for sort algorithm.
9676     if (RT->isUnionType())
9677       llvm::sort(FE);
9678     // We can now complete the TypeString.
9679     unsigned E = FE.size();
9680     for (unsigned I = 0; I != E; ++I) {
9681       if (I)
9682         Enc += ',';
9683       Enc += FE[I].str();
9684     }
9685   }
9686   Enc += '}';
9687   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
9688   return true;
9689 }
9690 
9691 /// Appends enum types to Enc and adds the encoding to the cache.
9692 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
9693                            TypeStringCache &TSC,
9694                            const IdentifierInfo *ID) {
9695   // Append the cached TypeString if we have one.
9696   StringRef TypeString = TSC.lookupStr(ID);
9697   if (!TypeString.empty()) {
9698     Enc += TypeString;
9699     return true;
9700   }
9701 
9702   size_t Start = Enc.size();
9703   Enc += "e(";
9704   if (ID)
9705     Enc += ID->getName();
9706   Enc += "){";
9707 
9708   // We collect all encoded enumerations and order them alphanumerically.
9709   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
9710     SmallVector<FieldEncoding, 16> FE;
9711     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
9712          ++I) {
9713       SmallStringEnc EnumEnc;
9714       EnumEnc += "m(";
9715       EnumEnc += I->getName();
9716       EnumEnc += "){";
9717       I->getInitVal().toString(EnumEnc);
9718       EnumEnc += '}';
9719       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
9720     }
9721     llvm::sort(FE);
9722     unsigned E = FE.size();
9723     for (unsigned I = 0; I != E; ++I) {
9724       if (I)
9725         Enc += ',';
9726       Enc += FE[I].str();
9727     }
9728   }
9729   Enc += '}';
9730   TSC.addIfComplete(ID, Enc.substr(Start), false);
9731   return true;
9732 }
9733 
9734 /// Appends type's qualifier to Enc.
9735 /// This is done prior to appending the type's encoding.
9736 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
9737   // Qualifiers are emitted in alphabetical order.
9738   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
9739   int Lookup = 0;
9740   if (QT.isConstQualified())
9741     Lookup += 1<<0;
9742   if (QT.isRestrictQualified())
9743     Lookup += 1<<1;
9744   if (QT.isVolatileQualified())
9745     Lookup += 1<<2;
9746   Enc += Table[Lookup];
9747 }
9748 
9749 /// Appends built-in types to Enc.
9750 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9751   const char *EncType;
9752   switch (BT->getKind()) {
9753     case BuiltinType::Void:
9754       EncType = "0";
9755       break;
9756     case BuiltinType::Bool:
9757       EncType = "b";
9758       break;
9759     case BuiltinType::Char_U:
9760       EncType = "uc";
9761       break;
9762     case BuiltinType::UChar:
9763       EncType = "uc";
9764       break;
9765     case BuiltinType::SChar:
9766       EncType = "sc";
9767       break;
9768     case BuiltinType::UShort:
9769       EncType = "us";
9770       break;
9771     case BuiltinType::Short:
9772       EncType = "ss";
9773       break;
9774     case BuiltinType::UInt:
9775       EncType = "ui";
9776       break;
9777     case BuiltinType::Int:
9778       EncType = "si";
9779       break;
9780     case BuiltinType::ULong:
9781       EncType = "ul";
9782       break;
9783     case BuiltinType::Long:
9784       EncType = "sl";
9785       break;
9786     case BuiltinType::ULongLong:
9787       EncType = "ull";
9788       break;
9789     case BuiltinType::LongLong:
9790       EncType = "sll";
9791       break;
9792     case BuiltinType::Float:
9793       EncType = "ft";
9794       break;
9795     case BuiltinType::Double:
9796       EncType = "d";
9797       break;
9798     case BuiltinType::LongDouble:
9799       EncType = "ld";
9800       break;
9801     default:
9802       return false;
9803   }
9804   Enc += EncType;
9805   return true;
9806 }
9807 
9808 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
9809 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9810                               const CodeGen::CodeGenModule &CGM,
9811                               TypeStringCache &TSC) {
9812   Enc += "p(";
9813   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9814     return false;
9815   Enc += ')';
9816   return true;
9817 }
9818 
9819 /// Appends array encoding to Enc before calling appendType for the element.
9820 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9821                             const ArrayType *AT,
9822                             const CodeGen::CodeGenModule &CGM,
9823                             TypeStringCache &TSC, StringRef NoSizeEnc) {
9824   if (AT->getSizeModifier() != ArrayType::Normal)
9825     return false;
9826   Enc += "a(";
9827   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9828     CAT->getSize().toStringUnsigned(Enc);
9829   else
9830     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9831   Enc += ':';
9832   // The Qualifiers should be attached to the type rather than the array.
9833   appendQualifier(Enc, QT);
9834   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9835     return false;
9836   Enc += ')';
9837   return true;
9838 }
9839 
9840 /// Appends a function encoding to Enc, calling appendType for the return type
9841 /// and the arguments.
9842 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9843                              const CodeGen::CodeGenModule &CGM,
9844                              TypeStringCache &TSC) {
9845   Enc += "f{";
9846   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9847     return false;
9848   Enc += "}(";
9849   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9850     // N.B. we are only interested in the adjusted param types.
9851     auto I = FPT->param_type_begin();
9852     auto E = FPT->param_type_end();
9853     if (I != E) {
9854       do {
9855         if (!appendType(Enc, *I, CGM, TSC))
9856           return false;
9857         ++I;
9858         if (I != E)
9859           Enc += ',';
9860       } while (I != E);
9861       if (FPT->isVariadic())
9862         Enc += ",va";
9863     } else {
9864       if (FPT->isVariadic())
9865         Enc += "va";
9866       else
9867         Enc += '0';
9868     }
9869   }
9870   Enc += ')';
9871   return true;
9872 }
9873 
9874 /// Handles the type's qualifier before dispatching a call to handle specific
9875 /// type encodings.
9876 static bool appendType(SmallStringEnc &Enc, QualType QType,
9877                        const CodeGen::CodeGenModule &CGM,
9878                        TypeStringCache &TSC) {
9879 
9880   QualType QT = QType.getCanonicalType();
9881 
9882   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9883     // The Qualifiers should be attached to the type rather than the array.
9884     // Thus we don't call appendQualifier() here.
9885     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9886 
9887   appendQualifier(Enc, QT);
9888 
9889   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9890     return appendBuiltinType(Enc, BT);
9891 
9892   if (const PointerType *PT = QT->getAs<PointerType>())
9893     return appendPointerType(Enc, PT, CGM, TSC);
9894 
9895   if (const EnumType *ET = QT->getAs<EnumType>())
9896     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9897 
9898   if (const RecordType *RT = QT->getAsStructureType())
9899     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9900 
9901   if (const RecordType *RT = QT->getAsUnionType())
9902     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9903 
9904   if (const FunctionType *FT = QT->getAs<FunctionType>())
9905     return appendFunctionType(Enc, FT, CGM, TSC);
9906 
9907   return false;
9908 }
9909 
9910 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9911                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9912   if (!D)
9913     return false;
9914 
9915   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9916     if (FD->getLanguageLinkage() != CLanguageLinkage)
9917       return false;
9918     return appendType(Enc, FD->getType(), CGM, TSC);
9919   }
9920 
9921   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9922     if (VD->getLanguageLinkage() != CLanguageLinkage)
9923       return false;
9924     QualType QT = VD->getType().getCanonicalType();
9925     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9926       // Global ArrayTypes are given a size of '*' if the size is unknown.
9927       // The Qualifiers should be attached to the type rather than the array.
9928       // Thus we don't call appendQualifier() here.
9929       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
9930     }
9931     return appendType(Enc, QT, CGM, TSC);
9932   }
9933   return false;
9934 }
9935 
9936 //===----------------------------------------------------------------------===//
9937 // RISCV ABI Implementation
9938 //===----------------------------------------------------------------------===//
9939 
9940 namespace {
9941 class RISCVABIInfo : public DefaultABIInfo {
9942 private:
9943   // Size of the integer ('x') registers in bits.
9944   unsigned XLen;
9945   // Size of the floating point ('f') registers in bits. Note that the target
9946   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
9947   // with soft float ABI has FLen==0).
9948   unsigned FLen;
9949   static const int NumArgGPRs = 8;
9950   static const int NumArgFPRs = 8;
9951   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9952                                       llvm::Type *&Field1Ty,
9953                                       CharUnits &Field1Off,
9954                                       llvm::Type *&Field2Ty,
9955                                       CharUnits &Field2Off) const;
9956 
9957 public:
9958   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
9959       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
9960 
9961   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9962   // non-virtual, but computeInfo is virtual, so we overload it.
9963   void computeInfo(CGFunctionInfo &FI) const override;
9964 
9965   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
9966                                   int &ArgFPRsLeft) const;
9967   ABIArgInfo classifyReturnType(QualType RetTy) const;
9968 
9969   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9970                     QualType Ty) const override;
9971 
9972   ABIArgInfo extendType(QualType Ty) const;
9973 
9974   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9975                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
9976                                 CharUnits &Field2Off, int &NeededArgGPRs,
9977                                 int &NeededArgFPRs) const;
9978   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
9979                                                CharUnits Field1Off,
9980                                                llvm::Type *Field2Ty,
9981                                                CharUnits Field2Off) const;
9982 };
9983 } // end anonymous namespace
9984 
9985 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9986   QualType RetTy = FI.getReturnType();
9987   if (!getCXXABI().classifyReturnType(FI))
9988     FI.getReturnInfo() = classifyReturnType(RetTy);
9989 
9990   // IsRetIndirect is true if classifyArgumentType indicated the value should
9991   // be passed indirect, or if the type size is a scalar greater than 2*XLen
9992   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
9993   // in LLVM IR, relying on the backend lowering code to rewrite the argument
9994   // list and pass indirectly on RV32.
9995   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
9996   if (!IsRetIndirect && RetTy->isScalarType() &&
9997       getContext().getTypeSize(RetTy) > (2 * XLen)) {
9998     if (RetTy->isComplexType() && FLen) {
9999       QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
10000       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10001     } else {
10002       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10003       IsRetIndirect = true;
10004     }
10005   }
10006 
10007   // We must track the number of GPRs used in order to conform to the RISC-V
10008   // ABI, as integer scalars passed in registers should have signext/zeroext
10009   // when promoted, but are anyext if passed on the stack. As GPR usage is
10010   // different for variadic arguments, we must also track whether we are
10011   // examining a vararg or not.
10012   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10013   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10014   int NumFixedArgs = FI.getNumRequiredArgs();
10015 
10016   int ArgNum = 0;
10017   for (auto &ArgInfo : FI.arguments()) {
10018     bool IsFixed = ArgNum < NumFixedArgs;
10019     ArgInfo.info =
10020         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10021     ArgNum++;
10022   }
10023 }
10024 
10025 // Returns true if the struct is a potential candidate for the floating point
10026 // calling convention. If this function returns true, the caller is
10027 // responsible for checking that if there is only a single field then that
10028 // field is a float.
10029 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10030                                                   llvm::Type *&Field1Ty,
10031                                                   CharUnits &Field1Off,
10032                                                   llvm::Type *&Field2Ty,
10033                                                   CharUnits &Field2Off) const {
10034   bool IsInt = Ty->isIntegralOrEnumerationType();
10035   bool IsFloat = Ty->isRealFloatingType();
10036 
10037   if (IsInt || IsFloat) {
10038     uint64_t Size = getContext().getTypeSize(Ty);
10039     if (IsInt && Size > XLen)
10040       return false;
10041     // Can't be eligible if larger than the FP registers. Half precision isn't
10042     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10043     // default to the integer ABI in that case.
10044     if (IsFloat && (Size > FLen || Size < 32))
10045       return false;
10046     // Can't be eligible if an integer type was already found (int+int pairs
10047     // are not eligible).
10048     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10049       return false;
10050     if (!Field1Ty) {
10051       Field1Ty = CGT.ConvertType(Ty);
10052       Field1Off = CurOff;
10053       return true;
10054     }
10055     if (!Field2Ty) {
10056       Field2Ty = CGT.ConvertType(Ty);
10057       Field2Off = CurOff;
10058       return true;
10059     }
10060     return false;
10061   }
10062 
10063   if (auto CTy = Ty->getAs<ComplexType>()) {
10064     if (Field1Ty)
10065       return false;
10066     QualType EltTy = CTy->getElementType();
10067     if (getContext().getTypeSize(EltTy) > FLen)
10068       return false;
10069     Field1Ty = CGT.ConvertType(EltTy);
10070     Field1Off = CurOff;
10071     assert(CurOff.isZero() && "Unexpected offset for first field");
10072     Field2Ty = Field1Ty;
10073     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10074     return true;
10075   }
10076 
10077   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10078     uint64_t ArraySize = ATy->getSize().getZExtValue();
10079     QualType EltTy = ATy->getElementType();
10080     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10081     for (uint64_t i = 0; i < ArraySize; ++i) {
10082       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10083                                                 Field1Off, Field2Ty, Field2Off);
10084       if (!Ret)
10085         return false;
10086       CurOff += EltSize;
10087     }
10088     return true;
10089   }
10090 
10091   if (const auto *RTy = Ty->getAs<RecordType>()) {
10092     // Structures with either a non-trivial destructor or a non-trivial
10093     // copy constructor are not eligible for the FP calling convention.
10094     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10095       return false;
10096     if (isEmptyRecord(getContext(), Ty, true))
10097       return true;
10098     const RecordDecl *RD = RTy->getDecl();
10099     // Unions aren't eligible unless they're empty (which is caught above).
10100     if (RD->isUnion())
10101       return false;
10102     int ZeroWidthBitFieldCount = 0;
10103     for (const FieldDecl *FD : RD->fields()) {
10104       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10105       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10106       QualType QTy = FD->getType();
10107       if (FD->isBitField()) {
10108         unsigned BitWidth = FD->getBitWidthValue(getContext());
10109         // Allow a bitfield with a type greater than XLen as long as the
10110         // bitwidth is XLen or less.
10111         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10112           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10113         if (BitWidth == 0) {
10114           ZeroWidthBitFieldCount++;
10115           continue;
10116         }
10117       }
10118 
10119       bool Ret = detectFPCCEligibleStructHelper(
10120           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10121           Field1Ty, Field1Off, Field2Ty, Field2Off);
10122       if (!Ret)
10123         return false;
10124 
10125       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10126       // or int+fp structs, but are ignored for a struct with an fp field and
10127       // any number of zero-width bitfields.
10128       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10129         return false;
10130     }
10131     return Field1Ty != nullptr;
10132   }
10133 
10134   return false;
10135 }
10136 
10137 // Determine if a struct is eligible for passing according to the floating
10138 // point calling convention (i.e., when flattened it contains a single fp
10139 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10140 // NeededArgGPRs are incremented appropriately.
10141 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10142                                             CharUnits &Field1Off,
10143                                             llvm::Type *&Field2Ty,
10144                                             CharUnits &Field2Off,
10145                                             int &NeededArgGPRs,
10146                                             int &NeededArgFPRs) const {
10147   Field1Ty = nullptr;
10148   Field2Ty = nullptr;
10149   NeededArgGPRs = 0;
10150   NeededArgFPRs = 0;
10151   bool IsCandidate = detectFPCCEligibleStructHelper(
10152       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10153   // Not really a candidate if we have a single int but no float.
10154   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10155     return false;
10156   if (!IsCandidate)
10157     return false;
10158   if (Field1Ty && Field1Ty->isFloatingPointTy())
10159     NeededArgFPRs++;
10160   else if (Field1Ty)
10161     NeededArgGPRs++;
10162   if (Field2Ty && Field2Ty->isFloatingPointTy())
10163     NeededArgFPRs++;
10164   else if (Field2Ty)
10165     NeededArgGPRs++;
10166   return IsCandidate;
10167 }
10168 
10169 // Call getCoerceAndExpand for the two-element flattened struct described by
10170 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10171 // appropriate coerceToType and unpaddedCoerceToType.
10172 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10173     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10174     CharUnits Field2Off) const {
10175   SmallVector<llvm::Type *, 3> CoerceElts;
10176   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10177   if (!Field1Off.isZero())
10178     CoerceElts.push_back(llvm::ArrayType::get(
10179         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10180 
10181   CoerceElts.push_back(Field1Ty);
10182   UnpaddedCoerceElts.push_back(Field1Ty);
10183 
10184   if (!Field2Ty) {
10185     return ABIArgInfo::getCoerceAndExpand(
10186         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10187         UnpaddedCoerceElts[0]);
10188   }
10189 
10190   CharUnits Field2Align =
10191       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10192   CharUnits Field1Size =
10193       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10194   CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
10195 
10196   CharUnits Padding = CharUnits::Zero();
10197   if (Field2Off > Field2OffNoPadNoPack)
10198     Padding = Field2Off - Field2OffNoPadNoPack;
10199   else if (Field2Off != Field2Align && Field2Off > Field1Size)
10200     Padding = Field2Off - Field1Size;
10201 
10202   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10203 
10204   if (!Padding.isZero())
10205     CoerceElts.push_back(llvm::ArrayType::get(
10206         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10207 
10208   CoerceElts.push_back(Field2Ty);
10209   UnpaddedCoerceElts.push_back(Field2Ty);
10210 
10211   auto CoerceToType =
10212       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10213   auto UnpaddedCoerceToType =
10214       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10215 
10216   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10217 }
10218 
10219 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10220                                               int &ArgGPRsLeft,
10221                                               int &ArgFPRsLeft) const {
10222   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10223   Ty = useFirstFieldIfTransparentUnion(Ty);
10224 
10225   // Structures with either a non-trivial destructor or a non-trivial
10226   // copy constructor are always passed indirectly.
10227   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10228     if (ArgGPRsLeft)
10229       ArgGPRsLeft -= 1;
10230     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10231                                            CGCXXABI::RAA_DirectInMemory);
10232   }
10233 
10234   // Ignore empty structs/unions.
10235   if (isEmptyRecord(getContext(), Ty, true))
10236     return ABIArgInfo::getIgnore();
10237 
10238   uint64_t Size = getContext().getTypeSize(Ty);
10239 
10240   // Pass floating point values via FPRs if possible.
10241   if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) {
10242     ArgFPRsLeft--;
10243     return ABIArgInfo::getDirect();
10244   }
10245 
10246   // Complex types for the hard float ABI must be passed direct rather than
10247   // using CoerceAndExpand.
10248   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10249     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10250     if (getContext().getTypeSize(EltTy) <= FLen) {
10251       ArgFPRsLeft -= 2;
10252       return ABIArgInfo::getDirect();
10253     }
10254   }
10255 
10256   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10257     llvm::Type *Field1Ty = nullptr;
10258     llvm::Type *Field2Ty = nullptr;
10259     CharUnits Field1Off = CharUnits::Zero();
10260     CharUnits Field2Off = CharUnits::Zero();
10261     int NeededArgGPRs;
10262     int NeededArgFPRs;
10263     bool IsCandidate =
10264         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10265                                  NeededArgGPRs, NeededArgFPRs);
10266     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10267         NeededArgFPRs <= ArgFPRsLeft) {
10268       ArgGPRsLeft -= NeededArgGPRs;
10269       ArgFPRsLeft -= NeededArgFPRs;
10270       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10271                                                Field2Off);
10272     }
10273   }
10274 
10275   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10276   bool MustUseStack = false;
10277   // Determine the number of GPRs needed to pass the current argument
10278   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10279   // register pairs, so may consume 3 registers.
10280   int NeededArgGPRs = 1;
10281   if (!IsFixed && NeededAlign == 2 * XLen)
10282     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10283   else if (Size > XLen && Size <= 2 * XLen)
10284     NeededArgGPRs = 2;
10285 
10286   if (NeededArgGPRs > ArgGPRsLeft) {
10287     MustUseStack = true;
10288     NeededArgGPRs = ArgGPRsLeft;
10289   }
10290 
10291   ArgGPRsLeft -= NeededArgGPRs;
10292 
10293   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10294     // Treat an enum type as its underlying type.
10295     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10296       Ty = EnumTy->getDecl()->getIntegerType();
10297 
10298     // All integral types are promoted to XLen width, unless passed on the
10299     // stack.
10300     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10301       return extendType(Ty);
10302     }
10303 
10304     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10305       if (EIT->getNumBits() < XLen && !MustUseStack)
10306         return extendType(Ty);
10307       if (EIT->getNumBits() > 128 ||
10308           (!getContext().getTargetInfo().hasInt128Type() &&
10309            EIT->getNumBits() > 64))
10310         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10311     }
10312 
10313     return ABIArgInfo::getDirect();
10314   }
10315 
10316   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10317   // so coerce to integers.
10318   if (Size <= 2 * XLen) {
10319     unsigned Alignment = getContext().getTypeAlign(Ty);
10320 
10321     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10322     // required, and a 2-element XLen array if only XLen alignment is required.
10323     if (Size <= XLen) {
10324       return ABIArgInfo::getDirect(
10325           llvm::IntegerType::get(getVMContext(), XLen));
10326     } else if (Alignment == 2 * XLen) {
10327       return ABIArgInfo::getDirect(
10328           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10329     } else {
10330       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10331           llvm::IntegerType::get(getVMContext(), XLen), 2));
10332     }
10333   }
10334   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10335 }
10336 
10337 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10338   if (RetTy->isVoidType())
10339     return ABIArgInfo::getIgnore();
10340 
10341   int ArgGPRsLeft = 2;
10342   int ArgFPRsLeft = FLen ? 2 : 0;
10343 
10344   // The rules for return and argument types are the same, so defer to
10345   // classifyArgumentType.
10346   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10347                               ArgFPRsLeft);
10348 }
10349 
10350 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10351                                 QualType Ty) const {
10352   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10353 
10354   // Empty records are ignored for parameter passing purposes.
10355   if (isEmptyRecord(getContext(), Ty, true)) {
10356     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10357     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10358     return Addr;
10359   }
10360 
10361   std::pair<CharUnits, CharUnits> SizeAndAlign =
10362       getContext().getTypeInfoInChars(Ty);
10363 
10364   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10365   bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
10366 
10367   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
10368                           SlotSize, /*AllowHigherAlign=*/true);
10369 }
10370 
10371 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10372   int TySize = getContext().getTypeSize(Ty);
10373   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10374   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10375     return ABIArgInfo::getSignExtend(Ty);
10376   return ABIArgInfo::getExtend(Ty);
10377 }
10378 
10379 namespace {
10380 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10381 public:
10382   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10383                          unsigned FLen)
10384       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10385 
10386   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10387                            CodeGen::CodeGenModule &CGM) const override {
10388     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10389     if (!FD) return;
10390 
10391     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10392     if (!Attr)
10393       return;
10394 
10395     const char *Kind;
10396     switch (Attr->getInterrupt()) {
10397     case RISCVInterruptAttr::user: Kind = "user"; break;
10398     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10399     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10400     }
10401 
10402     auto *Fn = cast<llvm::Function>(GV);
10403 
10404     Fn->addFnAttr("interrupt", Kind);
10405   }
10406 };
10407 } // namespace
10408 
10409 //===----------------------------------------------------------------------===//
10410 // Driver code
10411 //===----------------------------------------------------------------------===//
10412 
10413 bool CodeGenModule::supportsCOMDAT() const {
10414   return getTriple().supportsCOMDAT();
10415 }
10416 
10417 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10418   if (TheTargetCodeGenInfo)
10419     return *TheTargetCodeGenInfo;
10420 
10421   // Helper to set the unique_ptr while still keeping the return value.
10422   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10423     this->TheTargetCodeGenInfo.reset(P);
10424     return *P;
10425   };
10426 
10427   const llvm::Triple &Triple = getTarget().getTriple();
10428   switch (Triple.getArch()) {
10429   default:
10430     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10431 
10432   case llvm::Triple::le32:
10433     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10434   case llvm::Triple::mips:
10435   case llvm::Triple::mipsel:
10436     if (Triple.getOS() == llvm::Triple::NaCl)
10437       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10438     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10439 
10440   case llvm::Triple::mips64:
10441   case llvm::Triple::mips64el:
10442     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10443 
10444   case llvm::Triple::avr:
10445     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10446 
10447   case llvm::Triple::aarch64:
10448   case llvm::Triple::aarch64_32:
10449   case llvm::Triple::aarch64_be: {
10450     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10451     if (getTarget().getABI() == "darwinpcs")
10452       Kind = AArch64ABIInfo::DarwinPCS;
10453     else if (Triple.isOSWindows())
10454       return SetCGInfo(
10455           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10456 
10457     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10458   }
10459 
10460   case llvm::Triple::wasm32:
10461   case llvm::Triple::wasm64: {
10462     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10463     if (getTarget().getABI() == "experimental-mv")
10464       Kind = WebAssemblyABIInfo::ExperimentalMV;
10465     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10466   }
10467 
10468   case llvm::Triple::arm:
10469   case llvm::Triple::armeb:
10470   case llvm::Triple::thumb:
10471   case llvm::Triple::thumbeb: {
10472     if (Triple.getOS() == llvm::Triple::Win32) {
10473       return SetCGInfo(
10474           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10475     }
10476 
10477     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10478     StringRef ABIStr = getTarget().getABI();
10479     if (ABIStr == "apcs-gnu")
10480       Kind = ARMABIInfo::APCS;
10481     else if (ABIStr == "aapcs16")
10482       Kind = ARMABIInfo::AAPCS16_VFP;
10483     else if (CodeGenOpts.FloatABI == "hard" ||
10484              (CodeGenOpts.FloatABI != "soft" &&
10485               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10486                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10487                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10488       Kind = ARMABIInfo::AAPCS_VFP;
10489 
10490     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10491   }
10492 
10493   case llvm::Triple::ppc: {
10494     bool IsSoftFloat =
10495         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10496     bool RetSmallStructInRegABI =
10497         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10498     return SetCGInfo(
10499         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10500   }
10501   case llvm::Triple::ppc64:
10502     if (Triple.isOSBinFormatELF()) {
10503       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10504       if (getTarget().getABI() == "elfv2")
10505         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10506       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10507       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10508 
10509       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10510                                                         IsSoftFloat));
10511     } else
10512       return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10513   case llvm::Triple::ppc64le: {
10514     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10515     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10516     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
10517       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10518     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10519     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10520 
10521     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10522                                                       IsSoftFloat));
10523   }
10524 
10525   case llvm::Triple::nvptx:
10526   case llvm::Triple::nvptx64:
10527     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10528 
10529   case llvm::Triple::msp430:
10530     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10531 
10532   case llvm::Triple::riscv32:
10533   case llvm::Triple::riscv64: {
10534     StringRef ABIStr = getTarget().getABI();
10535     unsigned XLen = getTarget().getPointerWidth(0);
10536     unsigned ABIFLen = 0;
10537     if (ABIStr.endswith("f"))
10538       ABIFLen = 32;
10539     else if (ABIStr.endswith("d"))
10540       ABIFLen = 64;
10541     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10542   }
10543 
10544   case llvm::Triple::systemz: {
10545     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
10546     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
10547     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
10548   }
10549 
10550   case llvm::Triple::tce:
10551   case llvm::Triple::tcele:
10552     return SetCGInfo(new TCETargetCodeGenInfo(Types));
10553 
10554   case llvm::Triple::x86: {
10555     bool IsDarwinVectorABI = Triple.isOSDarwin();
10556     bool RetSmallStructInRegABI =
10557         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10558     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
10559 
10560     if (Triple.getOS() == llvm::Triple::Win32) {
10561       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
10562           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10563           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
10564     } else {
10565       return SetCGInfo(new X86_32TargetCodeGenInfo(
10566           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10567           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
10568           CodeGenOpts.FloatABI == "soft"));
10569     }
10570   }
10571 
10572   case llvm::Triple::x86_64: {
10573     StringRef ABI = getTarget().getABI();
10574     X86AVXABILevel AVXLevel =
10575         (ABI == "avx512"
10576              ? X86AVXABILevel::AVX512
10577              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
10578 
10579     switch (Triple.getOS()) {
10580     case llvm::Triple::Win32:
10581       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
10582     default:
10583       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
10584     }
10585   }
10586   case llvm::Triple::hexagon:
10587     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
10588   case llvm::Triple::lanai:
10589     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
10590   case llvm::Triple::r600:
10591     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10592   case llvm::Triple::amdgcn:
10593     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10594   case llvm::Triple::sparc:
10595     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
10596   case llvm::Triple::sparcv9:
10597     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
10598   case llvm::Triple::xcore:
10599     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
10600   case llvm::Triple::arc:
10601     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
10602   case llvm::Triple::spir:
10603   case llvm::Triple::spir64:
10604     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
10605   }
10606 }
10607 
10608 /// Create an OpenCL kernel for an enqueued block.
10609 ///
10610 /// The kernel has the same function type as the block invoke function. Its
10611 /// name is the name of the block invoke function postfixed with "_kernel".
10612 /// It simply calls the block invoke function then returns.
10613 llvm::Function *
10614 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
10615                                              llvm::Function *Invoke,
10616                                              llvm::Value *BlockLiteral) const {
10617   auto *InvokeFT = Invoke->getFunctionType();
10618   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10619   for (auto &P : InvokeFT->params())
10620     ArgTys.push_back(P);
10621   auto &C = CGF.getLLVMContext();
10622   std::string Name = Invoke->getName().str() + "_kernel";
10623   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10624   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10625                                    &CGF.CGM.getModule());
10626   auto IP = CGF.Builder.saveIP();
10627   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10628   auto &Builder = CGF.Builder;
10629   Builder.SetInsertPoint(BB);
10630   llvm::SmallVector<llvm::Value *, 2> Args;
10631   for (auto &A : F->args())
10632     Args.push_back(&A);
10633   Builder.CreateCall(Invoke, Args);
10634   Builder.CreateRetVoid();
10635   Builder.restoreIP(IP);
10636   return F;
10637 }
10638 
10639 /// Create an OpenCL kernel for an enqueued block.
10640 ///
10641 /// The type of the first argument (the block literal) is the struct type
10642 /// of the block literal instead of a pointer type. The first argument
10643 /// (block literal) is passed directly by value to the kernel. The kernel
10644 /// allocates the same type of struct on stack and stores the block literal
10645 /// to it and passes its pointer to the block invoke function. The kernel
10646 /// has "enqueued-block" function attribute and kernel argument metadata.
10647 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
10648     CodeGenFunction &CGF, llvm::Function *Invoke,
10649     llvm::Value *BlockLiteral) const {
10650   auto &Builder = CGF.Builder;
10651   auto &C = CGF.getLLVMContext();
10652 
10653   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
10654   auto *InvokeFT = Invoke->getFunctionType();
10655   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10656   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
10657   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
10658   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
10659   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
10660   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
10661   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
10662 
10663   ArgTys.push_back(BlockTy);
10664   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10665   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
10666   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10667   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10668   AccessQuals.push_back(llvm::MDString::get(C, "none"));
10669   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
10670   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
10671     ArgTys.push_back(InvokeFT->getParamType(I));
10672     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
10673     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
10674     AccessQuals.push_back(llvm::MDString::get(C, "none"));
10675     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
10676     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10677     ArgNames.push_back(
10678         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
10679   }
10680   std::string Name = Invoke->getName().str() + "_kernel";
10681   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10682   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10683                                    &CGF.CGM.getModule());
10684   F->addFnAttr("enqueued-block");
10685   auto IP = CGF.Builder.saveIP();
10686   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10687   Builder.SetInsertPoint(BB);
10688   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
10689   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
10690   BlockPtr->setAlignment(BlockAlign);
10691   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
10692   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
10693   llvm::SmallVector<llvm::Value *, 2> Args;
10694   Args.push_back(Cast);
10695   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
10696     Args.push_back(I);
10697   Builder.CreateCall(Invoke, Args);
10698   Builder.CreateRetVoid();
10699   Builder.restoreIP(IP);
10700 
10701   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
10702   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
10703   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
10704   F->setMetadata("kernel_arg_base_type",
10705                  llvm::MDNode::get(C, ArgBaseTypeNames));
10706   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
10707   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
10708     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
10709 
10710   return F;
10711 }
10712