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/Basic/DiagnosticFrontend.h"
24 #include "clang/CodeGen/CGFunctionInfo.h"
25 #include "clang/CodeGen/SwiftCallingConv.h"
26 #include "llvm/ADT/SmallBitVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IntrinsicsNVPTX.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm> // std::sort
36 
37 using namespace clang;
38 using namespace CodeGen;
39 
40 // Helper for coercing an aggregate argument or return value into an integer
41 // array of the same size (including padding) and alignment.  This alternate
42 // coercion happens only for the RenderScript ABI and can be removed after
43 // runtimes that rely on it are no longer supported.
44 //
45 // RenderScript assumes that the size of the argument / return value in the IR
46 // is the same as the size of the corresponding qualified type. This helper
47 // coerces the aggregate type into an array of the same size (including
48 // padding).  This coercion is used in lieu of expansion of struct members or
49 // other canonical coercions that return a coerced-type of larger size.
50 //
51 // Ty          - The argument / return value type
52 // Context     - The associated ASTContext
53 // LLVMContext - The associated LLVMContext
54 static ABIArgInfo coerceToIntArray(QualType Ty,
55                                    ASTContext &Context,
56                                    llvm::LLVMContext &LLVMContext) {
57   // Alignment and Size are measured in bits.
58   const uint64_t Size = Context.getTypeSize(Ty);
59   const uint64_t Alignment = Context.getTypeAlign(Ty);
60   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
61   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
62   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
63 }
64 
65 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
66                                llvm::Value *Array,
67                                llvm::Value *Value,
68                                unsigned FirstIndex,
69                                unsigned LastIndex) {
70   // Alternatively, we could emit this as a loop in the source.
71   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
72     llvm::Value *Cell =
73         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
74     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
75   }
76 }
77 
78 static bool isAggregateTypeForABI(QualType T) {
79   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
80          T->isMemberFunctionPointerType();
81 }
82 
83 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
84                                             bool Realign,
85                                             llvm::Type *Padding) const {
86   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
87                                  Realign, Padding);
88 }
89 
90 ABIArgInfo
91 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
92   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
93                                       /*ByVal*/ false, Realign);
94 }
95 
96 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
97                              QualType Ty) const {
98   return Address::invalid();
99 }
100 
101 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
102   if (Ty->isPromotableIntegerType())
103     return true;
104 
105   if (const auto *EIT = Ty->getAs<ExtIntType>())
106     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
107       return true;
108 
109   return false;
110 }
111 
112 ABIInfo::~ABIInfo() {}
113 
114 /// Does the given lowering require more than the given number of
115 /// registers when expanded?
116 ///
117 /// This is intended to be the basis of a reasonable basic implementation
118 /// of should{Pass,Return}IndirectlyForSwift.
119 ///
120 /// For most targets, a limit of four total registers is reasonable; this
121 /// limits the amount of code required in order to move around the value
122 /// in case it wasn't produced immediately prior to the call by the caller
123 /// (or wasn't produced in exactly the right registers) or isn't used
124 /// immediately within the callee.  But some targets may need to further
125 /// limit the register count due to an inability to support that many
126 /// return registers.
127 static bool occupiesMoreThan(CodeGenTypes &cgt,
128                              ArrayRef<llvm::Type*> scalarTypes,
129                              unsigned maxAllRegisters) {
130   unsigned intCount = 0, fpCount = 0;
131   for (llvm::Type *type : scalarTypes) {
132     if (type->isPointerTy()) {
133       intCount++;
134     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
135       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
136       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
137     } else {
138       assert(type->isVectorTy() || type->isFloatingPointTy());
139       fpCount++;
140     }
141   }
142 
143   return (intCount + fpCount > maxAllRegisters);
144 }
145 
146 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
147                                              llvm::Type *eltTy,
148                                              unsigned numElts) const {
149   // The default implementation of this assumes that the target guarantees
150   // 128-bit SIMD support but nothing more.
151   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
152 }
153 
154 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
155                                               CGCXXABI &CXXABI) {
156   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
157   if (!RD) {
158     if (!RT->getDecl()->canPassInRegisters())
159       return CGCXXABI::RAA_Indirect;
160     return CGCXXABI::RAA_Default;
161   }
162   return CXXABI.getRecordArgABI(RD);
163 }
164 
165 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
166                                               CGCXXABI &CXXABI) {
167   const RecordType *RT = T->getAs<RecordType>();
168   if (!RT)
169     return CGCXXABI::RAA_Default;
170   return getRecordArgABI(RT, CXXABI);
171 }
172 
173 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
174                                const ABIInfo &Info) {
175   QualType Ty = FI.getReturnType();
176 
177   if (const auto *RT = Ty->getAs<RecordType>())
178     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
179         !RT->getDecl()->canPassInRegisters()) {
180       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
181       return true;
182     }
183 
184   return CXXABI.classifyReturnType(FI);
185 }
186 
187 /// Pass transparent unions as if they were the type of the first element. Sema
188 /// should ensure that all elements of the union have the same "machine type".
189 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
190   if (const RecordType *UT = Ty->getAsUnionType()) {
191     const RecordDecl *UD = UT->getDecl();
192     if (UD->hasAttr<TransparentUnionAttr>()) {
193       assert(!UD->field_empty() && "sema created an empty transparent union");
194       return UD->field_begin()->getType();
195     }
196   }
197   return Ty;
198 }
199 
200 CGCXXABI &ABIInfo::getCXXABI() const {
201   return CGT.getCXXABI();
202 }
203 
204 ASTContext &ABIInfo::getContext() const {
205   return CGT.getContext();
206 }
207 
208 llvm::LLVMContext &ABIInfo::getVMContext() const {
209   return CGT.getLLVMContext();
210 }
211 
212 const llvm::DataLayout &ABIInfo::getDataLayout() const {
213   return CGT.getDataLayout();
214 }
215 
216 const TargetInfo &ABIInfo::getTarget() const {
217   return CGT.getTarget();
218 }
219 
220 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
221   return CGT.getCodeGenOpts();
222 }
223 
224 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
225 
226 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
227   return false;
228 }
229 
230 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
231                                                 uint64_t Members) const {
232   return false;
233 }
234 
235 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
236   raw_ostream &OS = llvm::errs();
237   OS << "(ABIArgInfo Kind=";
238   switch (TheKind) {
239   case Direct:
240     OS << "Direct Type=";
241     if (llvm::Type *Ty = getCoerceToType())
242       Ty->print(OS);
243     else
244       OS << "null";
245     break;
246   case Extend:
247     OS << "Extend";
248     break;
249   case Ignore:
250     OS << "Ignore";
251     break;
252   case InAlloca:
253     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
254     break;
255   case Indirect:
256     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
257        << " ByVal=" << getIndirectByVal()
258        << " Realign=" << getIndirectRealign();
259     break;
260   case IndirectAliased:
261     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
262        << " AadrSpace=" << getIndirectAddrSpace()
263        << " Realign=" << getIndirectRealign();
264     break;
265   case Expand:
266     OS << "Expand";
267     break;
268   case CoerceAndExpand:
269     OS << "CoerceAndExpand Type=";
270     getCoerceAndExpandType()->print(OS);
271     break;
272   }
273   OS << ")\n";
274 }
275 
276 // Dynamically round a pointer up to a multiple of the given alignment.
277 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
278                                                   llvm::Value *Ptr,
279                                                   CharUnits Align) {
280   llvm::Value *PtrAsInt = Ptr;
281   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
282   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
283   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
284         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
285   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
286            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
287   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
288                                         Ptr->getType(),
289                                         Ptr->getName() + ".aligned");
290   return PtrAsInt;
291 }
292 
293 /// Emit va_arg for a platform using the common void* representation,
294 /// where arguments are simply emitted in an array of slots on the stack.
295 ///
296 /// This version implements the core direct-value passing rules.
297 ///
298 /// \param SlotSize - The size and alignment of a stack slot.
299 ///   Each argument will be allocated to a multiple of this number of
300 ///   slots, and all the slots will be aligned to this value.
301 /// \param AllowHigherAlign - The slot alignment is not a cap;
302 ///   an argument type with an alignment greater than the slot size
303 ///   will be emitted on a higher-alignment address, potentially
304 ///   leaving one or more empty slots behind as padding.  If this
305 ///   is false, the returned address might be less-aligned than
306 ///   DirectAlign.
307 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
308                                       Address VAListAddr,
309                                       llvm::Type *DirectTy,
310                                       CharUnits DirectSize,
311                                       CharUnits DirectAlign,
312                                       CharUnits SlotSize,
313                                       bool AllowHigherAlign) {
314   // Cast the element type to i8* if necessary.  Some platforms define
315   // va_list as a struct containing an i8* instead of just an i8*.
316   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
317     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
318 
319   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
320 
321   // If the CC aligns values higher than the slot size, do so if needed.
322   Address Addr = Address::invalid();
323   if (AllowHigherAlign && DirectAlign > SlotSize) {
324     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
325                                                  DirectAlign);
326   } else {
327     Addr = Address(Ptr, SlotSize);
328   }
329 
330   // Advance the pointer past the argument, then store that back.
331   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
332   Address NextPtr =
333       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
334   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
335 
336   // If the argument is smaller than a slot, and this is a big-endian
337   // target, the argument will be right-adjusted in its slot.
338   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
339       !DirectTy->isStructTy()) {
340     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
341   }
342 
343   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
344   return Addr;
345 }
346 
347 /// Emit va_arg for a platform using the common void* representation,
348 /// where arguments are simply emitted in an array of slots on the stack.
349 ///
350 /// \param IsIndirect - Values of this type are passed indirectly.
351 /// \param ValueInfo - The size and alignment of this type, generally
352 ///   computed with getContext().getTypeInfoInChars(ValueTy).
353 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
354 ///   Each argument will be allocated to a multiple of this number of
355 ///   slots, and all the slots will be aligned to this value.
356 /// \param AllowHigherAlign - The slot alignment is not a cap;
357 ///   an argument type with an alignment greater than the slot size
358 ///   will be emitted on a higher-alignment address, potentially
359 ///   leaving one or more empty slots behind as padding.
360 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
361                                 QualType ValueTy, bool IsIndirect,
362                                 TypeInfoChars ValueInfo,
363                                 CharUnits SlotSizeAndAlign,
364                                 bool AllowHigherAlign) {
365   // The size and alignment of the value that was passed directly.
366   CharUnits DirectSize, DirectAlign;
367   if (IsIndirect) {
368     DirectSize = CGF.getPointerSize();
369     DirectAlign = CGF.getPointerAlign();
370   } else {
371     DirectSize = ValueInfo.Width;
372     DirectAlign = ValueInfo.Align;
373   }
374 
375   // Cast the address we've calculated to the right type.
376   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
377   if (IsIndirect)
378     DirectTy = DirectTy->getPointerTo(0);
379 
380   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
381                                         DirectSize, DirectAlign,
382                                         SlotSizeAndAlign,
383                                         AllowHigherAlign);
384 
385   if (IsIndirect) {
386     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
387   }
388 
389   return Addr;
390 
391 }
392 
393 static Address emitMergePHI(CodeGenFunction &CGF,
394                             Address Addr1, llvm::BasicBlock *Block1,
395                             Address Addr2, llvm::BasicBlock *Block2,
396                             const llvm::Twine &Name = "") {
397   assert(Addr1.getType() == Addr2.getType());
398   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
399   PHI->addIncoming(Addr1.getPointer(), Block1);
400   PHI->addIncoming(Addr2.getPointer(), Block2);
401   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
402   return Address(PHI, Align);
403 }
404 
405 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
406 
407 // If someone can figure out a general rule for this, that would be great.
408 // It's probably just doomed to be platform-dependent, though.
409 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
410   // Verified for:
411   //   x86-64     FreeBSD, Linux, Darwin
412   //   x86-32     FreeBSD, Linux, Darwin
413   //   PowerPC    Linux, Darwin
414   //   ARM        Darwin (*not* EABI)
415   //   AArch64    Linux
416   return 32;
417 }
418 
419 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
420                                      const FunctionNoProtoType *fnType) const {
421   // The following conventions are known to require this to be false:
422   //   x86_stdcall
423   //   MIPS
424   // For everything else, we just prefer false unless we opt out.
425   return false;
426 }
427 
428 void
429 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
430                                              llvm::SmallString<24> &Opt) const {
431   // This assumes the user is passing a library name like "rt" instead of a
432   // filename like "librt.a/so", and that they don't care whether it's static or
433   // dynamic.
434   Opt = "-l";
435   Opt += Lib;
436 }
437 
438 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
439   // OpenCL kernels are called via an explicit runtime API with arguments
440   // set with clSetKernelArg(), not as normal sub-functions.
441   // Return SPIR_KERNEL by default as the kernel calling convention to
442   // ensure the fingerprint is fixed such way that each OpenCL argument
443   // gets one matching argument in the produced kernel function argument
444   // list to enable feasible implementation of clSetKernelArg() with
445   // aggregates etc. In case we would use the default C calling conv here,
446   // clSetKernelArg() might break depending on the target-specific
447   // conventions; different targets might split structs passed as values
448   // to multiple function arguments etc.
449   return llvm::CallingConv::SPIR_KERNEL;
450 }
451 
452 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
453     llvm::PointerType *T, QualType QT) const {
454   return llvm::ConstantPointerNull::get(T);
455 }
456 
457 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
458                                                    const VarDecl *D) const {
459   assert(!CGM.getLangOpts().OpenCL &&
460          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
461          "Address space agnostic languages only");
462   return D ? D->getType().getAddressSpace() : LangAS::Default;
463 }
464 
465 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
466     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
467     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
468   // Since target may map different address spaces in AST to the same address
469   // space, an address space conversion may end up as a bitcast.
470   if (auto *C = dyn_cast<llvm::Constant>(Src))
471     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
472   // Try to preserve the source's name to make IR more readable.
473   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
474       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
475 }
476 
477 llvm::Constant *
478 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
479                                         LangAS SrcAddr, LangAS DestAddr,
480                                         llvm::Type *DestTy) const {
481   // Since target may map different address spaces in AST to the same address
482   // space, an address space conversion may end up as a bitcast.
483   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
484 }
485 
486 llvm::SyncScope::ID
487 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
488                                       SyncScope Scope,
489                                       llvm::AtomicOrdering Ordering,
490                                       llvm::LLVMContext &Ctx) const {
491   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
492 }
493 
494 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
495 
496 /// isEmptyField - Return true iff a the field is "empty", that is it
497 /// is an unnamed bit-field or an (array of) empty record(s).
498 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
499                          bool AllowArrays) {
500   if (FD->isUnnamedBitfield())
501     return true;
502 
503   QualType FT = FD->getType();
504 
505   // Constant arrays of empty records count as empty, strip them off.
506   // Constant arrays of zero length always count as empty.
507   bool WasArray = false;
508   if (AllowArrays)
509     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
510       if (AT->getSize() == 0)
511         return true;
512       FT = AT->getElementType();
513       // The [[no_unique_address]] special case below does not apply to
514       // arrays of C++ empty records, so we need to remember this fact.
515       WasArray = true;
516     }
517 
518   const RecordType *RT = FT->getAs<RecordType>();
519   if (!RT)
520     return false;
521 
522   // C++ record fields are never empty, at least in the Itanium ABI.
523   //
524   // FIXME: We should use a predicate for whether this behavior is true in the
525   // current ABI.
526   //
527   // The exception to the above rule are fields marked with the
528   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
529   // according to the Itanium ABI.  The exception applies only to records,
530   // not arrays of records, so we must also check whether we stripped off an
531   // array type above.
532   if (isa<CXXRecordDecl>(RT->getDecl()) &&
533       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
534     return false;
535 
536   return isEmptyRecord(Context, FT, AllowArrays);
537 }
538 
539 /// isEmptyRecord - Return true iff a structure contains only empty
540 /// fields. Note that a structure with a flexible array member is not
541 /// considered empty.
542 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
543   const RecordType *RT = T->getAs<RecordType>();
544   if (!RT)
545     return false;
546   const RecordDecl *RD = RT->getDecl();
547   if (RD->hasFlexibleArrayMember())
548     return false;
549 
550   // If this is a C++ record, check the bases first.
551   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
552     for (const auto &I : CXXRD->bases())
553       if (!isEmptyRecord(Context, I.getType(), true))
554         return false;
555 
556   for (const auto *I : RD->fields())
557     if (!isEmptyField(Context, I, AllowArrays))
558       return false;
559   return true;
560 }
561 
562 /// isSingleElementStruct - Determine if a structure is a "single
563 /// element struct", i.e. it has exactly one non-empty field or
564 /// exactly one field which is itself a single element
565 /// struct. Structures with flexible array members are never
566 /// considered single element structs.
567 ///
568 /// \return The field declaration for the single non-empty field, if
569 /// it exists.
570 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
571   const RecordType *RT = T->getAs<RecordType>();
572   if (!RT)
573     return nullptr;
574 
575   const RecordDecl *RD = RT->getDecl();
576   if (RD->hasFlexibleArrayMember())
577     return nullptr;
578 
579   const Type *Found = nullptr;
580 
581   // If this is a C++ record, check the bases first.
582   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
583     for (const auto &I : CXXRD->bases()) {
584       // Ignore empty records.
585       if (isEmptyRecord(Context, I.getType(), true))
586         continue;
587 
588       // If we already found an element then this isn't a single-element struct.
589       if (Found)
590         return nullptr;
591 
592       // If this is non-empty and not a single element struct, the composite
593       // cannot be a single element struct.
594       Found = isSingleElementStruct(I.getType(), Context);
595       if (!Found)
596         return nullptr;
597     }
598   }
599 
600   // Check for single element.
601   for (const auto *FD : RD->fields()) {
602     QualType FT = FD->getType();
603 
604     // Ignore empty fields.
605     if (isEmptyField(Context, FD, true))
606       continue;
607 
608     // If we already found an element then this isn't a single-element
609     // struct.
610     if (Found)
611       return nullptr;
612 
613     // Treat single element arrays as the element.
614     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
615       if (AT->getSize().getZExtValue() != 1)
616         break;
617       FT = AT->getElementType();
618     }
619 
620     if (!isAggregateTypeForABI(FT)) {
621       Found = FT.getTypePtr();
622     } else {
623       Found = isSingleElementStruct(FT, Context);
624       if (!Found)
625         return nullptr;
626     }
627   }
628 
629   // We don't consider a struct a single-element struct if it has
630   // padding beyond the element type.
631   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
632     return nullptr;
633 
634   return Found;
635 }
636 
637 namespace {
638 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
639                        const ABIArgInfo &AI) {
640   // This default implementation defers to the llvm backend's va_arg
641   // instruction. It can handle only passing arguments directly
642   // (typically only handled in the backend for primitive types), or
643   // aggregates passed indirectly by pointer (NOTE: if the "byval"
644   // flag has ABI impact in the callee, this implementation cannot
645   // work.)
646 
647   // Only a few cases are covered here at the moment -- those needed
648   // by the default abi.
649   llvm::Value *Val;
650 
651   if (AI.isIndirect()) {
652     assert(!AI.getPaddingType() &&
653            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
654     assert(
655         !AI.getIndirectRealign() &&
656         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
657 
658     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
659     CharUnits TyAlignForABI = TyInfo.Align;
660 
661     llvm::Type *BaseTy =
662         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
663     llvm::Value *Addr =
664         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
665     return Address(Addr, TyAlignForABI);
666   } else {
667     assert((AI.isDirect() || AI.isExtend()) &&
668            "Unexpected ArgInfo Kind in generic VAArg emitter!");
669 
670     assert(!AI.getInReg() &&
671            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
672     assert(!AI.getPaddingType() &&
673            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
674     assert(!AI.getDirectOffset() &&
675            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
676     assert(!AI.getCoerceToType() &&
677            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
678 
679     Address Temp = CGF.CreateMemTemp(Ty, "varet");
680     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
681     CGF.Builder.CreateStore(Val, Temp);
682     return Temp;
683   }
684 }
685 
686 /// DefaultABIInfo - The default implementation for ABI specific
687 /// details. This implementation provides information which results in
688 /// self-consistent and sensible LLVM IR generation, but does not
689 /// conform to any particular ABI.
690 class DefaultABIInfo : public ABIInfo {
691 public:
692   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
693 
694   ABIArgInfo classifyReturnType(QualType RetTy) const;
695   ABIArgInfo classifyArgumentType(QualType RetTy) const;
696 
697   void computeInfo(CGFunctionInfo &FI) const override {
698     if (!getCXXABI().classifyReturnType(FI))
699       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
700     for (auto &I : FI.arguments())
701       I.info = classifyArgumentType(I.type);
702   }
703 
704   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
705                     QualType Ty) const override {
706     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
707   }
708 };
709 
710 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
711 public:
712   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
713       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
714 };
715 
716 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
717   Ty = useFirstFieldIfTransparentUnion(Ty);
718 
719   if (isAggregateTypeForABI(Ty)) {
720     // Records with non-trivial destructors/copy-constructors should not be
721     // passed by value.
722     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
723       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
724 
725     return getNaturalAlignIndirect(Ty);
726   }
727 
728   // Treat an enum type as its underlying type.
729   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
730     Ty = EnumTy->getDecl()->getIntegerType();
731 
732   ASTContext &Context = getContext();
733   if (const auto *EIT = Ty->getAs<ExtIntType>())
734     if (EIT->getNumBits() >
735         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
736                                 ? Context.Int128Ty
737                                 : Context.LongLongTy))
738       return getNaturalAlignIndirect(Ty);
739 
740   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
741                                             : ABIArgInfo::getDirect());
742 }
743 
744 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
745   if (RetTy->isVoidType())
746     return ABIArgInfo::getIgnore();
747 
748   if (isAggregateTypeForABI(RetTy))
749     return getNaturalAlignIndirect(RetTy);
750 
751   // Treat an enum type as its underlying type.
752   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
753     RetTy = EnumTy->getDecl()->getIntegerType();
754 
755   if (const auto *EIT = RetTy->getAs<ExtIntType>())
756     if (EIT->getNumBits() >
757         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
758                                      ? getContext().Int128Ty
759                                      : getContext().LongLongTy))
760       return getNaturalAlignIndirect(RetTy);
761 
762   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
763                                                : ABIArgInfo::getDirect());
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // WebAssembly ABI Implementation
768 //
769 // This is a very simple ABI that relies a lot on DefaultABIInfo.
770 //===----------------------------------------------------------------------===//
771 
772 class WebAssemblyABIInfo final : public SwiftABIInfo {
773 public:
774   enum ABIKind {
775     MVP = 0,
776     ExperimentalMV = 1,
777   };
778 
779 private:
780   DefaultABIInfo defaultInfo;
781   ABIKind Kind;
782 
783 public:
784   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
785       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
786 
787 private:
788   ABIArgInfo classifyReturnType(QualType RetTy) const;
789   ABIArgInfo classifyArgumentType(QualType Ty) const;
790 
791   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
792   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
793   // overload them.
794   void computeInfo(CGFunctionInfo &FI) const override {
795     if (!getCXXABI().classifyReturnType(FI))
796       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
797     for (auto &Arg : FI.arguments())
798       Arg.info = classifyArgumentType(Arg.type);
799   }
800 
801   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
802                     QualType Ty) const override;
803 
804   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
805                                     bool asReturnValue) const override {
806     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
807   }
808 
809   bool isSwiftErrorInRegister() const override {
810     return false;
811   }
812 };
813 
814 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
815 public:
816   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
817                                         WebAssemblyABIInfo::ABIKind K)
818       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
819 
820   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
821                            CodeGen::CodeGenModule &CGM) const override {
822     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
823     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
824       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
825         llvm::Function *Fn = cast<llvm::Function>(GV);
826         llvm::AttrBuilder B;
827         B.addAttribute("wasm-import-module", Attr->getImportModule());
828         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
829       }
830       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
831         llvm::Function *Fn = cast<llvm::Function>(GV);
832         llvm::AttrBuilder B;
833         B.addAttribute("wasm-import-name", Attr->getImportName());
834         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
835       }
836       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
837         llvm::Function *Fn = cast<llvm::Function>(GV);
838         llvm::AttrBuilder B;
839         B.addAttribute("wasm-export-name", Attr->getExportName());
840         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
841       }
842     }
843 
844     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
845       llvm::Function *Fn = cast<llvm::Function>(GV);
846       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
847         Fn->addFnAttr("no-prototype");
848     }
849   }
850 };
851 
852 /// Classify argument of given type \p Ty.
853 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
854   Ty = useFirstFieldIfTransparentUnion(Ty);
855 
856   if (isAggregateTypeForABI(Ty)) {
857     // Records with non-trivial destructors/copy-constructors should not be
858     // passed by value.
859     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
860       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
861     // Ignore empty structs/unions.
862     if (isEmptyRecord(getContext(), Ty, true))
863       return ABIArgInfo::getIgnore();
864     // Lower single-element structs to just pass a regular value. TODO: We
865     // could do reasonable-size multiple-element structs too, using getExpand(),
866     // though watch out for things like bitfields.
867     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
868       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
869     // For the experimental multivalue ABI, fully expand all other aggregates
870     if (Kind == ABIKind::ExperimentalMV) {
871       const RecordType *RT = Ty->getAs<RecordType>();
872       assert(RT);
873       bool HasBitField = false;
874       for (auto *Field : RT->getDecl()->fields()) {
875         if (Field->isBitField()) {
876           HasBitField = true;
877           break;
878         }
879       }
880       if (!HasBitField)
881         return ABIArgInfo::getExpand();
882     }
883   }
884 
885   // Otherwise just do the default thing.
886   return defaultInfo.classifyArgumentType(Ty);
887 }
888 
889 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
890   if (isAggregateTypeForABI(RetTy)) {
891     // Records with non-trivial destructors/copy-constructors should not be
892     // returned by value.
893     if (!getRecordArgABI(RetTy, getCXXABI())) {
894       // Ignore empty structs/unions.
895       if (isEmptyRecord(getContext(), RetTy, true))
896         return ABIArgInfo::getIgnore();
897       // Lower single-element structs to just return a regular value. TODO: We
898       // could do reasonable-size multiple-element structs too, using
899       // ABIArgInfo::getDirect().
900       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
901         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
902       // For the experimental multivalue ABI, return all other aggregates
903       if (Kind == ABIKind::ExperimentalMV)
904         return ABIArgInfo::getDirect();
905     }
906   }
907 
908   // Otherwise just do the default thing.
909   return defaultInfo.classifyReturnType(RetTy);
910 }
911 
912 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
913                                       QualType Ty) const {
914   bool IsIndirect = isAggregateTypeForABI(Ty) &&
915                     !isEmptyRecord(getContext(), Ty, true) &&
916                     !isSingleElementStruct(Ty, getContext());
917   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
918                           getContext().getTypeInfoInChars(Ty),
919                           CharUnits::fromQuantity(4),
920                           /*AllowHigherAlign=*/true);
921 }
922 
923 //===----------------------------------------------------------------------===//
924 // le32/PNaCl bitcode ABI Implementation
925 //
926 // This is a simplified version of the x86_32 ABI.  Arguments and return values
927 // are always passed on the stack.
928 //===----------------------------------------------------------------------===//
929 
930 class PNaClABIInfo : public ABIInfo {
931  public:
932   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
933 
934   ABIArgInfo classifyReturnType(QualType RetTy) const;
935   ABIArgInfo classifyArgumentType(QualType RetTy) const;
936 
937   void computeInfo(CGFunctionInfo &FI) const override;
938   Address EmitVAArg(CodeGenFunction &CGF,
939                     Address VAListAddr, QualType Ty) const override;
940 };
941 
942 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
943  public:
944    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
945        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
946 };
947 
948 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
949   if (!getCXXABI().classifyReturnType(FI))
950     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
951 
952   for (auto &I : FI.arguments())
953     I.info = classifyArgumentType(I.type);
954 }
955 
956 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
957                                 QualType Ty) const {
958   // The PNaCL ABI is a bit odd, in that varargs don't use normal
959   // function classification. Structs get passed directly for varargs
960   // functions, through a rewriting transform in
961   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
962   // this target to actually support a va_arg instructions with an
963   // aggregate type, unlike other targets.
964   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
965 }
966 
967 /// Classify argument of given type \p Ty.
968 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
969   if (isAggregateTypeForABI(Ty)) {
970     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
971       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
972     return getNaturalAlignIndirect(Ty);
973   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
974     // Treat an enum type as its underlying type.
975     Ty = EnumTy->getDecl()->getIntegerType();
976   } else if (Ty->isFloatingType()) {
977     // Floating-point types don't go inreg.
978     return ABIArgInfo::getDirect();
979   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
980     // Treat extended integers as integers if <=64, otherwise pass indirectly.
981     if (EIT->getNumBits() > 64)
982       return getNaturalAlignIndirect(Ty);
983     return ABIArgInfo::getDirect();
984   }
985 
986   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
987                                             : ABIArgInfo::getDirect());
988 }
989 
990 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
991   if (RetTy->isVoidType())
992     return ABIArgInfo::getIgnore();
993 
994   // In the PNaCl ABI we always return records/structures on the stack.
995   if (isAggregateTypeForABI(RetTy))
996     return getNaturalAlignIndirect(RetTy);
997 
998   // Treat extended integers as integers if <=64, otherwise pass indirectly.
999   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
1000     if (EIT->getNumBits() > 64)
1001       return getNaturalAlignIndirect(RetTy);
1002     return ABIArgInfo::getDirect();
1003   }
1004 
1005   // Treat an enum type as its underlying type.
1006   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1007     RetTy = EnumTy->getDecl()->getIntegerType();
1008 
1009   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1010                                                : ABIArgInfo::getDirect());
1011 }
1012 
1013 /// IsX86_MMXType - Return true if this is an MMX type.
1014 bool IsX86_MMXType(llvm::Type *IRType) {
1015   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1016   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1017     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1018     IRType->getScalarSizeInBits() != 64;
1019 }
1020 
1021 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1022                                           StringRef Constraint,
1023                                           llvm::Type* Ty) {
1024   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1025                      .Cases("y", "&y", "^Ym", true)
1026                      .Default(false);
1027   if (IsMMXCons && Ty->isVectorTy()) {
1028     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1029         64) {
1030       // Invalid MMX constraint
1031       return nullptr;
1032     }
1033 
1034     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1035   }
1036 
1037   // No operation needed
1038   return Ty;
1039 }
1040 
1041 /// Returns true if this type can be passed in SSE registers with the
1042 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1043 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1044   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1045     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1046       if (BT->getKind() == BuiltinType::LongDouble) {
1047         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1048             &llvm::APFloat::x87DoubleExtended())
1049           return false;
1050       }
1051       return true;
1052     }
1053   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1054     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1055     // registers specially.
1056     unsigned VecSize = Context.getTypeSize(VT);
1057     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1058       return true;
1059   }
1060   return false;
1061 }
1062 
1063 /// Returns true if this aggregate is small enough to be passed in SSE registers
1064 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1065 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1066   return NumMembers <= 4;
1067 }
1068 
1069 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1070 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1071   auto AI = ABIArgInfo::getDirect(T);
1072   AI.setInReg(true);
1073   AI.setCanBeFlattened(false);
1074   return AI;
1075 }
1076 
1077 //===----------------------------------------------------------------------===//
1078 // X86-32 ABI Implementation
1079 //===----------------------------------------------------------------------===//
1080 
1081 /// Similar to llvm::CCState, but for Clang.
1082 struct CCState {
1083   CCState(CGFunctionInfo &FI)
1084       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1085 
1086   llvm::SmallBitVector IsPreassigned;
1087   unsigned CC = CallingConv::CC_C;
1088   unsigned FreeRegs = 0;
1089   unsigned FreeSSERegs = 0;
1090 };
1091 
1092 enum {
1093   // Vectorcall only allows the first 6 parameters to be passed in registers.
1094   VectorcallMaxParamNumAsReg = 6
1095 };
1096 
1097 /// X86_32ABIInfo - The X86-32 ABI information.
1098 class X86_32ABIInfo : public SwiftABIInfo {
1099   enum Class {
1100     Integer,
1101     Float
1102   };
1103 
1104   static const unsigned MinABIStackAlignInBytes = 4;
1105 
1106   bool IsDarwinVectorABI;
1107   bool IsRetSmallStructInRegABI;
1108   bool IsWin32StructABI;
1109   bool IsSoftFloatABI;
1110   bool IsMCUABI;
1111   unsigned DefaultNumRegisterParameters;
1112 
1113   static bool isRegisterSize(unsigned Size) {
1114     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1115   }
1116 
1117   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1118     // FIXME: Assumes vectorcall is in use.
1119     return isX86VectorTypeForVectorCall(getContext(), Ty);
1120   }
1121 
1122   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1123                                          uint64_t NumMembers) const override {
1124     // FIXME: Assumes vectorcall is in use.
1125     return isX86VectorCallAggregateSmallEnough(NumMembers);
1126   }
1127 
1128   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1129 
1130   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1131   /// such that the argument will be passed in memory.
1132   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1133 
1134   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1135 
1136   /// Return the alignment to use for the given type on the stack.
1137   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1138 
1139   Class classify(QualType Ty) const;
1140   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1141   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1142 
1143   /// Updates the number of available free registers, returns
1144   /// true if any registers were allocated.
1145   bool updateFreeRegs(QualType Ty, CCState &State) const;
1146 
1147   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1148                                 bool &NeedsPadding) const;
1149   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1150 
1151   bool canExpandIndirectArgument(QualType Ty) const;
1152 
1153   /// Rewrite the function info so that all memory arguments use
1154   /// inalloca.
1155   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1156 
1157   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1158                            CharUnits &StackOffset, ABIArgInfo &Info,
1159                            QualType Type) const;
1160   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1161 
1162 public:
1163 
1164   void computeInfo(CGFunctionInfo &FI) const override;
1165   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1166                     QualType Ty) const override;
1167 
1168   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1169                 bool RetSmallStructInRegABI, bool Win32StructABI,
1170                 unsigned NumRegisterParameters, bool SoftFloatABI)
1171     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1172       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1173       IsWin32StructABI(Win32StructABI),
1174       IsSoftFloatABI(SoftFloatABI),
1175       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1176       DefaultNumRegisterParameters(NumRegisterParameters) {}
1177 
1178   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1179                                     bool asReturnValue) const override {
1180     // LLVM's x86-32 lowering currently only assigns up to three
1181     // integer registers and three fp registers.  Oddly, it'll use up to
1182     // four vector registers for vectors, but those can overlap with the
1183     // scalar registers.
1184     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1185   }
1186 
1187   bool isSwiftErrorInRegister() const override {
1188     // x86-32 lowering does not support passing swifterror in a register.
1189     return false;
1190   }
1191 };
1192 
1193 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1194 public:
1195   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1196                           bool RetSmallStructInRegABI, bool Win32StructABI,
1197                           unsigned NumRegisterParameters, bool SoftFloatABI)
1198       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1199             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1200             NumRegisterParameters, SoftFloatABI)) {}
1201 
1202   static bool isStructReturnInRegABI(
1203       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1204 
1205   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1206                            CodeGen::CodeGenModule &CGM) const override;
1207 
1208   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1209     // Darwin uses different dwarf register numbers for EH.
1210     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1211     return 4;
1212   }
1213 
1214   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1215                                llvm::Value *Address) const override;
1216 
1217   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1218                                   StringRef Constraint,
1219                                   llvm::Type* Ty) const override {
1220     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1221   }
1222 
1223   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1224                                 std::string &Constraints,
1225                                 std::vector<llvm::Type *> &ResultRegTypes,
1226                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1227                                 std::vector<LValue> &ResultRegDests,
1228                                 std::string &AsmString,
1229                                 unsigned NumOutputs) const override;
1230 
1231   llvm::Constant *
1232   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1233     unsigned Sig = (0xeb << 0) |  // jmp rel8
1234                    (0x06 << 8) |  //           .+0x08
1235                    ('v' << 16) |
1236                    ('2' << 24);
1237     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1238   }
1239 
1240   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1241     return "movl\t%ebp, %ebp"
1242            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1243   }
1244 };
1245 
1246 }
1247 
1248 /// Rewrite input constraint references after adding some output constraints.
1249 /// In the case where there is one output and one input and we add one output,
1250 /// we need to replace all operand references greater than or equal to 1:
1251 ///     mov $0, $1
1252 ///     mov eax, $1
1253 /// The result will be:
1254 ///     mov $0, $2
1255 ///     mov eax, $2
1256 static void rewriteInputConstraintReferences(unsigned FirstIn,
1257                                              unsigned NumNewOuts,
1258                                              std::string &AsmString) {
1259   std::string Buf;
1260   llvm::raw_string_ostream OS(Buf);
1261   size_t Pos = 0;
1262   while (Pos < AsmString.size()) {
1263     size_t DollarStart = AsmString.find('$', Pos);
1264     if (DollarStart == std::string::npos)
1265       DollarStart = AsmString.size();
1266     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1267     if (DollarEnd == std::string::npos)
1268       DollarEnd = AsmString.size();
1269     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1270     Pos = DollarEnd;
1271     size_t NumDollars = DollarEnd - DollarStart;
1272     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1273       // We have an operand reference.
1274       size_t DigitStart = Pos;
1275       if (AsmString[DigitStart] == '{') {
1276         OS << '{';
1277         ++DigitStart;
1278       }
1279       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1280       if (DigitEnd == std::string::npos)
1281         DigitEnd = AsmString.size();
1282       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1283       unsigned OperandIndex;
1284       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1285         if (OperandIndex >= FirstIn)
1286           OperandIndex += NumNewOuts;
1287         OS << OperandIndex;
1288       } else {
1289         OS << OperandStr;
1290       }
1291       Pos = DigitEnd;
1292     }
1293   }
1294   AsmString = std::move(OS.str());
1295 }
1296 
1297 /// Add output constraints for EAX:EDX because they are return registers.
1298 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1299     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1300     std::vector<llvm::Type *> &ResultRegTypes,
1301     std::vector<llvm::Type *> &ResultTruncRegTypes,
1302     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1303     unsigned NumOutputs) const {
1304   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1305 
1306   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1307   // larger.
1308   if (!Constraints.empty())
1309     Constraints += ',';
1310   if (RetWidth <= 32) {
1311     Constraints += "={eax}";
1312     ResultRegTypes.push_back(CGF.Int32Ty);
1313   } else {
1314     // Use the 'A' constraint for EAX:EDX.
1315     Constraints += "=A";
1316     ResultRegTypes.push_back(CGF.Int64Ty);
1317   }
1318 
1319   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1320   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1321   ResultTruncRegTypes.push_back(CoerceTy);
1322 
1323   // Coerce the integer by bitcasting the return slot pointer.
1324   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1325                                                   CoerceTy->getPointerTo()));
1326   ResultRegDests.push_back(ReturnSlot);
1327 
1328   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1329 }
1330 
1331 /// shouldReturnTypeInRegister - Determine if the given type should be
1332 /// returned in a register (for the Darwin and MCU ABI).
1333 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1334                                                ASTContext &Context) const {
1335   uint64_t Size = Context.getTypeSize(Ty);
1336 
1337   // For i386, type must be register sized.
1338   // For the MCU ABI, it only needs to be <= 8-byte
1339   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1340    return false;
1341 
1342   if (Ty->isVectorType()) {
1343     // 64- and 128- bit vectors inside structures are not returned in
1344     // registers.
1345     if (Size == 64 || Size == 128)
1346       return false;
1347 
1348     return true;
1349   }
1350 
1351   // If this is a builtin, pointer, enum, complex type, member pointer, or
1352   // member function pointer it is ok.
1353   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1354       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1355       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1356     return true;
1357 
1358   // Arrays are treated like records.
1359   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1360     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1361 
1362   // Otherwise, it must be a record type.
1363   const RecordType *RT = Ty->getAs<RecordType>();
1364   if (!RT) return false;
1365 
1366   // FIXME: Traverse bases here too.
1367 
1368   // Structure types are passed in register if all fields would be
1369   // passed in a register.
1370   for (const auto *FD : RT->getDecl()->fields()) {
1371     // Empty fields are ignored.
1372     if (isEmptyField(Context, FD, true))
1373       continue;
1374 
1375     // Check fields recursively.
1376     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1377       return false;
1378   }
1379   return true;
1380 }
1381 
1382 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1383   // Treat complex types as the element type.
1384   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1385     Ty = CTy->getElementType();
1386 
1387   // Check for a type which we know has a simple scalar argument-passing
1388   // convention without any padding.  (We're specifically looking for 32
1389   // and 64-bit integer and integer-equivalents, float, and double.)
1390   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1391       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1392     return false;
1393 
1394   uint64_t Size = Context.getTypeSize(Ty);
1395   return Size == 32 || Size == 64;
1396 }
1397 
1398 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1399                           uint64_t &Size) {
1400   for (const auto *FD : RD->fields()) {
1401     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1402     // argument is smaller than 32-bits, expanding the struct will create
1403     // alignment padding.
1404     if (!is32Or64BitBasicType(FD->getType(), Context))
1405       return false;
1406 
1407     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1408     // how to expand them yet, and the predicate for telling if a bitfield still
1409     // counts as "basic" is more complicated than what we were doing previously.
1410     if (FD->isBitField())
1411       return false;
1412 
1413     Size += Context.getTypeSize(FD->getType());
1414   }
1415   return true;
1416 }
1417 
1418 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1419                                  uint64_t &Size) {
1420   // Don't do this if there are any non-empty bases.
1421   for (const CXXBaseSpecifier &Base : RD->bases()) {
1422     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1423                               Size))
1424       return false;
1425   }
1426   if (!addFieldSizes(Context, RD, Size))
1427     return false;
1428   return true;
1429 }
1430 
1431 /// Test whether an argument type which is to be passed indirectly (on the
1432 /// stack) would have the equivalent layout if it was expanded into separate
1433 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1434 /// optimizations.
1435 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1436   // We can only expand structure types.
1437   const RecordType *RT = Ty->getAs<RecordType>();
1438   if (!RT)
1439     return false;
1440   const RecordDecl *RD = RT->getDecl();
1441   uint64_t Size = 0;
1442   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1443     if (!IsWin32StructABI) {
1444       // On non-Windows, we have to conservatively match our old bitcode
1445       // prototypes in order to be ABI-compatible at the bitcode level.
1446       if (!CXXRD->isCLike())
1447         return false;
1448     } else {
1449       // Don't do this for dynamic classes.
1450       if (CXXRD->isDynamicClass())
1451         return false;
1452     }
1453     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1454       return false;
1455   } else {
1456     if (!addFieldSizes(getContext(), RD, Size))
1457       return false;
1458   }
1459 
1460   // We can do this if there was no alignment padding.
1461   return Size == getContext().getTypeSize(Ty);
1462 }
1463 
1464 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1465   // If the return value is indirect, then the hidden argument is consuming one
1466   // integer register.
1467   if (State.FreeRegs) {
1468     --State.FreeRegs;
1469     if (!IsMCUABI)
1470       return getNaturalAlignIndirectInReg(RetTy);
1471   }
1472   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1473 }
1474 
1475 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1476                                              CCState &State) const {
1477   if (RetTy->isVoidType())
1478     return ABIArgInfo::getIgnore();
1479 
1480   const Type *Base = nullptr;
1481   uint64_t NumElts = 0;
1482   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1483        State.CC == llvm::CallingConv::X86_RegCall) &&
1484       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1485     // The LLVM struct type for such an aggregate should lower properly.
1486     return ABIArgInfo::getDirect();
1487   }
1488 
1489   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1490     // On Darwin, some vectors are returned in registers.
1491     if (IsDarwinVectorABI) {
1492       uint64_t Size = getContext().getTypeSize(RetTy);
1493 
1494       // 128-bit vectors are a special case; they are returned in
1495       // registers and we need to make sure to pick a type the LLVM
1496       // backend will like.
1497       if (Size == 128)
1498         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1499             llvm::Type::getInt64Ty(getVMContext()), 2));
1500 
1501       // Always return in register if it fits in a general purpose
1502       // register, or if it is 64 bits and has a single element.
1503       if ((Size == 8 || Size == 16 || Size == 32) ||
1504           (Size == 64 && VT->getNumElements() == 1))
1505         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1506                                                             Size));
1507 
1508       return getIndirectReturnResult(RetTy, State);
1509     }
1510 
1511     return ABIArgInfo::getDirect();
1512   }
1513 
1514   if (isAggregateTypeForABI(RetTy)) {
1515     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1516       // Structures with flexible arrays are always indirect.
1517       if (RT->getDecl()->hasFlexibleArrayMember())
1518         return getIndirectReturnResult(RetTy, State);
1519     }
1520 
1521     // If specified, structs and unions are always indirect.
1522     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1523       return getIndirectReturnResult(RetTy, State);
1524 
1525     // Ignore empty structs/unions.
1526     if (isEmptyRecord(getContext(), RetTy, true))
1527       return ABIArgInfo::getIgnore();
1528 
1529     // Small structures which are register sized are generally returned
1530     // in a register.
1531     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1532       uint64_t Size = getContext().getTypeSize(RetTy);
1533 
1534       // As a special-case, if the struct is a "single-element" struct, and
1535       // the field is of type "float" or "double", return it in a
1536       // floating-point register. (MSVC does not apply this special case.)
1537       // We apply a similar transformation for pointer types to improve the
1538       // quality of the generated IR.
1539       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1540         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1541             || SeltTy->hasPointerRepresentation())
1542           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1543 
1544       // FIXME: We should be able to narrow this integer in cases with dead
1545       // padding.
1546       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1547     }
1548 
1549     return getIndirectReturnResult(RetTy, State);
1550   }
1551 
1552   // Treat an enum type as its underlying type.
1553   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1554     RetTy = EnumTy->getDecl()->getIntegerType();
1555 
1556   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1557     if (EIT->getNumBits() > 64)
1558       return getIndirectReturnResult(RetTy, State);
1559 
1560   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1561                                                : ABIArgInfo::getDirect());
1562 }
1563 
1564 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1565   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1566 }
1567 
1568 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1569   const RecordType *RT = Ty->getAs<RecordType>();
1570   if (!RT)
1571     return 0;
1572   const RecordDecl *RD = RT->getDecl();
1573 
1574   // If this is a C++ record, check the bases first.
1575   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1576     for (const auto &I : CXXRD->bases())
1577       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1578         return false;
1579 
1580   for (const auto *i : RD->fields()) {
1581     QualType FT = i->getType();
1582 
1583     if (isSIMDVectorType(Context, FT))
1584       return true;
1585 
1586     if (isRecordWithSIMDVectorType(Context, FT))
1587       return true;
1588   }
1589 
1590   return false;
1591 }
1592 
1593 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1594                                                  unsigned Align) const {
1595   // Otherwise, if the alignment is less than or equal to the minimum ABI
1596   // alignment, just use the default; the backend will handle this.
1597   if (Align <= MinABIStackAlignInBytes)
1598     return 0; // Use default alignment.
1599 
1600   // On non-Darwin, the stack type alignment is always 4.
1601   if (!IsDarwinVectorABI) {
1602     // Set explicit alignment, since we may need to realign the top.
1603     return MinABIStackAlignInBytes;
1604   }
1605 
1606   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1607   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1608                       isRecordWithSIMDVectorType(getContext(), Ty)))
1609     return 16;
1610 
1611   return MinABIStackAlignInBytes;
1612 }
1613 
1614 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1615                                             CCState &State) const {
1616   if (!ByVal) {
1617     if (State.FreeRegs) {
1618       --State.FreeRegs; // Non-byval indirects just use one pointer.
1619       if (!IsMCUABI)
1620         return getNaturalAlignIndirectInReg(Ty);
1621     }
1622     return getNaturalAlignIndirect(Ty, false);
1623   }
1624 
1625   // Compute the byval alignment.
1626   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1627   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1628   if (StackAlign == 0)
1629     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1630 
1631   // If the stack alignment is less than the type alignment, realign the
1632   // argument.
1633   bool Realign = TypeAlign > StackAlign;
1634   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1635                                  /*ByVal=*/true, Realign);
1636 }
1637 
1638 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1639   const Type *T = isSingleElementStruct(Ty, getContext());
1640   if (!T)
1641     T = Ty.getTypePtr();
1642 
1643   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1644     BuiltinType::Kind K = BT->getKind();
1645     if (K == BuiltinType::Float || K == BuiltinType::Double)
1646       return Float;
1647   }
1648   return Integer;
1649 }
1650 
1651 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1652   if (!IsSoftFloatABI) {
1653     Class C = classify(Ty);
1654     if (C == Float)
1655       return false;
1656   }
1657 
1658   unsigned Size = getContext().getTypeSize(Ty);
1659   unsigned SizeInRegs = (Size + 31) / 32;
1660 
1661   if (SizeInRegs == 0)
1662     return false;
1663 
1664   if (!IsMCUABI) {
1665     if (SizeInRegs > State.FreeRegs) {
1666       State.FreeRegs = 0;
1667       return false;
1668     }
1669   } else {
1670     // The MCU psABI allows passing parameters in-reg even if there are
1671     // earlier parameters that are passed on the stack. Also,
1672     // it does not allow passing >8-byte structs in-register,
1673     // even if there are 3 free registers available.
1674     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1675       return false;
1676   }
1677 
1678   State.FreeRegs -= SizeInRegs;
1679   return true;
1680 }
1681 
1682 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1683                                              bool &InReg,
1684                                              bool &NeedsPadding) const {
1685   // On Windows, aggregates other than HFAs are never passed in registers, and
1686   // they do not consume register slots. Homogenous floating-point aggregates
1687   // (HFAs) have already been dealt with at this point.
1688   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1689     return false;
1690 
1691   NeedsPadding = false;
1692   InReg = !IsMCUABI;
1693 
1694   if (!updateFreeRegs(Ty, State))
1695     return false;
1696 
1697   if (IsMCUABI)
1698     return true;
1699 
1700   if (State.CC == llvm::CallingConv::X86_FastCall ||
1701       State.CC == llvm::CallingConv::X86_VectorCall ||
1702       State.CC == llvm::CallingConv::X86_RegCall) {
1703     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1704       NeedsPadding = true;
1705 
1706     return false;
1707   }
1708 
1709   return true;
1710 }
1711 
1712 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1713   if (!updateFreeRegs(Ty, State))
1714     return false;
1715 
1716   if (IsMCUABI)
1717     return false;
1718 
1719   if (State.CC == llvm::CallingConv::X86_FastCall ||
1720       State.CC == llvm::CallingConv::X86_VectorCall ||
1721       State.CC == llvm::CallingConv::X86_RegCall) {
1722     if (getContext().getTypeSize(Ty) > 32)
1723       return false;
1724 
1725     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1726         Ty->isReferenceType());
1727   }
1728 
1729   return true;
1730 }
1731 
1732 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1733   // Vectorcall x86 works subtly different than in x64, so the format is
1734   // a bit different than the x64 version.  First, all vector types (not HVAs)
1735   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1736   // This differs from the x64 implementation, where the first 6 by INDEX get
1737   // registers.
1738   // In the second pass over the arguments, HVAs are passed in the remaining
1739   // vector registers if possible, or indirectly by address. The address will be
1740   // passed in ECX/EDX if available. Any other arguments are passed according to
1741   // the usual fastcall rules.
1742   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1743   for (int I = 0, E = Args.size(); I < E; ++I) {
1744     const Type *Base = nullptr;
1745     uint64_t NumElts = 0;
1746     const QualType &Ty = Args[I].type;
1747     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1748         isHomogeneousAggregate(Ty, Base, NumElts)) {
1749       if (State.FreeSSERegs >= NumElts) {
1750         State.FreeSSERegs -= NumElts;
1751         Args[I].info = ABIArgInfo::getDirectInReg();
1752         State.IsPreassigned.set(I);
1753       }
1754     }
1755   }
1756 }
1757 
1758 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1759                                                CCState &State) const {
1760   // FIXME: Set alignment on indirect arguments.
1761   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1762   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1763   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1764 
1765   Ty = useFirstFieldIfTransparentUnion(Ty);
1766   TypeInfo TI = getContext().getTypeInfo(Ty);
1767 
1768   // Check with the C++ ABI first.
1769   const RecordType *RT = Ty->getAs<RecordType>();
1770   if (RT) {
1771     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1772     if (RAA == CGCXXABI::RAA_Indirect) {
1773       return getIndirectResult(Ty, false, State);
1774     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1775       // The field index doesn't matter, we'll fix it up later.
1776       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1777     }
1778   }
1779 
1780   // Regcall uses the concept of a homogenous vector aggregate, similar
1781   // to other targets.
1782   const Type *Base = nullptr;
1783   uint64_t NumElts = 0;
1784   if ((IsRegCall || IsVectorCall) &&
1785       isHomogeneousAggregate(Ty, Base, NumElts)) {
1786     if (State.FreeSSERegs >= NumElts) {
1787       State.FreeSSERegs -= NumElts;
1788 
1789       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1790       // does.
1791       if (IsVectorCall)
1792         return getDirectX86Hva();
1793 
1794       if (Ty->isBuiltinType() || Ty->isVectorType())
1795         return ABIArgInfo::getDirect();
1796       return ABIArgInfo::getExpand();
1797     }
1798     return getIndirectResult(Ty, /*ByVal=*/false, State);
1799   }
1800 
1801   if (isAggregateTypeForABI(Ty)) {
1802     // Structures with flexible arrays are always indirect.
1803     // FIXME: This should not be byval!
1804     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1805       return getIndirectResult(Ty, true, State);
1806 
1807     // Ignore empty structs/unions on non-Windows.
1808     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1809       return ABIArgInfo::getIgnore();
1810 
1811     llvm::LLVMContext &LLVMContext = getVMContext();
1812     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1813     bool NeedsPadding = false;
1814     bool InReg;
1815     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1816       unsigned SizeInRegs = (TI.Width + 31) / 32;
1817       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1818       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1819       if (InReg)
1820         return ABIArgInfo::getDirectInReg(Result);
1821       else
1822         return ABIArgInfo::getDirect(Result);
1823     }
1824     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1825 
1826     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1827     // added in MSVC 2015.
1828     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1829       return getIndirectResult(Ty, /*ByVal=*/false, State);
1830 
1831     // Expand small (<= 128-bit) record types when we know that the stack layout
1832     // of those arguments will match the struct. This is important because the
1833     // LLVM backend isn't smart enough to remove byval, which inhibits many
1834     // optimizations.
1835     // Don't do this for the MCU if there are still free integer registers
1836     // (see X86_64 ABI for full explanation).
1837     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1838         canExpandIndirectArgument(Ty))
1839       return ABIArgInfo::getExpandWithPadding(
1840           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1841 
1842     return getIndirectResult(Ty, true, State);
1843   }
1844 
1845   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1846     // On Windows, vectors are passed directly if registers are available, or
1847     // indirectly if not. This avoids the need to align argument memory. Pass
1848     // user-defined vector types larger than 512 bits indirectly for simplicity.
1849     if (IsWin32StructABI) {
1850       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1851         --State.FreeSSERegs;
1852         return ABIArgInfo::getDirectInReg();
1853       }
1854       return getIndirectResult(Ty, /*ByVal=*/false, State);
1855     }
1856 
1857     // On Darwin, some vectors are passed in memory, we handle this by passing
1858     // it as an i8/i16/i32/i64.
1859     if (IsDarwinVectorABI) {
1860       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1861           (TI.Width == 64 && VT->getNumElements() == 1))
1862         return ABIArgInfo::getDirect(
1863             llvm::IntegerType::get(getVMContext(), TI.Width));
1864     }
1865 
1866     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1867       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1868 
1869     return ABIArgInfo::getDirect();
1870   }
1871 
1872 
1873   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1874     Ty = EnumTy->getDecl()->getIntegerType();
1875 
1876   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1877 
1878   if (isPromotableIntegerTypeForABI(Ty)) {
1879     if (InReg)
1880       return ABIArgInfo::getExtendInReg(Ty);
1881     return ABIArgInfo::getExtend(Ty);
1882   }
1883 
1884   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1885     if (EIT->getNumBits() <= 64) {
1886       if (InReg)
1887         return ABIArgInfo::getDirectInReg();
1888       return ABIArgInfo::getDirect();
1889     }
1890     return getIndirectResult(Ty, /*ByVal=*/false, State);
1891   }
1892 
1893   if (InReg)
1894     return ABIArgInfo::getDirectInReg();
1895   return ABIArgInfo::getDirect();
1896 }
1897 
1898 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1899   CCState State(FI);
1900   if (IsMCUABI)
1901     State.FreeRegs = 3;
1902   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1903     State.FreeRegs = 2;
1904     State.FreeSSERegs = 3;
1905   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1906     State.FreeRegs = 2;
1907     State.FreeSSERegs = 6;
1908   } else if (FI.getHasRegParm())
1909     State.FreeRegs = FI.getRegParm();
1910   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1911     State.FreeRegs = 5;
1912     State.FreeSSERegs = 8;
1913   } else if (IsWin32StructABI) {
1914     // Since MSVC 2015, the first three SSE vectors have been passed in
1915     // registers. The rest are passed indirectly.
1916     State.FreeRegs = DefaultNumRegisterParameters;
1917     State.FreeSSERegs = 3;
1918   } else
1919     State.FreeRegs = DefaultNumRegisterParameters;
1920 
1921   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1922     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1923   } else if (FI.getReturnInfo().isIndirect()) {
1924     // The C++ ABI is not aware of register usage, so we have to check if the
1925     // return value was sret and put it in a register ourselves if appropriate.
1926     if (State.FreeRegs) {
1927       --State.FreeRegs;  // The sret parameter consumes a register.
1928       if (!IsMCUABI)
1929         FI.getReturnInfo().setInReg(true);
1930     }
1931   }
1932 
1933   // The chain argument effectively gives us another free register.
1934   if (FI.isChainCall())
1935     ++State.FreeRegs;
1936 
1937   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1938   // arguments to XMM registers as available.
1939   if (State.CC == llvm::CallingConv::X86_VectorCall)
1940     runVectorCallFirstPass(FI, State);
1941 
1942   bool UsedInAlloca = false;
1943   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1944   for (int I = 0, E = Args.size(); I < E; ++I) {
1945     // Skip arguments that have already been assigned.
1946     if (State.IsPreassigned.test(I))
1947       continue;
1948 
1949     Args[I].info = classifyArgumentType(Args[I].type, State);
1950     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1951   }
1952 
1953   // If we needed to use inalloca for any argument, do a second pass and rewrite
1954   // all the memory arguments to use inalloca.
1955   if (UsedInAlloca)
1956     rewriteWithInAlloca(FI);
1957 }
1958 
1959 void
1960 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1961                                    CharUnits &StackOffset, ABIArgInfo &Info,
1962                                    QualType Type) const {
1963   // Arguments are always 4-byte-aligned.
1964   CharUnits WordSize = CharUnits::fromQuantity(4);
1965   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1966 
1967   // sret pointers and indirect things will require an extra pointer
1968   // indirection, unless they are byval. Most things are byval, and will not
1969   // require this indirection.
1970   bool IsIndirect = false;
1971   if (Info.isIndirect() && !Info.getIndirectByVal())
1972     IsIndirect = true;
1973   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1974   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1975   if (IsIndirect)
1976     LLTy = LLTy->getPointerTo(0);
1977   FrameFields.push_back(LLTy);
1978   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1979 
1980   // Insert padding bytes to respect alignment.
1981   CharUnits FieldEnd = StackOffset;
1982   StackOffset = FieldEnd.alignTo(WordSize);
1983   if (StackOffset != FieldEnd) {
1984     CharUnits NumBytes = StackOffset - FieldEnd;
1985     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1986     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1987     FrameFields.push_back(Ty);
1988   }
1989 }
1990 
1991 static bool isArgInAlloca(const ABIArgInfo &Info) {
1992   // Leave ignored and inreg arguments alone.
1993   switch (Info.getKind()) {
1994   case ABIArgInfo::InAlloca:
1995     return true;
1996   case ABIArgInfo::Ignore:
1997   case ABIArgInfo::IndirectAliased:
1998     return false;
1999   case ABIArgInfo::Indirect:
2000   case ABIArgInfo::Direct:
2001   case ABIArgInfo::Extend:
2002     return !Info.getInReg();
2003   case ABIArgInfo::Expand:
2004   case ABIArgInfo::CoerceAndExpand:
2005     // These are aggregate types which are never passed in registers when
2006     // inalloca is involved.
2007     return true;
2008   }
2009   llvm_unreachable("invalid enum");
2010 }
2011 
2012 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2013   assert(IsWin32StructABI && "inalloca only supported on win32");
2014 
2015   // Build a packed struct type for all of the arguments in memory.
2016   SmallVector<llvm::Type *, 6> FrameFields;
2017 
2018   // The stack alignment is always 4.
2019   CharUnits StackAlign = CharUnits::fromQuantity(4);
2020 
2021   CharUnits StackOffset;
2022   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2023 
2024   // Put 'this' into the struct before 'sret', if necessary.
2025   bool IsThisCall =
2026       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2027   ABIArgInfo &Ret = FI.getReturnInfo();
2028   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2029       isArgInAlloca(I->info)) {
2030     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2031     ++I;
2032   }
2033 
2034   // Put the sret parameter into the inalloca struct if it's in memory.
2035   if (Ret.isIndirect() && !Ret.getInReg()) {
2036     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2037     // On Windows, the hidden sret parameter is always returned in eax.
2038     Ret.setInAllocaSRet(IsWin32StructABI);
2039   }
2040 
2041   // Skip the 'this' parameter in ecx.
2042   if (IsThisCall)
2043     ++I;
2044 
2045   // Put arguments passed in memory into the struct.
2046   for (; I != E; ++I) {
2047     if (isArgInAlloca(I->info))
2048       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2049   }
2050 
2051   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2052                                         /*isPacked=*/true),
2053                   StackAlign);
2054 }
2055 
2056 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2057                                  Address VAListAddr, QualType Ty) const {
2058 
2059   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2060 
2061   // x86-32 changes the alignment of certain arguments on the stack.
2062   //
2063   // Just messing with TypeInfo like this works because we never pass
2064   // anything indirectly.
2065   TypeInfo.Align = CharUnits::fromQuantity(
2066                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2067 
2068   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2069                           TypeInfo, CharUnits::fromQuantity(4),
2070                           /*AllowHigherAlign*/ true);
2071 }
2072 
2073 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2074     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2075   assert(Triple.getArch() == llvm::Triple::x86);
2076 
2077   switch (Opts.getStructReturnConvention()) {
2078   case CodeGenOptions::SRCK_Default:
2079     break;
2080   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2081     return false;
2082   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2083     return true;
2084   }
2085 
2086   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2087     return true;
2088 
2089   switch (Triple.getOS()) {
2090   case llvm::Triple::DragonFly:
2091   case llvm::Triple::FreeBSD:
2092   case llvm::Triple::OpenBSD:
2093   case llvm::Triple::Win32:
2094     return true;
2095   default:
2096     return false;
2097   }
2098 }
2099 
2100 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2101                                  CodeGen::CodeGenModule &CGM) {
2102   if (!FD->hasAttr<AnyX86InterruptAttr>())
2103     return;
2104 
2105   llvm::Function *Fn = cast<llvm::Function>(GV);
2106   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2107   if (FD->getNumParams() == 0)
2108     return;
2109 
2110   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2111   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2112   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2113     Fn->getContext(), ByValTy);
2114   Fn->addParamAttr(0, NewAttr);
2115 }
2116 
2117 void X86_32TargetCodeGenInfo::setTargetAttributes(
2118     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2119   if (GV->isDeclaration())
2120     return;
2121   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2122     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2123       llvm::Function *Fn = cast<llvm::Function>(GV);
2124       Fn->addFnAttr("stackrealign");
2125     }
2126 
2127     addX86InterruptAttrs(FD, GV, CGM);
2128   }
2129 }
2130 
2131 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2132                                                CodeGen::CodeGenFunction &CGF,
2133                                                llvm::Value *Address) const {
2134   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2135 
2136   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2137 
2138   // 0-7 are the eight integer registers;  the order is different
2139   //   on Darwin (for EH), but the range is the same.
2140   // 8 is %eip.
2141   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2142 
2143   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2144     // 12-16 are st(0..4).  Not sure why we stop at 4.
2145     // These have size 16, which is sizeof(long double) on
2146     // platforms with 8-byte alignment for that type.
2147     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2148     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2149 
2150   } else {
2151     // 9 is %eflags, which doesn't get a size on Darwin for some
2152     // reason.
2153     Builder.CreateAlignedStore(
2154         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2155                                CharUnits::One());
2156 
2157     // 11-16 are st(0..5).  Not sure why we stop at 5.
2158     // These have size 12, which is sizeof(long double) on
2159     // platforms with 4-byte alignment for that type.
2160     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2161     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2162   }
2163 
2164   return false;
2165 }
2166 
2167 //===----------------------------------------------------------------------===//
2168 // X86-64 ABI Implementation
2169 //===----------------------------------------------------------------------===//
2170 
2171 
2172 namespace {
2173 /// The AVX ABI level for X86 targets.
2174 enum class X86AVXABILevel {
2175   None,
2176   AVX,
2177   AVX512
2178 };
2179 
2180 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2181 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2182   switch (AVXLevel) {
2183   case X86AVXABILevel::AVX512:
2184     return 512;
2185   case X86AVXABILevel::AVX:
2186     return 256;
2187   case X86AVXABILevel::None:
2188     return 128;
2189   }
2190   llvm_unreachable("Unknown AVXLevel");
2191 }
2192 
2193 /// X86_64ABIInfo - The X86_64 ABI information.
2194 class X86_64ABIInfo : public SwiftABIInfo {
2195   enum Class {
2196     Integer = 0,
2197     SSE,
2198     SSEUp,
2199     X87,
2200     X87Up,
2201     ComplexX87,
2202     NoClass,
2203     Memory
2204   };
2205 
2206   /// merge - Implement the X86_64 ABI merging algorithm.
2207   ///
2208   /// Merge an accumulating classification \arg Accum with a field
2209   /// classification \arg Field.
2210   ///
2211   /// \param Accum - The accumulating classification. This should
2212   /// always be either NoClass or the result of a previous merge
2213   /// call. In addition, this should never be Memory (the caller
2214   /// should just return Memory for the aggregate).
2215   static Class merge(Class Accum, Class Field);
2216 
2217   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2218   ///
2219   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2220   /// final MEMORY or SSE classes when necessary.
2221   ///
2222   /// \param AggregateSize - The size of the current aggregate in
2223   /// the classification process.
2224   ///
2225   /// \param Lo - The classification for the parts of the type
2226   /// residing in the low word of the containing object.
2227   ///
2228   /// \param Hi - The classification for the parts of the type
2229   /// residing in the higher words of the containing object.
2230   ///
2231   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2232 
2233   /// classify - Determine the x86_64 register classes in which the
2234   /// given type T should be passed.
2235   ///
2236   /// \param Lo - The classification for the parts of the type
2237   /// residing in the low word of the containing object.
2238   ///
2239   /// \param Hi - The classification for the parts of the type
2240   /// residing in the high word of the containing object.
2241   ///
2242   /// \param OffsetBase - The bit offset of this type in the
2243   /// containing object.  Some parameters are classified different
2244   /// depending on whether they straddle an eightbyte boundary.
2245   ///
2246   /// \param isNamedArg - Whether the argument in question is a "named"
2247   /// argument, as used in AMD64-ABI 3.5.7.
2248   ///
2249   /// If a word is unused its result will be NoClass; if a type should
2250   /// be passed in Memory then at least the classification of \arg Lo
2251   /// will be Memory.
2252   ///
2253   /// The \arg Lo class will be NoClass iff the argument is ignored.
2254   ///
2255   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2256   /// also be ComplexX87.
2257   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2258                 bool isNamedArg) const;
2259 
2260   llvm::Type *GetByteVectorType(QualType Ty) const;
2261   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2262                                  unsigned IROffset, QualType SourceTy,
2263                                  unsigned SourceOffset) const;
2264   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2265                                      unsigned IROffset, QualType SourceTy,
2266                                      unsigned SourceOffset) const;
2267 
2268   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2269   /// such that the argument will be returned in memory.
2270   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2271 
2272   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2273   /// such that the argument will be passed in memory.
2274   ///
2275   /// \param freeIntRegs - The number of free integer registers remaining
2276   /// available.
2277   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2278 
2279   ABIArgInfo classifyReturnType(QualType RetTy) const;
2280 
2281   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2282                                   unsigned &neededInt, unsigned &neededSSE,
2283                                   bool isNamedArg) const;
2284 
2285   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2286                                        unsigned &NeededSSE) const;
2287 
2288   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2289                                            unsigned &NeededSSE) const;
2290 
2291   bool IsIllegalVectorType(QualType Ty) const;
2292 
2293   /// The 0.98 ABI revision clarified a lot of ambiguities,
2294   /// unfortunately in ways that were not always consistent with
2295   /// certain previous compilers.  In particular, platforms which
2296   /// required strict binary compatibility with older versions of GCC
2297   /// may need to exempt themselves.
2298   bool honorsRevision0_98() const {
2299     return !getTarget().getTriple().isOSDarwin();
2300   }
2301 
2302   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2303   /// classify it as INTEGER (for compatibility with older clang compilers).
2304   bool classifyIntegerMMXAsSSE() const {
2305     // Clang <= 3.8 did not do this.
2306     if (getContext().getLangOpts().getClangABICompat() <=
2307         LangOptions::ClangABI::Ver3_8)
2308       return false;
2309 
2310     const llvm::Triple &Triple = getTarget().getTriple();
2311     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2312       return false;
2313     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2314       return false;
2315     return true;
2316   }
2317 
2318   // GCC classifies vectors of __int128 as memory.
2319   bool passInt128VectorsInMem() const {
2320     // Clang <= 9.0 did not do this.
2321     if (getContext().getLangOpts().getClangABICompat() <=
2322         LangOptions::ClangABI::Ver9)
2323       return false;
2324 
2325     const llvm::Triple &T = getTarget().getTriple();
2326     return T.isOSLinux() || T.isOSNetBSD();
2327   }
2328 
2329   X86AVXABILevel AVXLevel;
2330   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2331   // 64-bit hardware.
2332   bool Has64BitPointers;
2333 
2334 public:
2335   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2336       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2337       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2338   }
2339 
2340   bool isPassedUsingAVXType(QualType type) const {
2341     unsigned neededInt, neededSSE;
2342     // The freeIntRegs argument doesn't matter here.
2343     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2344                                            /*isNamedArg*/true);
2345     if (info.isDirect()) {
2346       llvm::Type *ty = info.getCoerceToType();
2347       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2348         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2349     }
2350     return false;
2351   }
2352 
2353   void computeInfo(CGFunctionInfo &FI) const override;
2354 
2355   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2356                     QualType Ty) const override;
2357   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2358                       QualType Ty) const override;
2359 
2360   bool has64BitPointers() const {
2361     return Has64BitPointers;
2362   }
2363 
2364   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2365                                     bool asReturnValue) const override {
2366     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2367   }
2368   bool isSwiftErrorInRegister() const override {
2369     return true;
2370   }
2371 };
2372 
2373 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2374 class WinX86_64ABIInfo : public SwiftABIInfo {
2375 public:
2376   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2377       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2378         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2379 
2380   void computeInfo(CGFunctionInfo &FI) const override;
2381 
2382   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2383                     QualType Ty) const override;
2384 
2385   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2386     // FIXME: Assumes vectorcall is in use.
2387     return isX86VectorTypeForVectorCall(getContext(), Ty);
2388   }
2389 
2390   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2391                                          uint64_t NumMembers) const override {
2392     // FIXME: Assumes vectorcall is in use.
2393     return isX86VectorCallAggregateSmallEnough(NumMembers);
2394   }
2395 
2396   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2397                                     bool asReturnValue) const override {
2398     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2399   }
2400 
2401   bool isSwiftErrorInRegister() const override {
2402     return true;
2403   }
2404 
2405 private:
2406   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2407                       bool IsVectorCall, bool IsRegCall) const;
2408   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2409                                       const ABIArgInfo &current) const;
2410   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2411                              bool IsVectorCall, bool IsRegCall) const;
2412 
2413   X86AVXABILevel AVXLevel;
2414 
2415   bool IsMingw64;
2416 };
2417 
2418 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2419 public:
2420   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2421       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2422 
2423   const X86_64ABIInfo &getABIInfo() const {
2424     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2425   }
2426 
2427   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2428   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2429   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2430 
2431   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2432     return 7;
2433   }
2434 
2435   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2436                                llvm::Value *Address) const override {
2437     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2438 
2439     // 0-15 are the 16 integer registers.
2440     // 16 is %rip.
2441     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2442     return false;
2443   }
2444 
2445   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2446                                   StringRef Constraint,
2447                                   llvm::Type* Ty) const override {
2448     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2449   }
2450 
2451   bool isNoProtoCallVariadic(const CallArgList &args,
2452                              const FunctionNoProtoType *fnType) const override {
2453     // The default CC on x86-64 sets %al to the number of SSA
2454     // registers used, and GCC sets this when calling an unprototyped
2455     // function, so we override the default behavior.  However, don't do
2456     // that when AVX types are involved: the ABI explicitly states it is
2457     // undefined, and it doesn't work in practice because of how the ABI
2458     // defines varargs anyway.
2459     if (fnType->getCallConv() == CC_C) {
2460       bool HasAVXType = false;
2461       for (CallArgList::const_iterator
2462              it = args.begin(), ie = args.end(); it != ie; ++it) {
2463         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2464           HasAVXType = true;
2465           break;
2466         }
2467       }
2468 
2469       if (!HasAVXType)
2470         return true;
2471     }
2472 
2473     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2474   }
2475 
2476   llvm::Constant *
2477   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2478     unsigned Sig = (0xeb << 0) | // jmp rel8
2479                    (0x06 << 8) | //           .+0x08
2480                    ('v' << 16) |
2481                    ('2' << 24);
2482     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2483   }
2484 
2485   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2486                            CodeGen::CodeGenModule &CGM) const override {
2487     if (GV->isDeclaration())
2488       return;
2489     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2490       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2491         llvm::Function *Fn = cast<llvm::Function>(GV);
2492         Fn->addFnAttr("stackrealign");
2493       }
2494 
2495       addX86InterruptAttrs(FD, GV, CGM);
2496     }
2497   }
2498 
2499   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2500                             const FunctionDecl *Caller,
2501                             const FunctionDecl *Callee,
2502                             const CallArgList &Args) const override;
2503 };
2504 
2505 static void initFeatureMaps(const ASTContext &Ctx,
2506                             llvm::StringMap<bool> &CallerMap,
2507                             const FunctionDecl *Caller,
2508                             llvm::StringMap<bool> &CalleeMap,
2509                             const FunctionDecl *Callee) {
2510   if (CalleeMap.empty() && CallerMap.empty()) {
2511     // The caller is potentially nullptr in the case where the call isn't in a
2512     // function.  In this case, the getFunctionFeatureMap ensures we just get
2513     // the TU level setting (since it cannot be modified by 'target'..
2514     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2515     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2516   }
2517 }
2518 
2519 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2520                                  SourceLocation CallLoc,
2521                                  const llvm::StringMap<bool> &CallerMap,
2522                                  const llvm::StringMap<bool> &CalleeMap,
2523                                  QualType Ty, StringRef Feature,
2524                                  bool IsArgument) {
2525   bool CallerHasFeat = CallerMap.lookup(Feature);
2526   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2527   if (!CallerHasFeat && !CalleeHasFeat)
2528     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2529            << IsArgument << Ty << Feature;
2530 
2531   // Mixing calling conventions here is very clearly an error.
2532   if (!CallerHasFeat || !CalleeHasFeat)
2533     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2534            << IsArgument << Ty << Feature;
2535 
2536   // Else, both caller and callee have the required feature, so there is no need
2537   // to diagnose.
2538   return false;
2539 }
2540 
2541 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2542                           SourceLocation CallLoc,
2543                           const llvm::StringMap<bool> &CallerMap,
2544                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2545                           bool IsArgument) {
2546   uint64_t Size = Ctx.getTypeSize(Ty);
2547   if (Size > 256)
2548     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2549                                 "avx512f", IsArgument);
2550 
2551   if (Size > 128)
2552     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2553                                 IsArgument);
2554 
2555   return false;
2556 }
2557 
2558 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2559     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2560     const FunctionDecl *Callee, const CallArgList &Args) const {
2561   llvm::StringMap<bool> CallerMap;
2562   llvm::StringMap<bool> CalleeMap;
2563   unsigned ArgIndex = 0;
2564 
2565   // We need to loop through the actual call arguments rather than the the
2566   // function's parameters, in case this variadic.
2567   for (const CallArg &Arg : Args) {
2568     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2569     // additionally changes how vectors >256 in size are passed. Like GCC, we
2570     // warn when a function is called with an argument where this will change.
2571     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2572     // the caller and callee features are mismatched.
2573     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2574     // change its ABI with attribute-target after this call.
2575     if (Arg.getType()->isVectorType() &&
2576         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2577       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2578       QualType Ty = Arg.getType();
2579       // The CallArg seems to have desugared the type already, so for clearer
2580       // diagnostics, replace it with the type in the FunctionDecl if possible.
2581       if (ArgIndex < Callee->getNumParams())
2582         Ty = Callee->getParamDecl(ArgIndex)->getType();
2583 
2584       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2585                         CalleeMap, Ty, /*IsArgument*/ true))
2586         return;
2587     }
2588     ++ArgIndex;
2589   }
2590 
2591   // Check return always, as we don't have a good way of knowing in codegen
2592   // whether this value is used, tail-called, etc.
2593   if (Callee->getReturnType()->isVectorType() &&
2594       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2595     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2596     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2597                   CalleeMap, Callee->getReturnType(),
2598                   /*IsArgument*/ false);
2599   }
2600 }
2601 
2602 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2603   // If the argument does not end in .lib, automatically add the suffix.
2604   // If the argument contains a space, enclose it in quotes.
2605   // This matches the behavior of MSVC.
2606   bool Quote = (Lib.find(' ') != StringRef::npos);
2607   std::string ArgStr = Quote ? "\"" : "";
2608   ArgStr += Lib;
2609   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2610     ArgStr += ".lib";
2611   ArgStr += Quote ? "\"" : "";
2612   return ArgStr;
2613 }
2614 
2615 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2616 public:
2617   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2618         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2619         unsigned NumRegisterParameters)
2620     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2621         Win32StructABI, NumRegisterParameters, false) {}
2622 
2623   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2624                            CodeGen::CodeGenModule &CGM) const override;
2625 
2626   void getDependentLibraryOption(llvm::StringRef Lib,
2627                                  llvm::SmallString<24> &Opt) const override {
2628     Opt = "/DEFAULTLIB:";
2629     Opt += qualifyWindowsLibrary(Lib);
2630   }
2631 
2632   void getDetectMismatchOption(llvm::StringRef Name,
2633                                llvm::StringRef Value,
2634                                llvm::SmallString<32> &Opt) const override {
2635     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2636   }
2637 };
2638 
2639 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2640                                           CodeGen::CodeGenModule &CGM) {
2641   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2642 
2643     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2644       Fn->addFnAttr("stack-probe-size",
2645                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2646     if (CGM.getCodeGenOpts().NoStackArgProbe)
2647       Fn->addFnAttr("no-stack-arg-probe");
2648   }
2649 }
2650 
2651 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2652     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2653   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2654   if (GV->isDeclaration())
2655     return;
2656   addStackProbeTargetAttributes(D, GV, CGM);
2657 }
2658 
2659 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2660 public:
2661   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2662                              X86AVXABILevel AVXLevel)
2663       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2664 
2665   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2666                            CodeGen::CodeGenModule &CGM) const override;
2667 
2668   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2669     return 7;
2670   }
2671 
2672   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2673                                llvm::Value *Address) const override {
2674     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2675 
2676     // 0-15 are the 16 integer registers.
2677     // 16 is %rip.
2678     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2679     return false;
2680   }
2681 
2682   void getDependentLibraryOption(llvm::StringRef Lib,
2683                                  llvm::SmallString<24> &Opt) const override {
2684     Opt = "/DEFAULTLIB:";
2685     Opt += qualifyWindowsLibrary(Lib);
2686   }
2687 
2688   void getDetectMismatchOption(llvm::StringRef Name,
2689                                llvm::StringRef Value,
2690                                llvm::SmallString<32> &Opt) const override {
2691     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2692   }
2693 };
2694 
2695 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2696     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2697   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2698   if (GV->isDeclaration())
2699     return;
2700   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2701     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2702       llvm::Function *Fn = cast<llvm::Function>(GV);
2703       Fn->addFnAttr("stackrealign");
2704     }
2705 
2706     addX86InterruptAttrs(FD, GV, CGM);
2707   }
2708 
2709   addStackProbeTargetAttributes(D, GV, CGM);
2710 }
2711 }
2712 
2713 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2714                               Class &Hi) const {
2715   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2716   //
2717   // (a) If one of the classes is Memory, the whole argument is passed in
2718   //     memory.
2719   //
2720   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2721   //     memory.
2722   //
2723   // (c) If the size of the aggregate exceeds two eightbytes and the first
2724   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2725   //     argument is passed in memory. NOTE: This is necessary to keep the
2726   //     ABI working for processors that don't support the __m256 type.
2727   //
2728   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2729   //
2730   // Some of these are enforced by the merging logic.  Others can arise
2731   // only with unions; for example:
2732   //   union { _Complex double; unsigned; }
2733   //
2734   // Note that clauses (b) and (c) were added in 0.98.
2735   //
2736   if (Hi == Memory)
2737     Lo = Memory;
2738   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2739     Lo = Memory;
2740   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2741     Lo = Memory;
2742   if (Hi == SSEUp && Lo != SSE)
2743     Hi = SSE;
2744 }
2745 
2746 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2747   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2748   // classified recursively so that always two fields are
2749   // considered. The resulting class is calculated according to
2750   // the classes of the fields in the eightbyte:
2751   //
2752   // (a) If both classes are equal, this is the resulting class.
2753   //
2754   // (b) If one of the classes is NO_CLASS, the resulting class is
2755   // the other class.
2756   //
2757   // (c) If one of the classes is MEMORY, the result is the MEMORY
2758   // class.
2759   //
2760   // (d) If one of the classes is INTEGER, the result is the
2761   // INTEGER.
2762   //
2763   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2764   // MEMORY is used as class.
2765   //
2766   // (f) Otherwise class SSE is used.
2767 
2768   // Accum should never be memory (we should have returned) or
2769   // ComplexX87 (because this cannot be passed in a structure).
2770   assert((Accum != Memory && Accum != ComplexX87) &&
2771          "Invalid accumulated classification during merge.");
2772   if (Accum == Field || Field == NoClass)
2773     return Accum;
2774   if (Field == Memory)
2775     return Memory;
2776   if (Accum == NoClass)
2777     return Field;
2778   if (Accum == Integer || Field == Integer)
2779     return Integer;
2780   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2781       Accum == X87 || Accum == X87Up)
2782     return Memory;
2783   return SSE;
2784 }
2785 
2786 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2787                              Class &Lo, Class &Hi, bool isNamedArg) const {
2788   // FIXME: This code can be simplified by introducing a simple value class for
2789   // Class pairs with appropriate constructor methods for the various
2790   // situations.
2791 
2792   // FIXME: Some of the split computations are wrong; unaligned vectors
2793   // shouldn't be passed in registers for example, so there is no chance they
2794   // can straddle an eightbyte. Verify & simplify.
2795 
2796   Lo = Hi = NoClass;
2797 
2798   Class &Current = OffsetBase < 64 ? Lo : Hi;
2799   Current = Memory;
2800 
2801   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2802     BuiltinType::Kind k = BT->getKind();
2803 
2804     if (k == BuiltinType::Void) {
2805       Current = NoClass;
2806     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2807       Lo = Integer;
2808       Hi = Integer;
2809     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2810       Current = Integer;
2811     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2812       Current = SSE;
2813     } else if (k == BuiltinType::LongDouble) {
2814       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2815       if (LDF == &llvm::APFloat::IEEEquad()) {
2816         Lo = SSE;
2817         Hi = SSEUp;
2818       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2819         Lo = X87;
2820         Hi = X87Up;
2821       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2822         Current = SSE;
2823       } else
2824         llvm_unreachable("unexpected long double representation!");
2825     }
2826     // FIXME: _Decimal32 and _Decimal64 are SSE.
2827     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2828     return;
2829   }
2830 
2831   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2832     // Classify the underlying integer type.
2833     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2834     return;
2835   }
2836 
2837   if (Ty->hasPointerRepresentation()) {
2838     Current = Integer;
2839     return;
2840   }
2841 
2842   if (Ty->isMemberPointerType()) {
2843     if (Ty->isMemberFunctionPointerType()) {
2844       if (Has64BitPointers) {
2845         // If Has64BitPointers, this is an {i64, i64}, so classify both
2846         // Lo and Hi now.
2847         Lo = Hi = Integer;
2848       } else {
2849         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2850         // straddles an eightbyte boundary, Hi should be classified as well.
2851         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2852         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2853         if (EB_FuncPtr != EB_ThisAdj) {
2854           Lo = Hi = Integer;
2855         } else {
2856           Current = Integer;
2857         }
2858       }
2859     } else {
2860       Current = Integer;
2861     }
2862     return;
2863   }
2864 
2865   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2866     uint64_t Size = getContext().getTypeSize(VT);
2867     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2868       // gcc passes the following as integer:
2869       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2870       // 2 bytes - <2 x char>, <1 x short>
2871       // 1 byte  - <1 x char>
2872       Current = Integer;
2873 
2874       // If this type crosses an eightbyte boundary, it should be
2875       // split.
2876       uint64_t EB_Lo = (OffsetBase) / 64;
2877       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2878       if (EB_Lo != EB_Hi)
2879         Hi = Lo;
2880     } else if (Size == 64) {
2881       QualType ElementType = VT->getElementType();
2882 
2883       // gcc passes <1 x double> in memory. :(
2884       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2885         return;
2886 
2887       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2888       // pass them as integer.  For platforms where clang is the de facto
2889       // platform compiler, we must continue to use integer.
2890       if (!classifyIntegerMMXAsSSE() &&
2891           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2892            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2893            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2894            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2895         Current = Integer;
2896       else
2897         Current = SSE;
2898 
2899       // If this type crosses an eightbyte boundary, it should be
2900       // split.
2901       if (OffsetBase && OffsetBase != 64)
2902         Hi = Lo;
2903     } else if (Size == 128 ||
2904                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2905       QualType ElementType = VT->getElementType();
2906 
2907       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2908       if (passInt128VectorsInMem() && Size != 128 &&
2909           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2910            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2911         return;
2912 
2913       // Arguments of 256-bits are split into four eightbyte chunks. The
2914       // least significant one belongs to class SSE and all the others to class
2915       // SSEUP. The original Lo and Hi design considers that types can't be
2916       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2917       // This design isn't correct for 256-bits, but since there're no cases
2918       // where the upper parts would need to be inspected, avoid adding
2919       // complexity and just consider Hi to match the 64-256 part.
2920       //
2921       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2922       // registers if they are "named", i.e. not part of the "..." of a
2923       // variadic function.
2924       //
2925       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2926       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2927       Lo = SSE;
2928       Hi = SSEUp;
2929     }
2930     return;
2931   }
2932 
2933   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2934     QualType ET = getContext().getCanonicalType(CT->getElementType());
2935 
2936     uint64_t Size = getContext().getTypeSize(Ty);
2937     if (ET->isIntegralOrEnumerationType()) {
2938       if (Size <= 64)
2939         Current = Integer;
2940       else if (Size <= 128)
2941         Lo = Hi = Integer;
2942     } else if (ET == getContext().FloatTy) {
2943       Current = SSE;
2944     } else if (ET == getContext().DoubleTy) {
2945       Lo = Hi = SSE;
2946     } else if (ET == getContext().LongDoubleTy) {
2947       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2948       if (LDF == &llvm::APFloat::IEEEquad())
2949         Current = Memory;
2950       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2951         Current = ComplexX87;
2952       else if (LDF == &llvm::APFloat::IEEEdouble())
2953         Lo = Hi = SSE;
2954       else
2955         llvm_unreachable("unexpected long double representation!");
2956     }
2957 
2958     // If this complex type crosses an eightbyte boundary then it
2959     // should be split.
2960     uint64_t EB_Real = (OffsetBase) / 64;
2961     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2962     if (Hi == NoClass && EB_Real != EB_Imag)
2963       Hi = Lo;
2964 
2965     return;
2966   }
2967 
2968   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2969     if (EITy->getNumBits() <= 64)
2970       Current = Integer;
2971     else if (EITy->getNumBits() <= 128)
2972       Lo = Hi = Integer;
2973     // Larger values need to get passed in memory.
2974     return;
2975   }
2976 
2977   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2978     // Arrays are treated like structures.
2979 
2980     uint64_t Size = getContext().getTypeSize(Ty);
2981 
2982     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2983     // than eight eightbytes, ..., it has class MEMORY.
2984     if (Size > 512)
2985       return;
2986 
2987     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2988     // fields, it has class MEMORY.
2989     //
2990     // Only need to check alignment of array base.
2991     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2992       return;
2993 
2994     // Otherwise implement simplified merge. We could be smarter about
2995     // this, but it isn't worth it and would be harder to verify.
2996     Current = NoClass;
2997     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2998     uint64_t ArraySize = AT->getSize().getZExtValue();
2999 
3000     // The only case a 256-bit wide vector could be used is when the array
3001     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3002     // to work for sizes wider than 128, early check and fallback to memory.
3003     //
3004     if (Size > 128 &&
3005         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3006       return;
3007 
3008     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3009       Class FieldLo, FieldHi;
3010       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3011       Lo = merge(Lo, FieldLo);
3012       Hi = merge(Hi, FieldHi);
3013       if (Lo == Memory || Hi == Memory)
3014         break;
3015     }
3016 
3017     postMerge(Size, Lo, Hi);
3018     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3019     return;
3020   }
3021 
3022   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3023     uint64_t Size = getContext().getTypeSize(Ty);
3024 
3025     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3026     // than eight eightbytes, ..., it has class MEMORY.
3027     if (Size > 512)
3028       return;
3029 
3030     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3031     // copy constructor or a non-trivial destructor, it is passed by invisible
3032     // reference.
3033     if (getRecordArgABI(RT, getCXXABI()))
3034       return;
3035 
3036     const RecordDecl *RD = RT->getDecl();
3037 
3038     // Assume variable sized types are passed in memory.
3039     if (RD->hasFlexibleArrayMember())
3040       return;
3041 
3042     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3043 
3044     // Reset Lo class, this will be recomputed.
3045     Current = NoClass;
3046 
3047     // If this is a C++ record, classify the bases first.
3048     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3049       for (const auto &I : CXXRD->bases()) {
3050         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3051                "Unexpected base class!");
3052         const auto *Base =
3053             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3054 
3055         // Classify this field.
3056         //
3057         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3058         // single eightbyte, each is classified separately. Each eightbyte gets
3059         // initialized to class NO_CLASS.
3060         Class FieldLo, FieldHi;
3061         uint64_t Offset =
3062           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3063         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3064         Lo = merge(Lo, FieldLo);
3065         Hi = merge(Hi, FieldHi);
3066         if (Lo == Memory || Hi == Memory) {
3067           postMerge(Size, Lo, Hi);
3068           return;
3069         }
3070       }
3071     }
3072 
3073     // Classify the fields one at a time, merging the results.
3074     unsigned idx = 0;
3075     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3076                                 LangOptions::ClangABI::Ver11 ||
3077                             getContext().getTargetInfo().getTriple().isPS4();
3078     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3079 
3080     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3081            i != e; ++i, ++idx) {
3082       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3083       bool BitField = i->isBitField();
3084 
3085       // Ignore padding bit-fields.
3086       if (BitField && i->isUnnamedBitfield())
3087         continue;
3088 
3089       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3090       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3091       //
3092       // The only case a 256-bit or a 512-bit wide vector could be used is when
3093       // the struct contains a single 256-bit or 512-bit element. Early check
3094       // and fallback to memory.
3095       //
3096       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3097       // than 128.
3098       if (Size > 128 &&
3099           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3100            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3101         Lo = Memory;
3102         postMerge(Size, Lo, Hi);
3103         return;
3104       }
3105       // Note, skip this test for bit-fields, see below.
3106       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3107         Lo = Memory;
3108         postMerge(Size, Lo, Hi);
3109         return;
3110       }
3111 
3112       // Classify this field.
3113       //
3114       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3115       // exceeds a single eightbyte, each is classified
3116       // separately. Each eightbyte gets initialized to class
3117       // NO_CLASS.
3118       Class FieldLo, FieldHi;
3119 
3120       // Bit-fields require special handling, they do not force the
3121       // structure to be passed in memory even if unaligned, and
3122       // therefore they can straddle an eightbyte.
3123       if (BitField) {
3124         assert(!i->isUnnamedBitfield());
3125         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3126         uint64_t Size = i->getBitWidthValue(getContext());
3127 
3128         uint64_t EB_Lo = Offset / 64;
3129         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3130 
3131         if (EB_Lo) {
3132           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3133           FieldLo = NoClass;
3134           FieldHi = Integer;
3135         } else {
3136           FieldLo = Integer;
3137           FieldHi = EB_Hi ? Integer : NoClass;
3138         }
3139       } else
3140         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3141       Lo = merge(Lo, FieldLo);
3142       Hi = merge(Hi, FieldHi);
3143       if (Lo == Memory || Hi == Memory)
3144         break;
3145     }
3146 
3147     postMerge(Size, Lo, Hi);
3148   }
3149 }
3150 
3151 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3152   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3153   // place naturally.
3154   if (!isAggregateTypeForABI(Ty)) {
3155     // Treat an enum type as its underlying type.
3156     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3157       Ty = EnumTy->getDecl()->getIntegerType();
3158 
3159     if (Ty->isExtIntType())
3160       return getNaturalAlignIndirect(Ty);
3161 
3162     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3163                                               : ABIArgInfo::getDirect());
3164   }
3165 
3166   return getNaturalAlignIndirect(Ty);
3167 }
3168 
3169 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3170   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3171     uint64_t Size = getContext().getTypeSize(VecTy);
3172     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3173     if (Size <= 64 || Size > LargestVector)
3174       return true;
3175     QualType EltTy = VecTy->getElementType();
3176     if (passInt128VectorsInMem() &&
3177         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3178          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3179       return true;
3180   }
3181 
3182   return false;
3183 }
3184 
3185 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3186                                             unsigned freeIntRegs) const {
3187   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3188   // place naturally.
3189   //
3190   // This assumption is optimistic, as there could be free registers available
3191   // when we need to pass this argument in memory, and LLVM could try to pass
3192   // the argument in the free register. This does not seem to happen currently,
3193   // but this code would be much safer if we could mark the argument with
3194   // 'onstack'. See PR12193.
3195   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3196       !Ty->isExtIntType()) {
3197     // Treat an enum type as its underlying type.
3198     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3199       Ty = EnumTy->getDecl()->getIntegerType();
3200 
3201     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3202                                               : ABIArgInfo::getDirect());
3203   }
3204 
3205   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3206     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3207 
3208   // Compute the byval alignment. We specify the alignment of the byval in all
3209   // cases so that the mid-level optimizer knows the alignment of the byval.
3210   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3211 
3212   // Attempt to avoid passing indirect results using byval when possible. This
3213   // is important for good codegen.
3214   //
3215   // We do this by coercing the value into a scalar type which the backend can
3216   // handle naturally (i.e., without using byval).
3217   //
3218   // For simplicity, we currently only do this when we have exhausted all of the
3219   // free integer registers. Doing this when there are free integer registers
3220   // would require more care, as we would have to ensure that the coerced value
3221   // did not claim the unused register. That would require either reording the
3222   // arguments to the function (so that any subsequent inreg values came first),
3223   // or only doing this optimization when there were no following arguments that
3224   // might be inreg.
3225   //
3226   // We currently expect it to be rare (particularly in well written code) for
3227   // arguments to be passed on the stack when there are still free integer
3228   // registers available (this would typically imply large structs being passed
3229   // by value), so this seems like a fair tradeoff for now.
3230   //
3231   // We can revisit this if the backend grows support for 'onstack' parameter
3232   // attributes. See PR12193.
3233   if (freeIntRegs == 0) {
3234     uint64_t Size = getContext().getTypeSize(Ty);
3235 
3236     // If this type fits in an eightbyte, coerce it into the matching integral
3237     // type, which will end up on the stack (with alignment 8).
3238     if (Align == 8 && Size <= 64)
3239       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3240                                                           Size));
3241   }
3242 
3243   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3244 }
3245 
3246 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3247 /// register. Pick an LLVM IR type that will be passed as a vector register.
3248 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3249   // Wrapper structs/arrays that only contain vectors are passed just like
3250   // vectors; strip them off if present.
3251   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3252     Ty = QualType(InnerTy, 0);
3253 
3254   llvm::Type *IRType = CGT.ConvertType(Ty);
3255   if (isa<llvm::VectorType>(IRType)) {
3256     // Don't pass vXi128 vectors in their native type, the backend can't
3257     // legalize them.
3258     if (passInt128VectorsInMem() &&
3259         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3260       // Use a vXi64 vector.
3261       uint64_t Size = getContext().getTypeSize(Ty);
3262       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3263                                         Size / 64);
3264     }
3265 
3266     return IRType;
3267   }
3268 
3269   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3270     return IRType;
3271 
3272   // We couldn't find the preferred IR vector type for 'Ty'.
3273   uint64_t Size = getContext().getTypeSize(Ty);
3274   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3275 
3276 
3277   // Return a LLVM IR vector type based on the size of 'Ty'.
3278   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3279                                     Size / 64);
3280 }
3281 
3282 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3283 /// is known to either be off the end of the specified type or being in
3284 /// alignment padding.  The user type specified is known to be at most 128 bits
3285 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3286 /// classification that put one of the two halves in the INTEGER class.
3287 ///
3288 /// It is conservatively correct to return false.
3289 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3290                                   unsigned EndBit, ASTContext &Context) {
3291   // If the bytes being queried are off the end of the type, there is no user
3292   // data hiding here.  This handles analysis of builtins, vectors and other
3293   // types that don't contain interesting padding.
3294   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3295   if (TySize <= StartBit)
3296     return true;
3297 
3298   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3299     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3300     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3301 
3302     // Check each element to see if the element overlaps with the queried range.
3303     for (unsigned i = 0; i != NumElts; ++i) {
3304       // If the element is after the span we care about, then we're done..
3305       unsigned EltOffset = i*EltSize;
3306       if (EltOffset >= EndBit) break;
3307 
3308       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3309       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3310                                  EndBit-EltOffset, Context))
3311         return false;
3312     }
3313     // If it overlaps no elements, then it is safe to process as padding.
3314     return true;
3315   }
3316 
3317   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3318     const RecordDecl *RD = RT->getDecl();
3319     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3320 
3321     // If this is a C++ record, check the bases first.
3322     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3323       for (const auto &I : CXXRD->bases()) {
3324         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3325                "Unexpected base class!");
3326         const auto *Base =
3327             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3328 
3329         // If the base is after the span we care about, ignore it.
3330         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3331         if (BaseOffset >= EndBit) continue;
3332 
3333         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3334         if (!BitsContainNoUserData(I.getType(), BaseStart,
3335                                    EndBit-BaseOffset, Context))
3336           return false;
3337       }
3338     }
3339 
3340     // Verify that no field has data that overlaps the region of interest.  Yes
3341     // this could be sped up a lot by being smarter about queried fields,
3342     // however we're only looking at structs up to 16 bytes, so we don't care
3343     // much.
3344     unsigned idx = 0;
3345     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3346          i != e; ++i, ++idx) {
3347       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3348 
3349       // If we found a field after the region we care about, then we're done.
3350       if (FieldOffset >= EndBit) break;
3351 
3352       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3353       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3354                                  Context))
3355         return false;
3356     }
3357 
3358     // If nothing in this record overlapped the area of interest, then we're
3359     // clean.
3360     return true;
3361   }
3362 
3363   return false;
3364 }
3365 
3366 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3367 /// float member at the specified offset.  For example, {int,{float}} has a
3368 /// float at offset 4.  It is conservatively correct for this routine to return
3369 /// false.
3370 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3371                                   const llvm::DataLayout &TD) {
3372   // Base case if we find a float.
3373   if (IROffset == 0 && IRType->isFloatTy())
3374     return true;
3375 
3376   // If this is a struct, recurse into the field at the specified offset.
3377   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3378     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3379     unsigned Elt = SL->getElementContainingOffset(IROffset);
3380     IROffset -= SL->getElementOffset(Elt);
3381     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3382   }
3383 
3384   // If this is an array, recurse into the field at the specified offset.
3385   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3386     llvm::Type *EltTy = ATy->getElementType();
3387     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3388     IROffset -= IROffset/EltSize*EltSize;
3389     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3390   }
3391 
3392   return false;
3393 }
3394 
3395 
3396 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3397 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3398 llvm::Type *X86_64ABIInfo::
3399 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3400                    QualType SourceTy, unsigned SourceOffset) const {
3401   // The only three choices we have are either double, <2 x float>, or float. We
3402   // pass as float if the last 4 bytes is just padding.  This happens for
3403   // structs that contain 3 floats.
3404   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3405                             SourceOffset*8+64, getContext()))
3406     return llvm::Type::getFloatTy(getVMContext());
3407 
3408   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3409   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3410   // case.
3411   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3412       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3413     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3414                                       2);
3415 
3416   return llvm::Type::getDoubleTy(getVMContext());
3417 }
3418 
3419 
3420 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3421 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3422 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3423 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3424 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3425 /// etc).
3426 ///
3427 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3428 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3429 /// the 8-byte value references.  PrefType may be null.
3430 ///
3431 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3432 /// an offset into this that we're processing (which is always either 0 or 8).
3433 ///
3434 llvm::Type *X86_64ABIInfo::
3435 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3436                        QualType SourceTy, unsigned SourceOffset) const {
3437   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3438   // returning an 8-byte unit starting with it.  See if we can safely use it.
3439   if (IROffset == 0) {
3440     // Pointers and int64's always fill the 8-byte unit.
3441     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3442         IRType->isIntegerTy(64))
3443       return IRType;
3444 
3445     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3446     // goodness in the source type is just tail padding.  This is allowed to
3447     // kick in for struct {double,int} on the int, but not on
3448     // struct{double,int,int} because we wouldn't return the second int.  We
3449     // have to do this analysis on the source type because we can't depend on
3450     // unions being lowered a specific way etc.
3451     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3452         IRType->isIntegerTy(32) ||
3453         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3454       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3455           cast<llvm::IntegerType>(IRType)->getBitWidth();
3456 
3457       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3458                                 SourceOffset*8+64, getContext()))
3459         return IRType;
3460     }
3461   }
3462 
3463   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3464     // If this is a struct, recurse into the field at the specified offset.
3465     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3466     if (IROffset < SL->getSizeInBytes()) {
3467       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3468       IROffset -= SL->getElementOffset(FieldIdx);
3469 
3470       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3471                                     SourceTy, SourceOffset);
3472     }
3473   }
3474 
3475   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3476     llvm::Type *EltTy = ATy->getElementType();
3477     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3478     unsigned EltOffset = IROffset/EltSize*EltSize;
3479     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3480                                   SourceOffset);
3481   }
3482 
3483   // Okay, we don't have any better idea of what to pass, so we pass this in an
3484   // integer register that isn't too big to fit the rest of the struct.
3485   unsigned TySizeInBytes =
3486     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3487 
3488   assert(TySizeInBytes != SourceOffset && "Empty field?");
3489 
3490   // It is always safe to classify this as an integer type up to i64 that
3491   // isn't larger than the structure.
3492   return llvm::IntegerType::get(getVMContext(),
3493                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3494 }
3495 
3496 
3497 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3498 /// be used as elements of a two register pair to pass or return, return a
3499 /// first class aggregate to represent them.  For example, if the low part of
3500 /// a by-value argument should be passed as i32* and the high part as float,
3501 /// return {i32*, float}.
3502 static llvm::Type *
3503 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3504                            const llvm::DataLayout &TD) {
3505   // In order to correctly satisfy the ABI, we need to the high part to start
3506   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3507   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3508   // the second element at offset 8.  Check for this:
3509   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3510   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3511   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3512   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3513 
3514   // To handle this, we have to increase the size of the low part so that the
3515   // second element will start at an 8 byte offset.  We can't increase the size
3516   // of the second element because it might make us access off the end of the
3517   // struct.
3518   if (HiStart != 8) {
3519     // There are usually two sorts of types the ABI generation code can produce
3520     // for the low part of a pair that aren't 8 bytes in size: float or
3521     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3522     // NaCl).
3523     // Promote these to a larger type.
3524     if (Lo->isFloatTy())
3525       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3526     else {
3527       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3528              && "Invalid/unknown lo type");
3529       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3530     }
3531   }
3532 
3533   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3534 
3535   // Verify that the second element is at an 8-byte offset.
3536   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3537          "Invalid x86-64 argument pair!");
3538   return Result;
3539 }
3540 
3541 ABIArgInfo X86_64ABIInfo::
3542 classifyReturnType(QualType RetTy) const {
3543   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3544   // classification algorithm.
3545   X86_64ABIInfo::Class Lo, Hi;
3546   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3547 
3548   // Check some invariants.
3549   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3550   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3551 
3552   llvm::Type *ResType = nullptr;
3553   switch (Lo) {
3554   case NoClass:
3555     if (Hi == NoClass)
3556       return ABIArgInfo::getIgnore();
3557     // If the low part is just padding, it takes no register, leave ResType
3558     // null.
3559     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3560            "Unknown missing lo part");
3561     break;
3562 
3563   case SSEUp:
3564   case X87Up:
3565     llvm_unreachable("Invalid classification for lo word.");
3566 
3567     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3568     // hidden argument.
3569   case Memory:
3570     return getIndirectReturnResult(RetTy);
3571 
3572     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3573     // available register of the sequence %rax, %rdx is used.
3574   case Integer:
3575     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3576 
3577     // If we have a sign or zero extended integer, make sure to return Extend
3578     // so that the parameter gets the right LLVM IR attributes.
3579     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3580       // Treat an enum type as its underlying type.
3581       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3582         RetTy = EnumTy->getDecl()->getIntegerType();
3583 
3584       if (RetTy->isIntegralOrEnumerationType() &&
3585           isPromotableIntegerTypeForABI(RetTy))
3586         return ABIArgInfo::getExtend(RetTy);
3587     }
3588     break;
3589 
3590     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3591     // available SSE register of the sequence %xmm0, %xmm1 is used.
3592   case SSE:
3593     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3594     break;
3595 
3596     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3597     // returned on the X87 stack in %st0 as 80-bit x87 number.
3598   case X87:
3599     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3600     break;
3601 
3602     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3603     // part of the value is returned in %st0 and the imaginary part in
3604     // %st1.
3605   case ComplexX87:
3606     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3607     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3608                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3609     break;
3610   }
3611 
3612   llvm::Type *HighPart = nullptr;
3613   switch (Hi) {
3614     // Memory was handled previously and X87 should
3615     // never occur as a hi class.
3616   case Memory:
3617   case X87:
3618     llvm_unreachable("Invalid classification for hi word.");
3619 
3620   case ComplexX87: // Previously handled.
3621   case NoClass:
3622     break;
3623 
3624   case Integer:
3625     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3626     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3627       return ABIArgInfo::getDirect(HighPart, 8);
3628     break;
3629   case SSE:
3630     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3631     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3632       return ABIArgInfo::getDirect(HighPart, 8);
3633     break;
3634 
3635     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3636     // is passed in the next available eightbyte chunk if the last used
3637     // vector register.
3638     //
3639     // SSEUP should always be preceded by SSE, just widen.
3640   case SSEUp:
3641     assert(Lo == SSE && "Unexpected SSEUp classification.");
3642     ResType = GetByteVectorType(RetTy);
3643     break;
3644 
3645     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3646     // returned together with the previous X87 value in %st0.
3647   case X87Up:
3648     // If X87Up is preceded by X87, we don't need to do
3649     // anything. However, in some cases with unions it may not be
3650     // preceded by X87. In such situations we follow gcc and pass the
3651     // extra bits in an SSE reg.
3652     if (Lo != X87) {
3653       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3654       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3655         return ABIArgInfo::getDirect(HighPart, 8);
3656     }
3657     break;
3658   }
3659 
3660   // If a high part was specified, merge it together with the low part.  It is
3661   // known to pass in the high eightbyte of the result.  We do this by forming a
3662   // first class struct aggregate with the high and low part: {low, high}
3663   if (HighPart)
3664     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3665 
3666   return ABIArgInfo::getDirect(ResType);
3667 }
3668 
3669 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3670   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3671   bool isNamedArg)
3672   const
3673 {
3674   Ty = useFirstFieldIfTransparentUnion(Ty);
3675 
3676   X86_64ABIInfo::Class Lo, Hi;
3677   classify(Ty, 0, Lo, Hi, isNamedArg);
3678 
3679   // Check some invariants.
3680   // FIXME: Enforce these by construction.
3681   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3682   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3683 
3684   neededInt = 0;
3685   neededSSE = 0;
3686   llvm::Type *ResType = nullptr;
3687   switch (Lo) {
3688   case NoClass:
3689     if (Hi == NoClass)
3690       return ABIArgInfo::getIgnore();
3691     // If the low part is just padding, it takes no register, leave ResType
3692     // null.
3693     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3694            "Unknown missing lo part");
3695     break;
3696 
3697     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3698     // on the stack.
3699   case Memory:
3700 
3701     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3702     // COMPLEX_X87, it is passed in memory.
3703   case X87:
3704   case ComplexX87:
3705     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3706       ++neededInt;
3707     return getIndirectResult(Ty, freeIntRegs);
3708 
3709   case SSEUp:
3710   case X87Up:
3711     llvm_unreachable("Invalid classification for lo word.");
3712 
3713     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3714     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3715     // and %r9 is used.
3716   case Integer:
3717     ++neededInt;
3718 
3719     // Pick an 8-byte type based on the preferred type.
3720     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3721 
3722     // If we have a sign or zero extended integer, make sure to return Extend
3723     // so that the parameter gets the right LLVM IR attributes.
3724     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3725       // Treat an enum type as its underlying type.
3726       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3727         Ty = EnumTy->getDecl()->getIntegerType();
3728 
3729       if (Ty->isIntegralOrEnumerationType() &&
3730           isPromotableIntegerTypeForABI(Ty))
3731         return ABIArgInfo::getExtend(Ty);
3732     }
3733 
3734     break;
3735 
3736     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3737     // available SSE register is used, the registers are taken in the
3738     // order from %xmm0 to %xmm7.
3739   case SSE: {
3740     llvm::Type *IRType = CGT.ConvertType(Ty);
3741     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3742     ++neededSSE;
3743     break;
3744   }
3745   }
3746 
3747   llvm::Type *HighPart = nullptr;
3748   switch (Hi) {
3749     // Memory was handled previously, ComplexX87 and X87 should
3750     // never occur as hi classes, and X87Up must be preceded by X87,
3751     // which is passed in memory.
3752   case Memory:
3753   case X87:
3754   case ComplexX87:
3755     llvm_unreachable("Invalid classification for hi word.");
3756 
3757   case NoClass: break;
3758 
3759   case Integer:
3760     ++neededInt;
3761     // Pick an 8-byte type based on the preferred type.
3762     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3763 
3764     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3765       return ABIArgInfo::getDirect(HighPart, 8);
3766     break;
3767 
3768     // X87Up generally doesn't occur here (long double is passed in
3769     // memory), except in situations involving unions.
3770   case X87Up:
3771   case SSE:
3772     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3773 
3774     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3775       return ABIArgInfo::getDirect(HighPart, 8);
3776 
3777     ++neededSSE;
3778     break;
3779 
3780     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3781     // eightbyte is passed in the upper half of the last used SSE
3782     // register.  This only happens when 128-bit vectors are passed.
3783   case SSEUp:
3784     assert(Lo == SSE && "Unexpected SSEUp classification");
3785     ResType = GetByteVectorType(Ty);
3786     break;
3787   }
3788 
3789   // If a high part was specified, merge it together with the low part.  It is
3790   // known to pass in the high eightbyte of the result.  We do this by forming a
3791   // first class struct aggregate with the high and low part: {low, high}
3792   if (HighPart)
3793     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3794 
3795   return ABIArgInfo::getDirect(ResType);
3796 }
3797 
3798 ABIArgInfo
3799 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3800                                              unsigned &NeededSSE) const {
3801   auto RT = Ty->getAs<RecordType>();
3802   assert(RT && "classifyRegCallStructType only valid with struct types");
3803 
3804   if (RT->getDecl()->hasFlexibleArrayMember())
3805     return getIndirectReturnResult(Ty);
3806 
3807   // Sum up bases
3808   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3809     if (CXXRD->isDynamicClass()) {
3810       NeededInt = NeededSSE = 0;
3811       return getIndirectReturnResult(Ty);
3812     }
3813 
3814     for (const auto &I : CXXRD->bases())
3815       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3816               .isIndirect()) {
3817         NeededInt = NeededSSE = 0;
3818         return getIndirectReturnResult(Ty);
3819       }
3820   }
3821 
3822   // Sum up members
3823   for (const auto *FD : RT->getDecl()->fields()) {
3824     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3825       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3826               .isIndirect()) {
3827         NeededInt = NeededSSE = 0;
3828         return getIndirectReturnResult(Ty);
3829       }
3830     } else {
3831       unsigned LocalNeededInt, LocalNeededSSE;
3832       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3833                                LocalNeededSSE, true)
3834               .isIndirect()) {
3835         NeededInt = NeededSSE = 0;
3836         return getIndirectReturnResult(Ty);
3837       }
3838       NeededInt += LocalNeededInt;
3839       NeededSSE += LocalNeededSSE;
3840     }
3841   }
3842 
3843   return ABIArgInfo::getDirect();
3844 }
3845 
3846 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3847                                                     unsigned &NeededInt,
3848                                                     unsigned &NeededSSE) const {
3849 
3850   NeededInt = 0;
3851   NeededSSE = 0;
3852 
3853   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3854 }
3855 
3856 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3857 
3858   const unsigned CallingConv = FI.getCallingConvention();
3859   // It is possible to force Win64 calling convention on any x86_64 target by
3860   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3861   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3862   if (CallingConv == llvm::CallingConv::Win64) {
3863     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3864     Win64ABIInfo.computeInfo(FI);
3865     return;
3866   }
3867 
3868   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3869 
3870   // Keep track of the number of assigned registers.
3871   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3872   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3873   unsigned NeededInt, NeededSSE;
3874 
3875   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3876     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3877         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3878       FI.getReturnInfo() =
3879           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3880       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3881         FreeIntRegs -= NeededInt;
3882         FreeSSERegs -= NeededSSE;
3883       } else {
3884         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3885       }
3886     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3887                getContext().getCanonicalType(FI.getReturnType()
3888                                                  ->getAs<ComplexType>()
3889                                                  ->getElementType()) ==
3890                    getContext().LongDoubleTy)
3891       // Complex Long Double Type is passed in Memory when Regcall
3892       // calling convention is used.
3893       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3894     else
3895       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3896   }
3897 
3898   // If the return value is indirect, then the hidden argument is consuming one
3899   // integer register.
3900   if (FI.getReturnInfo().isIndirect())
3901     --FreeIntRegs;
3902 
3903   // The chain argument effectively gives us another free register.
3904   if (FI.isChainCall())
3905     ++FreeIntRegs;
3906 
3907   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3908   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3909   // get assigned (in left-to-right order) for passing as follows...
3910   unsigned ArgNo = 0;
3911   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3912        it != ie; ++it, ++ArgNo) {
3913     bool IsNamedArg = ArgNo < NumRequiredArgs;
3914 
3915     if (IsRegCall && it->type->isStructureOrClassType())
3916       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3917     else
3918       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3919                                       NeededSSE, IsNamedArg);
3920 
3921     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3922     // eightbyte of an argument, the whole argument is passed on the
3923     // stack. If registers have already been assigned for some
3924     // eightbytes of such an argument, the assignments get reverted.
3925     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3926       FreeIntRegs -= NeededInt;
3927       FreeSSERegs -= NeededSSE;
3928     } else {
3929       it->info = getIndirectResult(it->type, FreeIntRegs);
3930     }
3931   }
3932 }
3933 
3934 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3935                                          Address VAListAddr, QualType Ty) {
3936   Address overflow_arg_area_p =
3937       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3938   llvm::Value *overflow_arg_area =
3939     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3940 
3941   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3942   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3943   // It isn't stated explicitly in the standard, but in practice we use
3944   // alignment greater than 16 where necessary.
3945   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3946   if (Align > CharUnits::fromQuantity(8)) {
3947     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3948                                                       Align);
3949   }
3950 
3951   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3952   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3953   llvm::Value *Res =
3954     CGF.Builder.CreateBitCast(overflow_arg_area,
3955                               llvm::PointerType::getUnqual(LTy));
3956 
3957   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3958   // l->overflow_arg_area + sizeof(type).
3959   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3960   // an 8 byte boundary.
3961 
3962   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3963   llvm::Value *Offset =
3964       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3965   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3966                                             "overflow_arg_area.next");
3967   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3968 
3969   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3970   return Address(Res, Align);
3971 }
3972 
3973 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3974                                  QualType Ty) const {
3975   // Assume that va_list type is correct; should be pointer to LLVM type:
3976   // struct {
3977   //   i32 gp_offset;
3978   //   i32 fp_offset;
3979   //   i8* overflow_arg_area;
3980   //   i8* reg_save_area;
3981   // };
3982   unsigned neededInt, neededSSE;
3983 
3984   Ty = getContext().getCanonicalType(Ty);
3985   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3986                                        /*isNamedArg*/false);
3987 
3988   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3989   // in the registers. If not go to step 7.
3990   if (!neededInt && !neededSSE)
3991     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3992 
3993   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3994   // general purpose registers needed to pass type and num_fp to hold
3995   // the number of floating point registers needed.
3996 
3997   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3998   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3999   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4000   //
4001   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4002   // register save space).
4003 
4004   llvm::Value *InRegs = nullptr;
4005   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4006   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4007   if (neededInt) {
4008     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4009     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4010     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4011     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4012   }
4013 
4014   if (neededSSE) {
4015     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4016     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4017     llvm::Value *FitsInFP =
4018       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4019     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4020     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4021   }
4022 
4023   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4024   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4025   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4026   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4027 
4028   // Emit code to load the value if it was passed in registers.
4029 
4030   CGF.EmitBlock(InRegBlock);
4031 
4032   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4033   // an offset of l->gp_offset and/or l->fp_offset. This may require
4034   // copying to a temporary location in case the parameter is passed
4035   // in different register classes or requires an alignment greater
4036   // than 8 for general purpose registers and 16 for XMM registers.
4037   //
4038   // FIXME: This really results in shameful code when we end up needing to
4039   // collect arguments from different places; often what should result in a
4040   // simple assembling of a structure from scattered addresses has many more
4041   // loads than necessary. Can we clean this up?
4042   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4043   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4044       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4045 
4046   Address RegAddr = Address::invalid();
4047   if (neededInt && neededSSE) {
4048     // FIXME: Cleanup.
4049     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4050     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4051     Address Tmp = CGF.CreateMemTemp(Ty);
4052     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4053     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4054     llvm::Type *TyLo = ST->getElementType(0);
4055     llvm::Type *TyHi = ST->getElementType(1);
4056     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4057            "Unexpected ABI info for mixed regs");
4058     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4059     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4060     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4061     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4062     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4063     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4064 
4065     // Copy the first element.
4066     // FIXME: Our choice of alignment here and below is probably pessimistic.
4067     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4068         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4069         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4070     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4071 
4072     // Copy the second element.
4073     V = CGF.Builder.CreateAlignedLoad(
4074         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4075         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4076     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4077 
4078     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4079   } else if (neededInt) {
4080     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4081                       CharUnits::fromQuantity(8));
4082     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4083 
4084     // Copy to a temporary if necessary to ensure the appropriate alignment.
4085     auto TInfo = getContext().getTypeInfoInChars(Ty);
4086     uint64_t TySize = TInfo.Width.getQuantity();
4087     CharUnits TyAlign = TInfo.Align;
4088 
4089     // Copy into a temporary if the type is more aligned than the
4090     // register save area.
4091     if (TyAlign.getQuantity() > 8) {
4092       Address Tmp = CGF.CreateMemTemp(Ty);
4093       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4094       RegAddr = Tmp;
4095     }
4096 
4097   } else if (neededSSE == 1) {
4098     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4099                       CharUnits::fromQuantity(16));
4100     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4101   } else {
4102     assert(neededSSE == 2 && "Invalid number of needed registers!");
4103     // SSE registers are spaced 16 bytes apart in the register save
4104     // area, we need to collect the two eightbytes together.
4105     // The ABI isn't explicit about this, but it seems reasonable
4106     // to assume that the slots are 16-byte aligned, since the stack is
4107     // naturally 16-byte aligned and the prologue is expected to store
4108     // all the SSE registers to the RSA.
4109     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4110                                 CharUnits::fromQuantity(16));
4111     Address RegAddrHi =
4112       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4113                                              CharUnits::fromQuantity(16));
4114     llvm::Type *ST = AI.canHaveCoerceToType()
4115                          ? AI.getCoerceToType()
4116                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4117     llvm::Value *V;
4118     Address Tmp = CGF.CreateMemTemp(Ty);
4119     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4120     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4121         RegAddrLo, ST->getStructElementType(0)));
4122     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4123     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4124         RegAddrHi, ST->getStructElementType(1)));
4125     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4126 
4127     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4128   }
4129 
4130   // AMD64-ABI 3.5.7p5: Step 5. Set:
4131   // l->gp_offset = l->gp_offset + num_gp * 8
4132   // l->fp_offset = l->fp_offset + num_fp * 16.
4133   if (neededInt) {
4134     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4135     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4136                             gp_offset_p);
4137   }
4138   if (neededSSE) {
4139     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4140     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4141                             fp_offset_p);
4142   }
4143   CGF.EmitBranch(ContBlock);
4144 
4145   // Emit code to load the value if it was passed in memory.
4146 
4147   CGF.EmitBlock(InMemBlock);
4148   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4149 
4150   // Return the appropriate result.
4151 
4152   CGF.EmitBlock(ContBlock);
4153   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4154                                  "vaarg.addr");
4155   return ResAddr;
4156 }
4157 
4158 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4159                                    QualType Ty) const {
4160   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4161                           CGF.getContext().getTypeInfoInChars(Ty),
4162                           CharUnits::fromQuantity(8),
4163                           /*allowHigherAlign*/ false);
4164 }
4165 
4166 ABIArgInfo
4167 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
4168                                     const ABIArgInfo &current) const {
4169   // Assumes vectorCall calling convention.
4170   const Type *Base = nullptr;
4171   uint64_t NumElts = 0;
4172 
4173   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4174       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4175     FreeSSERegs -= NumElts;
4176     return getDirectX86Hva();
4177   }
4178   return current;
4179 }
4180 
4181 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4182                                       bool IsReturnType, bool IsVectorCall,
4183                                       bool IsRegCall) const {
4184 
4185   if (Ty->isVoidType())
4186     return ABIArgInfo::getIgnore();
4187 
4188   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4189     Ty = EnumTy->getDecl()->getIntegerType();
4190 
4191   TypeInfo Info = getContext().getTypeInfo(Ty);
4192   uint64_t Width = Info.Width;
4193   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4194 
4195   const RecordType *RT = Ty->getAs<RecordType>();
4196   if (RT) {
4197     if (!IsReturnType) {
4198       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4199         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4200     }
4201 
4202     if (RT->getDecl()->hasFlexibleArrayMember())
4203       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4204 
4205   }
4206 
4207   const Type *Base = nullptr;
4208   uint64_t NumElts = 0;
4209   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4210   // other targets.
4211   if ((IsVectorCall || IsRegCall) &&
4212       isHomogeneousAggregate(Ty, Base, NumElts)) {
4213     if (IsRegCall) {
4214       if (FreeSSERegs >= NumElts) {
4215         FreeSSERegs -= NumElts;
4216         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4217           return ABIArgInfo::getDirect();
4218         return ABIArgInfo::getExpand();
4219       }
4220       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4221     } else if (IsVectorCall) {
4222       if (FreeSSERegs >= NumElts &&
4223           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4224         FreeSSERegs -= NumElts;
4225         return ABIArgInfo::getDirect();
4226       } else if (IsReturnType) {
4227         return ABIArgInfo::getExpand();
4228       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4229         // HVAs are delayed and reclassified in the 2nd step.
4230         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4231       }
4232     }
4233   }
4234 
4235   if (Ty->isMemberPointerType()) {
4236     // If the member pointer is represented by an LLVM int or ptr, pass it
4237     // directly.
4238     llvm::Type *LLTy = CGT.ConvertType(Ty);
4239     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4240       return ABIArgInfo::getDirect();
4241   }
4242 
4243   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4244     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4245     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4246     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4247       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4248 
4249     // Otherwise, coerce it to a small integer.
4250     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4251   }
4252 
4253   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4254     switch (BT->getKind()) {
4255     case BuiltinType::Bool:
4256       // Bool type is always extended to the ABI, other builtin types are not
4257       // extended.
4258       return ABIArgInfo::getExtend(Ty);
4259 
4260     case BuiltinType::LongDouble:
4261       // Mingw64 GCC uses the old 80 bit extended precision floating point
4262       // unit. It passes them indirectly through memory.
4263       if (IsMingw64) {
4264         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4265         if (LDF == &llvm::APFloat::x87DoubleExtended())
4266           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4267       }
4268       break;
4269 
4270     case BuiltinType::Int128:
4271     case BuiltinType::UInt128:
4272       // If it's a parameter type, the normal ABI rule is that arguments larger
4273       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4274       // even though it isn't particularly efficient.
4275       if (!IsReturnType)
4276         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4277 
4278       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4279       // Clang matches them for compatibility.
4280       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4281           llvm::Type::getInt64Ty(getVMContext()), 2));
4282 
4283     default:
4284       break;
4285     }
4286   }
4287 
4288   if (Ty->isExtIntType()) {
4289     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4290     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4291     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4292     // anyway as long is it fits in them, so we don't have to check the power of
4293     // 2.
4294     if (Width <= 64)
4295       return ABIArgInfo::getDirect();
4296     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4297   }
4298 
4299   return ABIArgInfo::getDirect();
4300 }
4301 
4302 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4303                                              unsigned FreeSSERegs,
4304                                              bool IsVectorCall,
4305                                              bool IsRegCall) const {
4306   unsigned Count = 0;
4307   for (auto &I : FI.arguments()) {
4308     // Vectorcall in x64 only permits the first 6 arguments to be passed
4309     // as XMM/YMM registers.
4310     if (Count < VectorcallMaxParamNumAsReg)
4311       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4312     else {
4313       // Since these cannot be passed in registers, pretend no registers
4314       // are left.
4315       unsigned ZeroSSERegsAvail = 0;
4316       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4317                         IsVectorCall, IsRegCall);
4318     }
4319     ++Count;
4320   }
4321 
4322   for (auto &I : FI.arguments()) {
4323     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4324   }
4325 }
4326 
4327 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4328   const unsigned CC = FI.getCallingConvention();
4329   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4330   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4331 
4332   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4333   // classification rules.
4334   if (CC == llvm::CallingConv::X86_64_SysV) {
4335     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4336     SysVABIInfo.computeInfo(FI);
4337     return;
4338   }
4339 
4340   unsigned FreeSSERegs = 0;
4341   if (IsVectorCall) {
4342     // We can use up to 4 SSE return registers with vectorcall.
4343     FreeSSERegs = 4;
4344   } else if (IsRegCall) {
4345     // RegCall gives us 16 SSE registers.
4346     FreeSSERegs = 16;
4347   }
4348 
4349   if (!getCXXABI().classifyReturnType(FI))
4350     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4351                                   IsVectorCall, IsRegCall);
4352 
4353   if (IsVectorCall) {
4354     // We can use up to 6 SSE register parameters with vectorcall.
4355     FreeSSERegs = 6;
4356   } else if (IsRegCall) {
4357     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4358     FreeSSERegs = 16;
4359   }
4360 
4361   if (IsVectorCall) {
4362     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4363   } else {
4364     for (auto &I : FI.arguments())
4365       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4366   }
4367 
4368 }
4369 
4370 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4371                                     QualType Ty) const {
4372 
4373   bool IsIndirect = false;
4374 
4375   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4376   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4377   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4378     uint64_t Width = getContext().getTypeSize(Ty);
4379     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4380   }
4381 
4382   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4383                           CGF.getContext().getTypeInfoInChars(Ty),
4384                           CharUnits::fromQuantity(8),
4385                           /*allowHigherAlign*/ false);
4386 }
4387 
4388 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4389                                         llvm::Value *Address, bool Is64Bit,
4390                                         bool IsAIX) {
4391   // This is calculated from the LLVM and GCC tables and verified
4392   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4393 
4394   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4395 
4396   llvm::IntegerType *i8 = CGF.Int8Ty;
4397   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4398   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4399   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4400 
4401   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4402   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4403 
4404   // 32-63: fp0-31, the 8-byte floating-point registers
4405   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4406 
4407   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4408   // 64: mq
4409   // 65: lr
4410   // 66: ctr
4411   // 67: ap
4412   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4413 
4414   // 68-76 are various 4-byte special-purpose registers:
4415   // 68-75 cr0-7
4416   // 76: xer
4417   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4418 
4419   // 77-108: v0-31, the 16-byte vector registers
4420   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4421 
4422   // 109: vrsave
4423   // 110: vscr
4424   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4425 
4426   // AIX does not utilize the rest of the registers.
4427   if (IsAIX)
4428     return false;
4429 
4430   // 111: spe_acc
4431   // 112: spefscr
4432   // 113: sfp
4433   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4434 
4435   if (!Is64Bit)
4436     return false;
4437 
4438   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4439   // or above CPU.
4440   // 64-bit only registers:
4441   // 114: tfhar
4442   // 115: tfiar
4443   // 116: texasr
4444   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4445 
4446   return false;
4447 }
4448 
4449 // AIX
4450 namespace {
4451 /// AIXABIInfo - The AIX XCOFF ABI information.
4452 class AIXABIInfo : public ABIInfo {
4453   const bool Is64Bit;
4454   const unsigned PtrByteSize;
4455   CharUnits getParamTypeAlignment(QualType Ty) const;
4456 
4457 public:
4458   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4459       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4460 
4461   bool isPromotableTypeForABI(QualType Ty) const;
4462 
4463   ABIArgInfo classifyReturnType(QualType RetTy) const;
4464   ABIArgInfo classifyArgumentType(QualType Ty) const;
4465 
4466   void computeInfo(CGFunctionInfo &FI) const override {
4467     if (!getCXXABI().classifyReturnType(FI))
4468       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4469 
4470     for (auto &I : FI.arguments())
4471       I.info = classifyArgumentType(I.type);
4472   }
4473 
4474   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4475                     QualType Ty) const override;
4476 };
4477 
4478 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4479   const bool Is64Bit;
4480 
4481 public:
4482   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4483       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4484         Is64Bit(Is64Bit) {}
4485   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4486     return 1; // r1 is the dedicated stack pointer
4487   }
4488 
4489   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4490                                llvm::Value *Address) const override;
4491 };
4492 } // namespace
4493 
4494 // Return true if the ABI requires Ty to be passed sign- or zero-
4495 // extended to 32/64 bits.
4496 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4497   // Treat an enum type as its underlying type.
4498   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4499     Ty = EnumTy->getDecl()->getIntegerType();
4500 
4501   // Promotable integer types are required to be promoted by the ABI.
4502   if (Ty->isPromotableIntegerType())
4503     return true;
4504 
4505   if (!Is64Bit)
4506     return false;
4507 
4508   // For 64 bit mode, in addition to the usual promotable integer types, we also
4509   // need to extend all 32-bit types, since the ABI requires promotion to 64
4510   // bits.
4511   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4512     switch (BT->getKind()) {
4513     case BuiltinType::Int:
4514     case BuiltinType::UInt:
4515       return true;
4516     default:
4517       break;
4518     }
4519 
4520   return false;
4521 }
4522 
4523 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4524   if (RetTy->isAnyComplexType())
4525     return ABIArgInfo::getDirect();
4526 
4527   if (RetTy->isVectorType())
4528     return ABIArgInfo::getDirect();
4529 
4530   if (RetTy->isVoidType())
4531     return ABIArgInfo::getIgnore();
4532 
4533   if (isAggregateTypeForABI(RetTy))
4534     return getNaturalAlignIndirect(RetTy);
4535 
4536   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4537                                         : ABIArgInfo::getDirect());
4538 }
4539 
4540 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4541   Ty = useFirstFieldIfTransparentUnion(Ty);
4542 
4543   if (Ty->isAnyComplexType())
4544     return ABIArgInfo::getDirect();
4545 
4546   if (Ty->isVectorType())
4547     return ABIArgInfo::getDirect();
4548 
4549   if (isAggregateTypeForABI(Ty)) {
4550     // Records with non-trivial destructors/copy-constructors should not be
4551     // passed by value.
4552     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4553       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4554 
4555     CharUnits CCAlign = getParamTypeAlignment(Ty);
4556     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4557 
4558     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4559                                    /*Realign*/ TyAlign > CCAlign);
4560   }
4561 
4562   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4563                                      : ABIArgInfo::getDirect());
4564 }
4565 
4566 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4567   // Complex types are passed just like their elements.
4568   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4569     Ty = CTy->getElementType();
4570 
4571   if (Ty->isVectorType())
4572     return CharUnits::fromQuantity(16);
4573 
4574   // If the structure contains a vector type, the alignment is 16.
4575   if (isRecordWithSIMDVectorType(getContext(), Ty))
4576     return CharUnits::fromQuantity(16);
4577 
4578   return CharUnits::fromQuantity(PtrByteSize);
4579 }
4580 
4581 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4582                               QualType Ty) const {
4583   if (Ty->isAnyComplexType())
4584     llvm::report_fatal_error("complex type is not supported on AIX yet");
4585 
4586   if (Ty->isVectorType())
4587     llvm::report_fatal_error(
4588         "vector types are not yet supported for variadic functions on AIX");
4589 
4590   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4591   TypeInfo.Align = getParamTypeAlignment(Ty);
4592 
4593   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4594 
4595   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4596                           SlotSize, /*AllowHigher*/ true);
4597 }
4598 
4599 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4600     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4601   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4602 }
4603 
4604 // PowerPC-32
4605 namespace {
4606 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4607 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4608   bool IsSoftFloatABI;
4609   bool IsRetSmallStructInRegABI;
4610 
4611   CharUnits getParamTypeAlignment(QualType Ty) const;
4612 
4613 public:
4614   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4615                      bool RetSmallStructInRegABI)
4616       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4617         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4618 
4619   ABIArgInfo classifyReturnType(QualType RetTy) const;
4620 
4621   void computeInfo(CGFunctionInfo &FI) const override {
4622     if (!getCXXABI().classifyReturnType(FI))
4623       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4624     for (auto &I : FI.arguments())
4625       I.info = classifyArgumentType(I.type);
4626   }
4627 
4628   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4629                     QualType Ty) const override;
4630 };
4631 
4632 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4633 public:
4634   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4635                          bool RetSmallStructInRegABI)
4636       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4637             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4638 
4639   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4640                                      const CodeGenOptions &Opts);
4641 
4642   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4643     // This is recovered from gcc output.
4644     return 1; // r1 is the dedicated stack pointer
4645   }
4646 
4647   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4648                                llvm::Value *Address) const override;
4649 };
4650 }
4651 
4652 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4653   // Complex types are passed just like their elements.
4654   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4655     Ty = CTy->getElementType();
4656 
4657   if (Ty->isVectorType())
4658     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4659                                                                        : 4);
4660 
4661   // For single-element float/vector structs, we consider the whole type
4662   // to have the same alignment requirements as its single element.
4663   const Type *AlignTy = nullptr;
4664   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4665     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4666     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4667         (BT && BT->isFloatingPoint()))
4668       AlignTy = EltType;
4669   }
4670 
4671   if (AlignTy)
4672     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4673   return CharUnits::fromQuantity(4);
4674 }
4675 
4676 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4677   uint64_t Size;
4678 
4679   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4680   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4681       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4682     // System V ABI (1995), page 3-22, specified:
4683     // > A structure or union whose size is less than or equal to 8 bytes
4684     // > shall be returned in r3 and r4, as if it were first stored in the
4685     // > 8-byte aligned memory area and then the low addressed word were
4686     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4687     // > the last member of the structure or union are not defined.
4688     //
4689     // GCC for big-endian PPC32 inserts the pad before the first member,
4690     // not "beyond the last member" of the struct.  To stay compatible
4691     // with GCC, we coerce the struct to an integer of the same size.
4692     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4693     if (Size == 0)
4694       return ABIArgInfo::getIgnore();
4695     else {
4696       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4697       return ABIArgInfo::getDirect(CoerceTy);
4698     }
4699   }
4700 
4701   return DefaultABIInfo::classifyReturnType(RetTy);
4702 }
4703 
4704 // TODO: this implementation is now likely redundant with
4705 // DefaultABIInfo::EmitVAArg.
4706 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4707                                       QualType Ty) const {
4708   if (getTarget().getTriple().isOSDarwin()) {
4709     auto TI = getContext().getTypeInfoInChars(Ty);
4710     TI.Align = getParamTypeAlignment(Ty);
4711 
4712     CharUnits SlotSize = CharUnits::fromQuantity(4);
4713     return emitVoidPtrVAArg(CGF, VAList, Ty,
4714                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4715                             /*AllowHigherAlign=*/true);
4716   }
4717 
4718   const unsigned OverflowLimit = 8;
4719   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4720     // TODO: Implement this. For now ignore.
4721     (void)CTy;
4722     return Address::invalid(); // FIXME?
4723   }
4724 
4725   // struct __va_list_tag {
4726   //   unsigned char gpr;
4727   //   unsigned char fpr;
4728   //   unsigned short reserved;
4729   //   void *overflow_arg_area;
4730   //   void *reg_save_area;
4731   // };
4732 
4733   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4734   bool isInt =
4735       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4736   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4737 
4738   // All aggregates are passed indirectly?  That doesn't seem consistent
4739   // with the argument-lowering code.
4740   bool isIndirect = Ty->isAggregateType();
4741 
4742   CGBuilderTy &Builder = CGF.Builder;
4743 
4744   // The calling convention either uses 1-2 GPRs or 1 FPR.
4745   Address NumRegsAddr = Address::invalid();
4746   if (isInt || IsSoftFloatABI) {
4747     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4748   } else {
4749     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4750   }
4751 
4752   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4753 
4754   // "Align" the register count when TY is i64.
4755   if (isI64 || (isF64 && IsSoftFloatABI)) {
4756     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4757     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4758   }
4759 
4760   llvm::Value *CC =
4761       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4762 
4763   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4764   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4765   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4766 
4767   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4768 
4769   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4770   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4771 
4772   // Case 1: consume registers.
4773   Address RegAddr = Address::invalid();
4774   {
4775     CGF.EmitBlock(UsingRegs);
4776 
4777     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4778     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4779                       CharUnits::fromQuantity(8));
4780     assert(RegAddr.getElementType() == CGF.Int8Ty);
4781 
4782     // Floating-point registers start after the general-purpose registers.
4783     if (!(isInt || IsSoftFloatABI)) {
4784       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4785                                                    CharUnits::fromQuantity(32));
4786     }
4787 
4788     // Get the address of the saved value by scaling the number of
4789     // registers we've used by the number of
4790     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4791     llvm::Value *RegOffset =
4792       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4793     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4794                                             RegAddr.getPointer(), RegOffset),
4795                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4796     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4797 
4798     // Increase the used-register count.
4799     NumRegs =
4800       Builder.CreateAdd(NumRegs,
4801                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4802     Builder.CreateStore(NumRegs, NumRegsAddr);
4803 
4804     CGF.EmitBranch(Cont);
4805   }
4806 
4807   // Case 2: consume space in the overflow area.
4808   Address MemAddr = Address::invalid();
4809   {
4810     CGF.EmitBlock(UsingOverflow);
4811 
4812     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4813 
4814     // Everything in the overflow area is rounded up to a size of at least 4.
4815     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4816 
4817     CharUnits Size;
4818     if (!isIndirect) {
4819       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4820       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4821     } else {
4822       Size = CGF.getPointerSize();
4823     }
4824 
4825     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4826     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4827                          OverflowAreaAlign);
4828     // Round up address of argument to alignment
4829     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4830     if (Align > OverflowAreaAlign) {
4831       llvm::Value *Ptr = OverflowArea.getPointer();
4832       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4833                                                            Align);
4834     }
4835 
4836     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4837 
4838     // Increase the overflow area.
4839     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4840     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4841     CGF.EmitBranch(Cont);
4842   }
4843 
4844   CGF.EmitBlock(Cont);
4845 
4846   // Merge the cases with a phi.
4847   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4848                                 "vaarg.addr");
4849 
4850   // Load the pointer if the argument was passed indirectly.
4851   if (isIndirect) {
4852     Result = Address(Builder.CreateLoad(Result, "aggr"),
4853                      getContext().getTypeAlignInChars(Ty));
4854   }
4855 
4856   return Result;
4857 }
4858 
4859 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4860     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4861   assert(Triple.getArch() == llvm::Triple::ppc);
4862 
4863   switch (Opts.getStructReturnConvention()) {
4864   case CodeGenOptions::SRCK_Default:
4865     break;
4866   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4867     return false;
4868   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4869     return true;
4870   }
4871 
4872   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4873     return true;
4874 
4875   return false;
4876 }
4877 
4878 bool
4879 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4880                                                 llvm::Value *Address) const {
4881   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4882                                      /*IsAIX*/ false);
4883 }
4884 
4885 // PowerPC-64
4886 
4887 namespace {
4888 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4889 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4890 public:
4891   enum ABIKind {
4892     ELFv1 = 0,
4893     ELFv2
4894   };
4895 
4896 private:
4897   static const unsigned GPRBits = 64;
4898   ABIKind Kind;
4899   bool IsSoftFloatABI;
4900 
4901 public:
4902   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4903                      bool SoftFloatABI)
4904       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4905 
4906   bool isPromotableTypeForABI(QualType Ty) const;
4907   CharUnits getParamTypeAlignment(QualType Ty) const;
4908 
4909   ABIArgInfo classifyReturnType(QualType RetTy) const;
4910   ABIArgInfo classifyArgumentType(QualType Ty) const;
4911 
4912   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4913   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4914                                          uint64_t Members) const override;
4915 
4916   // TODO: We can add more logic to computeInfo to improve performance.
4917   // Example: For aggregate arguments that fit in a register, we could
4918   // use getDirectInReg (as is done below for structs containing a single
4919   // floating-point value) to avoid pushing them to memory on function
4920   // entry.  This would require changing the logic in PPCISelLowering
4921   // when lowering the parameters in the caller and args in the callee.
4922   void computeInfo(CGFunctionInfo &FI) const override {
4923     if (!getCXXABI().classifyReturnType(FI))
4924       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4925     for (auto &I : FI.arguments()) {
4926       // We rely on the default argument classification for the most part.
4927       // One exception:  An aggregate containing a single floating-point
4928       // or vector item must be passed in a register if one is available.
4929       const Type *T = isSingleElementStruct(I.type, getContext());
4930       if (T) {
4931         const BuiltinType *BT = T->getAs<BuiltinType>();
4932         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4933             (BT && BT->isFloatingPoint())) {
4934           QualType QT(T, 0);
4935           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4936           continue;
4937         }
4938       }
4939       I.info = classifyArgumentType(I.type);
4940     }
4941   }
4942 
4943   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4944                     QualType Ty) const override;
4945 
4946   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4947                                     bool asReturnValue) const override {
4948     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4949   }
4950 
4951   bool isSwiftErrorInRegister() const override {
4952     return false;
4953   }
4954 };
4955 
4956 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4957 
4958 public:
4959   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4960                                PPC64_SVR4_ABIInfo::ABIKind Kind,
4961                                bool SoftFloatABI)
4962       : TargetCodeGenInfo(
4963             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
4964 
4965   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4966     // This is recovered from gcc output.
4967     return 1; // r1 is the dedicated stack pointer
4968   }
4969 
4970   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4971                                llvm::Value *Address) const override;
4972 };
4973 
4974 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4975 public:
4976   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4977 
4978   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4979     // This is recovered from gcc output.
4980     return 1; // r1 is the dedicated stack pointer
4981   }
4982 
4983   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4984                                llvm::Value *Address) const override;
4985 };
4986 
4987 }
4988 
4989 // Return true if the ABI requires Ty to be passed sign- or zero-
4990 // extended to 64 bits.
4991 bool
4992 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4993   // Treat an enum type as its underlying type.
4994   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4995     Ty = EnumTy->getDecl()->getIntegerType();
4996 
4997   // Promotable integer types are required to be promoted by the ABI.
4998   if (isPromotableIntegerTypeForABI(Ty))
4999     return true;
5000 
5001   // In addition to the usual promotable integer types, we also need to
5002   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5003   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5004     switch (BT->getKind()) {
5005     case BuiltinType::Int:
5006     case BuiltinType::UInt:
5007       return true;
5008     default:
5009       break;
5010     }
5011 
5012   if (const auto *EIT = Ty->getAs<ExtIntType>())
5013     if (EIT->getNumBits() < 64)
5014       return true;
5015 
5016   return false;
5017 }
5018 
5019 /// isAlignedParamType - Determine whether a type requires 16-byte or
5020 /// higher alignment in the parameter area.  Always returns at least 8.
5021 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5022   // Complex types are passed just like their elements.
5023   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5024     Ty = CTy->getElementType();
5025 
5026   // Only vector types of size 16 bytes need alignment (larger types are
5027   // passed via reference, smaller types are not aligned).
5028   if (Ty->isVectorType()) {
5029     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5030   } else if (Ty->isRealFloatingType() &&
5031              &getContext().getFloatTypeSemantics(Ty) ==
5032                  &llvm::APFloat::IEEEquad()) {
5033     // According to ABI document section 'Optional Save Areas': If extended
5034     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5035     // format are supported, map them to a single quadword, quadword aligned.
5036     return CharUnits::fromQuantity(16);
5037   }
5038 
5039   // For single-element float/vector structs, we consider the whole type
5040   // to have the same alignment requirements as its single element.
5041   const Type *AlignAsType = nullptr;
5042   const Type *EltType = isSingleElementStruct(Ty, getContext());
5043   if (EltType) {
5044     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5045     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5046         (BT && BT->isFloatingPoint()))
5047       AlignAsType = EltType;
5048   }
5049 
5050   // Likewise for ELFv2 homogeneous aggregates.
5051   const Type *Base = nullptr;
5052   uint64_t Members = 0;
5053   if (!AlignAsType && Kind == ELFv2 &&
5054       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5055     AlignAsType = Base;
5056 
5057   // With special case aggregates, only vector base types need alignment.
5058   if (AlignAsType) {
5059     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5060   }
5061 
5062   // Otherwise, we only need alignment for any aggregate type that
5063   // has an alignment requirement of >= 16 bytes.
5064   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5065     return CharUnits::fromQuantity(16);
5066   }
5067 
5068   return CharUnits::fromQuantity(8);
5069 }
5070 
5071 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5072 /// aggregate.  Base is set to the base element type, and Members is set
5073 /// to the number of base elements.
5074 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5075                                      uint64_t &Members) const {
5076   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5077     uint64_t NElements = AT->getSize().getZExtValue();
5078     if (NElements == 0)
5079       return false;
5080     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5081       return false;
5082     Members *= NElements;
5083   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5084     const RecordDecl *RD = RT->getDecl();
5085     if (RD->hasFlexibleArrayMember())
5086       return false;
5087 
5088     Members = 0;
5089 
5090     // If this is a C++ record, check the bases first.
5091     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5092       for (const auto &I : CXXRD->bases()) {
5093         // Ignore empty records.
5094         if (isEmptyRecord(getContext(), I.getType(), true))
5095           continue;
5096 
5097         uint64_t FldMembers;
5098         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5099           return false;
5100 
5101         Members += FldMembers;
5102       }
5103     }
5104 
5105     for (const auto *FD : RD->fields()) {
5106       // Ignore (non-zero arrays of) empty records.
5107       QualType FT = FD->getType();
5108       while (const ConstantArrayType *AT =
5109              getContext().getAsConstantArrayType(FT)) {
5110         if (AT->getSize().getZExtValue() == 0)
5111           return false;
5112         FT = AT->getElementType();
5113       }
5114       if (isEmptyRecord(getContext(), FT, true))
5115         continue;
5116 
5117       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5118       if (getContext().getLangOpts().CPlusPlus &&
5119           FD->isZeroLengthBitField(getContext()))
5120         continue;
5121 
5122       uint64_t FldMembers;
5123       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5124         return false;
5125 
5126       Members = (RD->isUnion() ?
5127                  std::max(Members, FldMembers) : Members + FldMembers);
5128     }
5129 
5130     if (!Base)
5131       return false;
5132 
5133     // Ensure there is no padding.
5134     if (getContext().getTypeSize(Base) * Members !=
5135         getContext().getTypeSize(Ty))
5136       return false;
5137   } else {
5138     Members = 1;
5139     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5140       Members = 2;
5141       Ty = CT->getElementType();
5142     }
5143 
5144     // Most ABIs only support float, double, and some vector type widths.
5145     if (!isHomogeneousAggregateBaseType(Ty))
5146       return false;
5147 
5148     // The base type must be the same for all members.  Types that
5149     // agree in both total size and mode (float vs. vector) are
5150     // treated as being equivalent here.
5151     const Type *TyPtr = Ty.getTypePtr();
5152     if (!Base) {
5153       Base = TyPtr;
5154       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5155       // so make sure to widen it explicitly.
5156       if (const VectorType *VT = Base->getAs<VectorType>()) {
5157         QualType EltTy = VT->getElementType();
5158         unsigned NumElements =
5159             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5160         Base = getContext()
5161                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5162                    .getTypePtr();
5163       }
5164     }
5165 
5166     if (Base->isVectorType() != TyPtr->isVectorType() ||
5167         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5168       return false;
5169   }
5170   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5171 }
5172 
5173 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5174   // Homogeneous aggregates for ELFv2 must have base types of float,
5175   // double, long double, or 128-bit vectors.
5176   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5177     if (BT->getKind() == BuiltinType::Float ||
5178         BT->getKind() == BuiltinType::Double ||
5179         BT->getKind() == BuiltinType::LongDouble ||
5180         (getContext().getTargetInfo().hasFloat128Type() &&
5181           (BT->getKind() == BuiltinType::Float128))) {
5182       if (IsSoftFloatABI)
5183         return false;
5184       return true;
5185     }
5186   }
5187   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5188     if (getContext().getTypeSize(VT) == 128)
5189       return true;
5190   }
5191   return false;
5192 }
5193 
5194 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5195     const Type *Base, uint64_t Members) const {
5196   // Vector and fp128 types require one register, other floating point types
5197   // require one or two registers depending on their size.
5198   uint32_t NumRegs =
5199       ((getContext().getTargetInfo().hasFloat128Type() &&
5200           Base->isFloat128Type()) ||
5201         Base->isVectorType()) ? 1
5202                               : (getContext().getTypeSize(Base) + 63) / 64;
5203 
5204   // Homogeneous Aggregates may occupy at most 8 registers.
5205   return Members * NumRegs <= 8;
5206 }
5207 
5208 ABIArgInfo
5209 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5210   Ty = useFirstFieldIfTransparentUnion(Ty);
5211 
5212   if (Ty->isAnyComplexType())
5213     return ABIArgInfo::getDirect();
5214 
5215   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5216   // or via reference (larger than 16 bytes).
5217   if (Ty->isVectorType()) {
5218     uint64_t Size = getContext().getTypeSize(Ty);
5219     if (Size > 128)
5220       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5221     else if (Size < 128) {
5222       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5223       return ABIArgInfo::getDirect(CoerceTy);
5224     }
5225   }
5226 
5227   if (const auto *EIT = Ty->getAs<ExtIntType>())
5228     if (EIT->getNumBits() > 128)
5229       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5230 
5231   if (isAggregateTypeForABI(Ty)) {
5232     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5233       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5234 
5235     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5236     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5237 
5238     // ELFv2 homogeneous aggregates are passed as array types.
5239     const Type *Base = nullptr;
5240     uint64_t Members = 0;
5241     if (Kind == ELFv2 &&
5242         isHomogeneousAggregate(Ty, Base, Members)) {
5243       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5244       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5245       return ABIArgInfo::getDirect(CoerceTy);
5246     }
5247 
5248     // If an aggregate may end up fully in registers, we do not
5249     // use the ByVal method, but pass the aggregate as array.
5250     // This is usually beneficial since we avoid forcing the
5251     // back-end to store the argument to memory.
5252     uint64_t Bits = getContext().getTypeSize(Ty);
5253     if (Bits > 0 && Bits <= 8 * GPRBits) {
5254       llvm::Type *CoerceTy;
5255 
5256       // Types up to 8 bytes are passed as integer type (which will be
5257       // properly aligned in the argument save area doubleword).
5258       if (Bits <= GPRBits)
5259         CoerceTy =
5260             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5261       // Larger types are passed as arrays, with the base type selected
5262       // according to the required alignment in the save area.
5263       else {
5264         uint64_t RegBits = ABIAlign * 8;
5265         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5266         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5267         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5268       }
5269 
5270       return ABIArgInfo::getDirect(CoerceTy);
5271     }
5272 
5273     // All other aggregates are passed ByVal.
5274     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5275                                    /*ByVal=*/true,
5276                                    /*Realign=*/TyAlign > ABIAlign);
5277   }
5278 
5279   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5280                                      : ABIArgInfo::getDirect());
5281 }
5282 
5283 ABIArgInfo
5284 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5285   if (RetTy->isVoidType())
5286     return ABIArgInfo::getIgnore();
5287 
5288   if (RetTy->isAnyComplexType())
5289     return ABIArgInfo::getDirect();
5290 
5291   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5292   // or via reference (larger than 16 bytes).
5293   if (RetTy->isVectorType()) {
5294     uint64_t Size = getContext().getTypeSize(RetTy);
5295     if (Size > 128)
5296       return getNaturalAlignIndirect(RetTy);
5297     else if (Size < 128) {
5298       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5299       return ABIArgInfo::getDirect(CoerceTy);
5300     }
5301   }
5302 
5303   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5304     if (EIT->getNumBits() > 128)
5305       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5306 
5307   if (isAggregateTypeForABI(RetTy)) {
5308     // ELFv2 homogeneous aggregates are returned as array types.
5309     const Type *Base = nullptr;
5310     uint64_t Members = 0;
5311     if (Kind == ELFv2 &&
5312         isHomogeneousAggregate(RetTy, Base, Members)) {
5313       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5314       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5315       return ABIArgInfo::getDirect(CoerceTy);
5316     }
5317 
5318     // ELFv2 small aggregates are returned in up to two registers.
5319     uint64_t Bits = getContext().getTypeSize(RetTy);
5320     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5321       if (Bits == 0)
5322         return ABIArgInfo::getIgnore();
5323 
5324       llvm::Type *CoerceTy;
5325       if (Bits > GPRBits) {
5326         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5327         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5328       } else
5329         CoerceTy =
5330             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5331       return ABIArgInfo::getDirect(CoerceTy);
5332     }
5333 
5334     // All other aggregates are returned indirectly.
5335     return getNaturalAlignIndirect(RetTy);
5336   }
5337 
5338   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5339                                         : ABIArgInfo::getDirect());
5340 }
5341 
5342 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5343 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5344                                       QualType Ty) const {
5345   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5346   TypeInfo.Align = getParamTypeAlignment(Ty);
5347 
5348   CharUnits SlotSize = CharUnits::fromQuantity(8);
5349 
5350   // If we have a complex type and the base type is smaller than 8 bytes,
5351   // the ABI calls for the real and imaginary parts to be right-adjusted
5352   // in separate doublewords.  However, Clang expects us to produce a
5353   // pointer to a structure with the two parts packed tightly.  So generate
5354   // loads of the real and imaginary parts relative to the va_list pointer,
5355   // and store them to a temporary structure.
5356   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5357     CharUnits EltSize = TypeInfo.Width / 2;
5358     if (EltSize < SlotSize) {
5359       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5360                                             SlotSize * 2, SlotSize,
5361                                             SlotSize, /*AllowHigher*/ true);
5362 
5363       Address RealAddr = Addr;
5364       Address ImagAddr = RealAddr;
5365       if (CGF.CGM.getDataLayout().isBigEndian()) {
5366         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5367                                                           SlotSize - EltSize);
5368         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5369                                                       2 * SlotSize - EltSize);
5370       } else {
5371         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5372       }
5373 
5374       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5375       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5376       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5377       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5378       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5379 
5380       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5381       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5382                              /*init*/ true);
5383       return Temp;
5384     }
5385   }
5386 
5387   // Otherwise, just use the general rule.
5388   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5389                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5390 }
5391 
5392 bool
5393 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5394   CodeGen::CodeGenFunction &CGF,
5395   llvm::Value *Address) const {
5396   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5397                                      /*IsAIX*/ false);
5398 }
5399 
5400 bool
5401 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5402                                                 llvm::Value *Address) const {
5403   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5404                                      /*IsAIX*/ false);
5405 }
5406 
5407 //===----------------------------------------------------------------------===//
5408 // AArch64 ABI Implementation
5409 //===----------------------------------------------------------------------===//
5410 
5411 namespace {
5412 
5413 class AArch64ABIInfo : public SwiftABIInfo {
5414 public:
5415   enum ABIKind {
5416     AAPCS = 0,
5417     DarwinPCS,
5418     Win64
5419   };
5420 
5421 private:
5422   ABIKind Kind;
5423 
5424 public:
5425   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5426     : SwiftABIInfo(CGT), Kind(Kind) {}
5427 
5428 private:
5429   ABIKind getABIKind() const { return Kind; }
5430   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5431 
5432   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5433   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5434   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5435   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5436   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5437                                          uint64_t Members) const override;
5438 
5439   bool isIllegalVectorType(QualType Ty) const;
5440 
5441   void computeInfo(CGFunctionInfo &FI) const override {
5442     if (!::classifyReturnType(getCXXABI(), FI, *this))
5443       FI.getReturnInfo() =
5444           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5445 
5446     for (auto &it : FI.arguments())
5447       it.info = classifyArgumentType(it.type);
5448   }
5449 
5450   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5451                           CodeGenFunction &CGF) const;
5452 
5453   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5454                          CodeGenFunction &CGF) const;
5455 
5456   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5457                     QualType Ty) const override {
5458     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5459     if (isa<llvm::ScalableVectorType>(BaseTy))
5460       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5461                                "currently not supported");
5462 
5463     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5464                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5465                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5466   }
5467 
5468   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5469                       QualType Ty) const override;
5470 
5471   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5472                                     bool asReturnValue) const override {
5473     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5474   }
5475   bool isSwiftErrorInRegister() const override {
5476     return true;
5477   }
5478 
5479   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5480                                  unsigned elts) const override;
5481 
5482   bool allowBFloatArgsAndRet() const override {
5483     return getTarget().hasBFloat16Type();
5484   }
5485 };
5486 
5487 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5488 public:
5489   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5490       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5491 
5492   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5493     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5494   }
5495 
5496   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5497     return 31;
5498   }
5499 
5500   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5501 
5502   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5503                            CodeGen::CodeGenModule &CGM) const override {
5504     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5505     if (!FD)
5506       return;
5507 
5508     const auto *TA = FD->getAttr<TargetAttr>();
5509     if (TA == nullptr)
5510       return;
5511 
5512     ParsedTargetAttr Attr = TA->parse();
5513     if (Attr.BranchProtection.empty())
5514       return;
5515 
5516     TargetInfo::BranchProtectionInfo BPI;
5517     StringRef Error;
5518     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5519                                                    BPI, Error);
5520     assert(Error.empty());
5521 
5522     auto *Fn = cast<llvm::Function>(GV);
5523     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5524     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5525 
5526     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5527       Fn->addFnAttr("sign-return-address-key",
5528                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5529                         ? "a_key"
5530                         : "b_key");
5531     }
5532 
5533     Fn->addFnAttr("branch-target-enforcement",
5534                   BPI.BranchTargetEnforcement ? "true" : "false");
5535   }
5536 };
5537 
5538 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5539 public:
5540   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5541       : AArch64TargetCodeGenInfo(CGT, K) {}
5542 
5543   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5544                            CodeGen::CodeGenModule &CGM) const override;
5545 
5546   void getDependentLibraryOption(llvm::StringRef Lib,
5547                                  llvm::SmallString<24> &Opt) const override {
5548     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5549   }
5550 
5551   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5552                                llvm::SmallString<32> &Opt) const override {
5553     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5554   }
5555 };
5556 
5557 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5558     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5559   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5560   if (GV->isDeclaration())
5561     return;
5562   addStackProbeTargetAttributes(D, GV, CGM);
5563 }
5564 }
5565 
5566 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5567   assert(Ty->isVectorType() && "expected vector type!");
5568 
5569   const auto *VT = Ty->castAs<VectorType>();
5570   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5571     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5572     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5573                BuiltinType::UChar &&
5574            "unexpected builtin type for SVE predicate!");
5575     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5576         llvm::Type::getInt1Ty(getVMContext()), 16));
5577   }
5578 
5579   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5580     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5581 
5582     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5583     llvm::ScalableVectorType *ResType = nullptr;
5584     switch (BT->getKind()) {
5585     default:
5586       llvm_unreachable("unexpected builtin type for SVE vector!");
5587     case BuiltinType::SChar:
5588     case BuiltinType::UChar:
5589       ResType = llvm::ScalableVectorType::get(
5590           llvm::Type::getInt8Ty(getVMContext()), 16);
5591       break;
5592     case BuiltinType::Short:
5593     case BuiltinType::UShort:
5594       ResType = llvm::ScalableVectorType::get(
5595           llvm::Type::getInt16Ty(getVMContext()), 8);
5596       break;
5597     case BuiltinType::Int:
5598     case BuiltinType::UInt:
5599       ResType = llvm::ScalableVectorType::get(
5600           llvm::Type::getInt32Ty(getVMContext()), 4);
5601       break;
5602     case BuiltinType::Long:
5603     case BuiltinType::ULong:
5604       ResType = llvm::ScalableVectorType::get(
5605           llvm::Type::getInt64Ty(getVMContext()), 2);
5606       break;
5607     case BuiltinType::Half:
5608       ResType = llvm::ScalableVectorType::get(
5609           llvm::Type::getHalfTy(getVMContext()), 8);
5610       break;
5611     case BuiltinType::Float:
5612       ResType = llvm::ScalableVectorType::get(
5613           llvm::Type::getFloatTy(getVMContext()), 4);
5614       break;
5615     case BuiltinType::Double:
5616       ResType = llvm::ScalableVectorType::get(
5617           llvm::Type::getDoubleTy(getVMContext()), 2);
5618       break;
5619     case BuiltinType::BFloat16:
5620       ResType = llvm::ScalableVectorType::get(
5621           llvm::Type::getBFloatTy(getVMContext()), 8);
5622       break;
5623     }
5624     return ABIArgInfo::getDirect(ResType);
5625   }
5626 
5627   uint64_t Size = getContext().getTypeSize(Ty);
5628   // Android promotes <2 x i8> to i16, not i32
5629   if (isAndroid() && (Size <= 16)) {
5630     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5631     return ABIArgInfo::getDirect(ResType);
5632   }
5633   if (Size <= 32) {
5634     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5635     return ABIArgInfo::getDirect(ResType);
5636   }
5637   if (Size == 64) {
5638     auto *ResType =
5639         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5640     return ABIArgInfo::getDirect(ResType);
5641   }
5642   if (Size == 128) {
5643     auto *ResType =
5644         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5645     return ABIArgInfo::getDirect(ResType);
5646   }
5647   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5648 }
5649 
5650 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5651   Ty = useFirstFieldIfTransparentUnion(Ty);
5652 
5653   // Handle illegal vector types here.
5654   if (isIllegalVectorType(Ty))
5655     return coerceIllegalVector(Ty);
5656 
5657   if (!isAggregateTypeForABI(Ty)) {
5658     // Treat an enum type as its underlying type.
5659     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5660       Ty = EnumTy->getDecl()->getIntegerType();
5661 
5662     if (const auto *EIT = Ty->getAs<ExtIntType>())
5663       if (EIT->getNumBits() > 128)
5664         return getNaturalAlignIndirect(Ty);
5665 
5666     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5667                 ? ABIArgInfo::getExtend(Ty)
5668                 : ABIArgInfo::getDirect());
5669   }
5670 
5671   // Structures with either a non-trivial destructor or a non-trivial
5672   // copy constructor are always indirect.
5673   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5674     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5675                                      CGCXXABI::RAA_DirectInMemory);
5676   }
5677 
5678   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5679   // elsewhere for GNU compatibility.
5680   uint64_t Size = getContext().getTypeSize(Ty);
5681   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5682   if (IsEmpty || Size == 0) {
5683     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5684       return ABIArgInfo::getIgnore();
5685 
5686     // GNU C mode. The only argument that gets ignored is an empty one with size
5687     // 0.
5688     if (IsEmpty && Size == 0)
5689       return ABIArgInfo::getIgnore();
5690     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5691   }
5692 
5693   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5694   const Type *Base = nullptr;
5695   uint64_t Members = 0;
5696   if (isHomogeneousAggregate(Ty, Base, Members)) {
5697     return ABIArgInfo::getDirect(
5698         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5699   }
5700 
5701   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5702   if (Size <= 128) {
5703     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5704     // same size and alignment.
5705     if (getTarget().isRenderScriptTarget()) {
5706       return coerceToIntArray(Ty, getContext(), getVMContext());
5707     }
5708     unsigned Alignment;
5709     if (Kind == AArch64ABIInfo::AAPCS) {
5710       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5711       Alignment = Alignment < 128 ? 64 : 128;
5712     } else {
5713       Alignment = std::max(getContext().getTypeAlign(Ty),
5714                            (unsigned)getTarget().getPointerWidth(0));
5715     }
5716     Size = llvm::alignTo(Size, Alignment);
5717 
5718     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5719     // For aggregates with 16-byte alignment, we use i128.
5720     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5721     return ABIArgInfo::getDirect(
5722         Size == Alignment ? BaseTy
5723                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5724   }
5725 
5726   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5727 }
5728 
5729 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5730                                               bool IsVariadic) const {
5731   if (RetTy->isVoidType())
5732     return ABIArgInfo::getIgnore();
5733 
5734   if (const auto *VT = RetTy->getAs<VectorType>()) {
5735     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5736         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5737       return coerceIllegalVector(RetTy);
5738   }
5739 
5740   // Large vector types should be returned via memory.
5741   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5742     return getNaturalAlignIndirect(RetTy);
5743 
5744   if (!isAggregateTypeForABI(RetTy)) {
5745     // Treat an enum type as its underlying type.
5746     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5747       RetTy = EnumTy->getDecl()->getIntegerType();
5748 
5749     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5750       if (EIT->getNumBits() > 128)
5751         return getNaturalAlignIndirect(RetTy);
5752 
5753     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5754                 ? ABIArgInfo::getExtend(RetTy)
5755                 : ABIArgInfo::getDirect());
5756   }
5757 
5758   uint64_t Size = getContext().getTypeSize(RetTy);
5759   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5760     return ABIArgInfo::getIgnore();
5761 
5762   const Type *Base = nullptr;
5763   uint64_t Members = 0;
5764   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5765       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5766         IsVariadic))
5767     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5768     return ABIArgInfo::getDirect();
5769 
5770   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5771   if (Size <= 128) {
5772     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5773     // same size and alignment.
5774     if (getTarget().isRenderScriptTarget()) {
5775       return coerceToIntArray(RetTy, getContext(), getVMContext());
5776     }
5777     unsigned Alignment = getContext().getTypeAlign(RetTy);
5778     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5779 
5780     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5781     // For aggregates with 16-byte alignment, we use i128.
5782     if (Alignment < 128 && Size == 128) {
5783       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5784       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5785     }
5786     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5787   }
5788 
5789   return getNaturalAlignIndirect(RetTy);
5790 }
5791 
5792 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5793 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5794   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5795     // Check whether VT is a fixed-length SVE vector. These types are
5796     // represented as scalable vectors in function args/return and must be
5797     // coerced from fixed vectors.
5798     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5799         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5800       return true;
5801 
5802     // Check whether VT is legal.
5803     unsigned NumElements = VT->getNumElements();
5804     uint64_t Size = getContext().getTypeSize(VT);
5805     // NumElements should be power of 2.
5806     if (!llvm::isPowerOf2_32(NumElements))
5807       return true;
5808 
5809     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5810     // vectors for some reason.
5811     llvm::Triple Triple = getTarget().getTriple();
5812     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5813         Triple.isOSBinFormatMachO())
5814       return Size <= 32;
5815 
5816     return Size != 64 && (Size != 128 || NumElements == 1);
5817   }
5818   return false;
5819 }
5820 
5821 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5822                                                llvm::Type *eltTy,
5823                                                unsigned elts) const {
5824   if (!llvm::isPowerOf2_32(elts))
5825     return false;
5826   if (totalSize.getQuantity() != 8 &&
5827       (totalSize.getQuantity() != 16 || elts == 1))
5828     return false;
5829   return true;
5830 }
5831 
5832 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5833   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5834   // point type or a short-vector type. This is the same as the 32-bit ABI,
5835   // but with the difference that any floating-point type is allowed,
5836   // including __fp16.
5837   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5838     if (BT->isFloatingPoint())
5839       return true;
5840   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5841     unsigned VecSize = getContext().getTypeSize(VT);
5842     if (VecSize == 64 || VecSize == 128)
5843       return true;
5844   }
5845   return false;
5846 }
5847 
5848 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5849                                                        uint64_t Members) const {
5850   return Members <= 4;
5851 }
5852 
5853 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5854                                             QualType Ty,
5855                                             CodeGenFunction &CGF) const {
5856   ABIArgInfo AI = classifyArgumentType(Ty);
5857   bool IsIndirect = AI.isIndirect();
5858 
5859   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5860   if (IsIndirect)
5861     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5862   else if (AI.getCoerceToType())
5863     BaseTy = AI.getCoerceToType();
5864 
5865   unsigned NumRegs = 1;
5866   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5867     BaseTy = ArrTy->getElementType();
5868     NumRegs = ArrTy->getNumElements();
5869   }
5870   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5871 
5872   // The AArch64 va_list type and handling is specified in the Procedure Call
5873   // Standard, section B.4:
5874   //
5875   // struct {
5876   //   void *__stack;
5877   //   void *__gr_top;
5878   //   void *__vr_top;
5879   //   int __gr_offs;
5880   //   int __vr_offs;
5881   // };
5882 
5883   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5884   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5885   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5886   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5887 
5888   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5889   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5890 
5891   Address reg_offs_p = Address::invalid();
5892   llvm::Value *reg_offs = nullptr;
5893   int reg_top_index;
5894   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5895   if (!IsFPR) {
5896     // 3 is the field number of __gr_offs
5897     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5898     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5899     reg_top_index = 1; // field number for __gr_top
5900     RegSize = llvm::alignTo(RegSize, 8);
5901   } else {
5902     // 4 is the field number of __vr_offs.
5903     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5904     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5905     reg_top_index = 2; // field number for __vr_top
5906     RegSize = 16 * NumRegs;
5907   }
5908 
5909   //=======================================
5910   // Find out where argument was passed
5911   //=======================================
5912 
5913   // If reg_offs >= 0 we're already using the stack for this type of
5914   // argument. We don't want to keep updating reg_offs (in case it overflows,
5915   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5916   // whatever they get).
5917   llvm::Value *UsingStack = nullptr;
5918   UsingStack = CGF.Builder.CreateICmpSGE(
5919       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5920 
5921   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5922 
5923   // Otherwise, at least some kind of argument could go in these registers, the
5924   // question is whether this particular type is too big.
5925   CGF.EmitBlock(MaybeRegBlock);
5926 
5927   // Integer arguments may need to correct register alignment (for example a
5928   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5929   // align __gr_offs to calculate the potential address.
5930   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5931     int Align = TyAlign.getQuantity();
5932 
5933     reg_offs = CGF.Builder.CreateAdd(
5934         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5935         "align_regoffs");
5936     reg_offs = CGF.Builder.CreateAnd(
5937         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5938         "aligned_regoffs");
5939   }
5940 
5941   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5942   // The fact that this is done unconditionally reflects the fact that
5943   // allocating an argument to the stack also uses up all the remaining
5944   // registers of the appropriate kind.
5945   llvm::Value *NewOffset = nullptr;
5946   NewOffset = CGF.Builder.CreateAdd(
5947       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5948   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5949 
5950   // Now we're in a position to decide whether this argument really was in
5951   // registers or not.
5952   llvm::Value *InRegs = nullptr;
5953   InRegs = CGF.Builder.CreateICmpSLE(
5954       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5955 
5956   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5957 
5958   //=======================================
5959   // Argument was in registers
5960   //=======================================
5961 
5962   // Now we emit the code for if the argument was originally passed in
5963   // registers. First start the appropriate block:
5964   CGF.EmitBlock(InRegBlock);
5965 
5966   llvm::Value *reg_top = nullptr;
5967   Address reg_top_p =
5968       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5969   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5970   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5971                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5972   Address RegAddr = Address::invalid();
5973   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5974 
5975   if (IsIndirect) {
5976     // If it's been passed indirectly (actually a struct), whatever we find from
5977     // stored registers or on the stack will actually be a struct **.
5978     MemTy = llvm::PointerType::getUnqual(MemTy);
5979   }
5980 
5981   const Type *Base = nullptr;
5982   uint64_t NumMembers = 0;
5983   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5984   if (IsHFA && NumMembers > 1) {
5985     // Homogeneous aggregates passed in registers will have their elements split
5986     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5987     // qN+1, ...). We reload and store into a temporary local variable
5988     // contiguously.
5989     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5990     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5991     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5992     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5993     Address Tmp = CGF.CreateTempAlloca(HFATy,
5994                                        std::max(TyAlign, BaseTyInfo.Align));
5995 
5996     // On big-endian platforms, the value will be right-aligned in its slot.
5997     int Offset = 0;
5998     if (CGF.CGM.getDataLayout().isBigEndian() &&
5999         BaseTyInfo.Width.getQuantity() < 16)
6000       Offset = 16 - BaseTyInfo.Width.getQuantity();
6001 
6002     for (unsigned i = 0; i < NumMembers; ++i) {
6003       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6004       Address LoadAddr =
6005         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6006       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6007 
6008       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6009 
6010       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6011       CGF.Builder.CreateStore(Elem, StoreAddr);
6012     }
6013 
6014     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6015   } else {
6016     // Otherwise the object is contiguous in memory.
6017 
6018     // It might be right-aligned in its slot.
6019     CharUnits SlotSize = BaseAddr.getAlignment();
6020     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6021         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6022         TySize < SlotSize) {
6023       CharUnits Offset = SlotSize - TySize;
6024       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6025     }
6026 
6027     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6028   }
6029 
6030   CGF.EmitBranch(ContBlock);
6031 
6032   //=======================================
6033   // Argument was on the stack
6034   //=======================================
6035   CGF.EmitBlock(OnStackBlock);
6036 
6037   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6038   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6039 
6040   // Again, stack arguments may need realignment. In this case both integer and
6041   // floating-point ones might be affected.
6042   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6043     int Align = TyAlign.getQuantity();
6044 
6045     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6046 
6047     OnStackPtr = CGF.Builder.CreateAdd(
6048         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6049         "align_stack");
6050     OnStackPtr = CGF.Builder.CreateAnd(
6051         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6052         "align_stack");
6053 
6054     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6055   }
6056   Address OnStackAddr(OnStackPtr,
6057                       std::max(CharUnits::fromQuantity(8), TyAlign));
6058 
6059   // All stack slots are multiples of 8 bytes.
6060   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6061   CharUnits StackSize;
6062   if (IsIndirect)
6063     StackSize = StackSlotSize;
6064   else
6065     StackSize = TySize.alignTo(StackSlotSize);
6066 
6067   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6068   llvm::Value *NewStack =
6069       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6070 
6071   // Write the new value of __stack for the next call to va_arg
6072   CGF.Builder.CreateStore(NewStack, stack_p);
6073 
6074   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6075       TySize < StackSlotSize) {
6076     CharUnits Offset = StackSlotSize - TySize;
6077     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6078   }
6079 
6080   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6081 
6082   CGF.EmitBranch(ContBlock);
6083 
6084   //=======================================
6085   // Tidy up
6086   //=======================================
6087   CGF.EmitBlock(ContBlock);
6088 
6089   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6090                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6091 
6092   if (IsIndirect)
6093     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6094                    TyAlign);
6095 
6096   return ResAddr;
6097 }
6098 
6099 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6100                                         CodeGenFunction &CGF) const {
6101   // The backend's lowering doesn't support va_arg for aggregates or
6102   // illegal vector types.  Lower VAArg here for these cases and use
6103   // the LLVM va_arg instruction for everything else.
6104   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6105     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6106 
6107   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6108   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6109 
6110   // Empty records are ignored for parameter passing purposes.
6111   if (isEmptyRecord(getContext(), Ty, true)) {
6112     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6113     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6114     return Addr;
6115   }
6116 
6117   // The size of the actual thing passed, which might end up just
6118   // being a pointer for indirect types.
6119   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6120 
6121   // Arguments bigger than 16 bytes which aren't homogeneous
6122   // aggregates should be passed indirectly.
6123   bool IsIndirect = false;
6124   if (TyInfo.Width.getQuantity() > 16) {
6125     const Type *Base = nullptr;
6126     uint64_t Members = 0;
6127     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6128   }
6129 
6130   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6131                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6132 }
6133 
6134 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6135                                     QualType Ty) const {
6136   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6137                           CGF.getContext().getTypeInfoInChars(Ty),
6138                           CharUnits::fromQuantity(8),
6139                           /*allowHigherAlign*/ false);
6140 }
6141 
6142 //===----------------------------------------------------------------------===//
6143 // ARM ABI Implementation
6144 //===----------------------------------------------------------------------===//
6145 
6146 namespace {
6147 
6148 class ARMABIInfo : public SwiftABIInfo {
6149 public:
6150   enum ABIKind {
6151     APCS = 0,
6152     AAPCS = 1,
6153     AAPCS_VFP = 2,
6154     AAPCS16_VFP = 3,
6155   };
6156 
6157 private:
6158   ABIKind Kind;
6159   bool IsFloatABISoftFP;
6160 
6161 public:
6162   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6163       : SwiftABIInfo(CGT), Kind(_Kind) {
6164     setCCs();
6165     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6166         CGT.getCodeGenOpts().FloatABI == ""; // default
6167   }
6168 
6169   bool isEABI() const {
6170     switch (getTarget().getTriple().getEnvironment()) {
6171     case llvm::Triple::Android:
6172     case llvm::Triple::EABI:
6173     case llvm::Triple::EABIHF:
6174     case llvm::Triple::GNUEABI:
6175     case llvm::Triple::GNUEABIHF:
6176     case llvm::Triple::MuslEABI:
6177     case llvm::Triple::MuslEABIHF:
6178       return true;
6179     default:
6180       return false;
6181     }
6182   }
6183 
6184   bool isEABIHF() const {
6185     switch (getTarget().getTriple().getEnvironment()) {
6186     case llvm::Triple::EABIHF:
6187     case llvm::Triple::GNUEABIHF:
6188     case llvm::Triple::MuslEABIHF:
6189       return true;
6190     default:
6191       return false;
6192     }
6193   }
6194 
6195   ABIKind getABIKind() const { return Kind; }
6196 
6197   bool allowBFloatArgsAndRet() const override {
6198     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6199   }
6200 
6201 private:
6202   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6203                                 unsigned functionCallConv) const;
6204   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6205                                   unsigned functionCallConv) const;
6206   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6207                                           uint64_t Members) const;
6208   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6209   bool isIllegalVectorType(QualType Ty) const;
6210   bool containsAnyFP16Vectors(QualType Ty) const;
6211 
6212   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6213   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6214                                          uint64_t Members) const override;
6215 
6216   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6217 
6218   void computeInfo(CGFunctionInfo &FI) const override;
6219 
6220   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6221                     QualType Ty) const override;
6222 
6223   llvm::CallingConv::ID getLLVMDefaultCC() const;
6224   llvm::CallingConv::ID getABIDefaultCC() const;
6225   void setCCs();
6226 
6227   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6228                                     bool asReturnValue) const override {
6229     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6230   }
6231   bool isSwiftErrorInRegister() const override {
6232     return true;
6233   }
6234   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6235                                  unsigned elts) const override;
6236 };
6237 
6238 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6239 public:
6240   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6241       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6242 
6243   const ARMABIInfo &getABIInfo() const {
6244     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6245   }
6246 
6247   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6248     return 13;
6249   }
6250 
6251   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6252     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6253   }
6254 
6255   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6256                                llvm::Value *Address) const override {
6257     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6258 
6259     // 0-15 are the 16 integer registers.
6260     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6261     return false;
6262   }
6263 
6264   unsigned getSizeOfUnwindException() const override {
6265     if (getABIInfo().isEABI()) return 88;
6266     return TargetCodeGenInfo::getSizeOfUnwindException();
6267   }
6268 
6269   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6270                            CodeGen::CodeGenModule &CGM) const override {
6271     if (GV->isDeclaration())
6272       return;
6273     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6274     if (!FD)
6275       return;
6276 
6277     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6278     if (!Attr)
6279       return;
6280 
6281     const char *Kind;
6282     switch (Attr->getInterrupt()) {
6283     case ARMInterruptAttr::Generic: Kind = ""; break;
6284     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6285     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6286     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6287     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6288     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6289     }
6290 
6291     llvm::Function *Fn = cast<llvm::Function>(GV);
6292 
6293     Fn->addFnAttr("interrupt", Kind);
6294 
6295     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6296     if (ABI == ARMABIInfo::APCS)
6297       return;
6298 
6299     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6300     // however this is not necessarily true on taking any interrupt. Instruct
6301     // the backend to perform a realignment as part of the function prologue.
6302     llvm::AttrBuilder B;
6303     B.addStackAlignmentAttr(8);
6304     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6305   }
6306 };
6307 
6308 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6309 public:
6310   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6311       : ARMTargetCodeGenInfo(CGT, K) {}
6312 
6313   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6314                            CodeGen::CodeGenModule &CGM) const override;
6315 
6316   void getDependentLibraryOption(llvm::StringRef Lib,
6317                                  llvm::SmallString<24> &Opt) const override {
6318     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6319   }
6320 
6321   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6322                                llvm::SmallString<32> &Opt) const override {
6323     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6324   }
6325 };
6326 
6327 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6328     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6329   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6330   if (GV->isDeclaration())
6331     return;
6332   addStackProbeTargetAttributes(D, GV, CGM);
6333 }
6334 }
6335 
6336 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6337   if (!::classifyReturnType(getCXXABI(), FI, *this))
6338     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6339                                             FI.getCallingConvention());
6340 
6341   for (auto &I : FI.arguments())
6342     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6343                                   FI.getCallingConvention());
6344 
6345 
6346   // Always honor user-specified calling convention.
6347   if (FI.getCallingConvention() != llvm::CallingConv::C)
6348     return;
6349 
6350   llvm::CallingConv::ID cc = getRuntimeCC();
6351   if (cc != llvm::CallingConv::C)
6352     FI.setEffectiveCallingConvention(cc);
6353 }
6354 
6355 /// Return the default calling convention that LLVM will use.
6356 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6357   // The default calling convention that LLVM will infer.
6358   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6359     return llvm::CallingConv::ARM_AAPCS_VFP;
6360   else if (isEABI())
6361     return llvm::CallingConv::ARM_AAPCS;
6362   else
6363     return llvm::CallingConv::ARM_APCS;
6364 }
6365 
6366 /// Return the calling convention that our ABI would like us to use
6367 /// as the C calling convention.
6368 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6369   switch (getABIKind()) {
6370   case APCS: return llvm::CallingConv::ARM_APCS;
6371   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6372   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6373   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6374   }
6375   llvm_unreachable("bad ABI kind");
6376 }
6377 
6378 void ARMABIInfo::setCCs() {
6379   assert(getRuntimeCC() == llvm::CallingConv::C);
6380 
6381   // Don't muddy up the IR with a ton of explicit annotations if
6382   // they'd just match what LLVM will infer from the triple.
6383   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6384   if (abiCC != getLLVMDefaultCC())
6385     RuntimeCC = abiCC;
6386 }
6387 
6388 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6389   uint64_t Size = getContext().getTypeSize(Ty);
6390   if (Size <= 32) {
6391     llvm::Type *ResType =
6392         llvm::Type::getInt32Ty(getVMContext());
6393     return ABIArgInfo::getDirect(ResType);
6394   }
6395   if (Size == 64 || Size == 128) {
6396     auto *ResType = llvm::FixedVectorType::get(
6397         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6398     return ABIArgInfo::getDirect(ResType);
6399   }
6400   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6401 }
6402 
6403 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6404                                                     const Type *Base,
6405                                                     uint64_t Members) const {
6406   assert(Base && "Base class should be set for homogeneous aggregate");
6407   // Base can be a floating-point or a vector.
6408   if (const VectorType *VT = Base->getAs<VectorType>()) {
6409     // FP16 vectors should be converted to integer vectors
6410     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6411       uint64_t Size = getContext().getTypeSize(VT);
6412       auto *NewVecTy = llvm::FixedVectorType::get(
6413           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6414       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6415       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6416     }
6417   }
6418   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6419 }
6420 
6421 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6422                                             unsigned functionCallConv) const {
6423   // 6.1.2.1 The following argument types are VFP CPRCs:
6424   //   A single-precision floating-point type (including promoted
6425   //   half-precision types); A double-precision floating-point type;
6426   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6427   //   with a Base Type of a single- or double-precision floating-point type,
6428   //   64-bit containerized vectors or 128-bit containerized vectors with one
6429   //   to four Elements.
6430   // Variadic functions should always marshal to the base standard.
6431   bool IsAAPCS_VFP =
6432       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6433 
6434   Ty = useFirstFieldIfTransparentUnion(Ty);
6435 
6436   // Handle illegal vector types here.
6437   if (isIllegalVectorType(Ty))
6438     return coerceIllegalVector(Ty);
6439 
6440   if (!isAggregateTypeForABI(Ty)) {
6441     // Treat an enum type as its underlying type.
6442     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6443       Ty = EnumTy->getDecl()->getIntegerType();
6444     }
6445 
6446     if (const auto *EIT = Ty->getAs<ExtIntType>())
6447       if (EIT->getNumBits() > 64)
6448         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6449 
6450     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6451                                               : ABIArgInfo::getDirect());
6452   }
6453 
6454   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6455     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6456   }
6457 
6458   // Ignore empty records.
6459   if (isEmptyRecord(getContext(), Ty, true))
6460     return ABIArgInfo::getIgnore();
6461 
6462   if (IsAAPCS_VFP) {
6463     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6464     // into VFP registers.
6465     const Type *Base = nullptr;
6466     uint64_t Members = 0;
6467     if (isHomogeneousAggregate(Ty, Base, Members))
6468       return classifyHomogeneousAggregate(Ty, Base, Members);
6469   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6470     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6471     // this convention even for a variadic function: the backend will use GPRs
6472     // if needed.
6473     const Type *Base = nullptr;
6474     uint64_t Members = 0;
6475     if (isHomogeneousAggregate(Ty, Base, Members)) {
6476       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6477       llvm::Type *Ty =
6478         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6479       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6480     }
6481   }
6482 
6483   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6484       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6485     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6486     // bigger than 128-bits, they get placed in space allocated by the caller,
6487     // and a pointer is passed.
6488     return ABIArgInfo::getIndirect(
6489         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6490   }
6491 
6492   // Support byval for ARM.
6493   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6494   // most 8-byte. We realign the indirect argument if type alignment is bigger
6495   // than ABI alignment.
6496   uint64_t ABIAlign = 4;
6497   uint64_t TyAlign;
6498   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6499       getABIKind() == ARMABIInfo::AAPCS) {
6500     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6501     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6502   } else {
6503     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6504   }
6505   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6506     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6507     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6508                                    /*ByVal=*/true,
6509                                    /*Realign=*/TyAlign > ABIAlign);
6510   }
6511 
6512   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6513   // same size and alignment.
6514   if (getTarget().isRenderScriptTarget()) {
6515     return coerceToIntArray(Ty, getContext(), getVMContext());
6516   }
6517 
6518   // Otherwise, pass by coercing to a structure of the appropriate size.
6519   llvm::Type* ElemTy;
6520   unsigned SizeRegs;
6521   // FIXME: Try to match the types of the arguments more accurately where
6522   // we can.
6523   if (TyAlign <= 4) {
6524     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6525     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6526   } else {
6527     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6528     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6529   }
6530 
6531   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6532 }
6533 
6534 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6535                               llvm::LLVMContext &VMContext) {
6536   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6537   // is called integer-like if its size is less than or equal to one word, and
6538   // the offset of each of its addressable sub-fields is zero.
6539 
6540   uint64_t Size = Context.getTypeSize(Ty);
6541 
6542   // Check that the type fits in a word.
6543   if (Size > 32)
6544     return false;
6545 
6546   // FIXME: Handle vector types!
6547   if (Ty->isVectorType())
6548     return false;
6549 
6550   // Float types are never treated as "integer like".
6551   if (Ty->isRealFloatingType())
6552     return false;
6553 
6554   // If this is a builtin or pointer type then it is ok.
6555   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6556     return true;
6557 
6558   // Small complex integer types are "integer like".
6559   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6560     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6561 
6562   // Single element and zero sized arrays should be allowed, by the definition
6563   // above, but they are not.
6564 
6565   // Otherwise, it must be a record type.
6566   const RecordType *RT = Ty->getAs<RecordType>();
6567   if (!RT) return false;
6568 
6569   // Ignore records with flexible arrays.
6570   const RecordDecl *RD = RT->getDecl();
6571   if (RD->hasFlexibleArrayMember())
6572     return false;
6573 
6574   // Check that all sub-fields are at offset 0, and are themselves "integer
6575   // like".
6576   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6577 
6578   bool HadField = false;
6579   unsigned idx = 0;
6580   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6581        i != e; ++i, ++idx) {
6582     const FieldDecl *FD = *i;
6583 
6584     // Bit-fields are not addressable, we only need to verify they are "integer
6585     // like". We still have to disallow a subsequent non-bitfield, for example:
6586     //   struct { int : 0; int x }
6587     // is non-integer like according to gcc.
6588     if (FD->isBitField()) {
6589       if (!RD->isUnion())
6590         HadField = true;
6591 
6592       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6593         return false;
6594 
6595       continue;
6596     }
6597 
6598     // Check if this field is at offset 0.
6599     if (Layout.getFieldOffset(idx) != 0)
6600       return false;
6601 
6602     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6603       return false;
6604 
6605     // Only allow at most one field in a structure. This doesn't match the
6606     // wording above, but follows gcc in situations with a field following an
6607     // empty structure.
6608     if (!RD->isUnion()) {
6609       if (HadField)
6610         return false;
6611 
6612       HadField = true;
6613     }
6614   }
6615 
6616   return true;
6617 }
6618 
6619 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6620                                           unsigned functionCallConv) const {
6621 
6622   // Variadic functions should always marshal to the base standard.
6623   bool IsAAPCS_VFP =
6624       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6625 
6626   if (RetTy->isVoidType())
6627     return ABIArgInfo::getIgnore();
6628 
6629   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6630     // Large vector types should be returned via memory.
6631     if (getContext().getTypeSize(RetTy) > 128)
6632       return getNaturalAlignIndirect(RetTy);
6633     // TODO: FP16/BF16 vectors should be converted to integer vectors
6634     // This check is similar  to isIllegalVectorType - refactor?
6635     if ((!getTarget().hasLegalHalfType() &&
6636         (VT->getElementType()->isFloat16Type() ||
6637          VT->getElementType()->isHalfType())) ||
6638         (IsFloatABISoftFP &&
6639          VT->getElementType()->isBFloat16Type()))
6640       return coerceIllegalVector(RetTy);
6641   }
6642 
6643   if (!isAggregateTypeForABI(RetTy)) {
6644     // Treat an enum type as its underlying type.
6645     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6646       RetTy = EnumTy->getDecl()->getIntegerType();
6647 
6648     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6649       if (EIT->getNumBits() > 64)
6650         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6651 
6652     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6653                                                 : ABIArgInfo::getDirect();
6654   }
6655 
6656   // Are we following APCS?
6657   if (getABIKind() == APCS) {
6658     if (isEmptyRecord(getContext(), RetTy, false))
6659       return ABIArgInfo::getIgnore();
6660 
6661     // Complex types are all returned as packed integers.
6662     //
6663     // FIXME: Consider using 2 x vector types if the back end handles them
6664     // correctly.
6665     if (RetTy->isAnyComplexType())
6666       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6667           getVMContext(), getContext().getTypeSize(RetTy)));
6668 
6669     // Integer like structures are returned in r0.
6670     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6671       // Return in the smallest viable integer type.
6672       uint64_t Size = getContext().getTypeSize(RetTy);
6673       if (Size <= 8)
6674         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6675       if (Size <= 16)
6676         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6677       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6678     }
6679 
6680     // Otherwise return in memory.
6681     return getNaturalAlignIndirect(RetTy);
6682   }
6683 
6684   // Otherwise this is an AAPCS variant.
6685 
6686   if (isEmptyRecord(getContext(), RetTy, true))
6687     return ABIArgInfo::getIgnore();
6688 
6689   // Check for homogeneous aggregates with AAPCS-VFP.
6690   if (IsAAPCS_VFP) {
6691     const Type *Base = nullptr;
6692     uint64_t Members = 0;
6693     if (isHomogeneousAggregate(RetTy, Base, Members))
6694       return classifyHomogeneousAggregate(RetTy, Base, Members);
6695   }
6696 
6697   // Aggregates <= 4 bytes are returned in r0; other aggregates
6698   // are returned indirectly.
6699   uint64_t Size = getContext().getTypeSize(RetTy);
6700   if (Size <= 32) {
6701     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6702     // same size and alignment.
6703     if (getTarget().isRenderScriptTarget()) {
6704       return coerceToIntArray(RetTy, getContext(), getVMContext());
6705     }
6706     if (getDataLayout().isBigEndian())
6707       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6708       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6709 
6710     // Return in the smallest viable integer type.
6711     if (Size <= 8)
6712       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6713     if (Size <= 16)
6714       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6715     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6716   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6717     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6718     llvm::Type *CoerceTy =
6719         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6720     return ABIArgInfo::getDirect(CoerceTy);
6721   }
6722 
6723   return getNaturalAlignIndirect(RetTy);
6724 }
6725 
6726 /// isIllegalVector - check whether Ty is an illegal vector type.
6727 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6728   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6729     // On targets that don't support half, fp16 or bfloat, they are expanded
6730     // into float, and we don't want the ABI to depend on whether or not they
6731     // are supported in hardware. Thus return false to coerce vectors of these
6732     // types into integer vectors.
6733     // We do not depend on hasLegalHalfType for bfloat as it is a
6734     // separate IR type.
6735     if ((!getTarget().hasLegalHalfType() &&
6736         (VT->getElementType()->isFloat16Type() ||
6737          VT->getElementType()->isHalfType())) ||
6738         (IsFloatABISoftFP &&
6739          VT->getElementType()->isBFloat16Type()))
6740       return true;
6741     if (isAndroid()) {
6742       // Android shipped using Clang 3.1, which supported a slightly different
6743       // vector ABI. The primary differences were that 3-element vector types
6744       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6745       // accepts that legacy behavior for Android only.
6746       // Check whether VT is legal.
6747       unsigned NumElements = VT->getNumElements();
6748       // NumElements should be power of 2 or equal to 3.
6749       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6750         return true;
6751     } else {
6752       // Check whether VT is legal.
6753       unsigned NumElements = VT->getNumElements();
6754       uint64_t Size = getContext().getTypeSize(VT);
6755       // NumElements should be power of 2.
6756       if (!llvm::isPowerOf2_32(NumElements))
6757         return true;
6758       // Size should be greater than 32 bits.
6759       return Size <= 32;
6760     }
6761   }
6762   return false;
6763 }
6764 
6765 /// Return true if a type contains any 16-bit floating point vectors
6766 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6767   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6768     uint64_t NElements = AT->getSize().getZExtValue();
6769     if (NElements == 0)
6770       return false;
6771     return containsAnyFP16Vectors(AT->getElementType());
6772   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6773     const RecordDecl *RD = RT->getDecl();
6774 
6775     // If this is a C++ record, check the bases first.
6776     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6777       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6778             return containsAnyFP16Vectors(B.getType());
6779           }))
6780         return true;
6781 
6782     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6783           return FD && containsAnyFP16Vectors(FD->getType());
6784         }))
6785       return true;
6786 
6787     return false;
6788   } else {
6789     if (const VectorType *VT = Ty->getAs<VectorType>())
6790       return (VT->getElementType()->isFloat16Type() ||
6791               VT->getElementType()->isBFloat16Type() ||
6792               VT->getElementType()->isHalfType());
6793     return false;
6794   }
6795 }
6796 
6797 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6798                                            llvm::Type *eltTy,
6799                                            unsigned numElts) const {
6800   if (!llvm::isPowerOf2_32(numElts))
6801     return false;
6802   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6803   if (size > 64)
6804     return false;
6805   if (vectorSize.getQuantity() != 8 &&
6806       (vectorSize.getQuantity() != 16 || numElts == 1))
6807     return false;
6808   return true;
6809 }
6810 
6811 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6812   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6813   // double, or 64-bit or 128-bit vectors.
6814   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6815     if (BT->getKind() == BuiltinType::Float ||
6816         BT->getKind() == BuiltinType::Double ||
6817         BT->getKind() == BuiltinType::LongDouble)
6818       return true;
6819   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6820     unsigned VecSize = getContext().getTypeSize(VT);
6821     if (VecSize == 64 || VecSize == 128)
6822       return true;
6823   }
6824   return false;
6825 }
6826 
6827 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6828                                                    uint64_t Members) const {
6829   return Members <= 4;
6830 }
6831 
6832 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6833                                         bool acceptHalf) const {
6834   // Give precedence to user-specified calling conventions.
6835   if (callConvention != llvm::CallingConv::C)
6836     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6837   else
6838     return (getABIKind() == AAPCS_VFP) ||
6839            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6840 }
6841 
6842 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6843                               QualType Ty) const {
6844   CharUnits SlotSize = CharUnits::fromQuantity(4);
6845 
6846   // Empty records are ignored for parameter passing purposes.
6847   if (isEmptyRecord(getContext(), Ty, true)) {
6848     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6849     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6850     return Addr;
6851   }
6852 
6853   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6854   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6855 
6856   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6857   bool IsIndirect = false;
6858   const Type *Base = nullptr;
6859   uint64_t Members = 0;
6860   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6861     IsIndirect = true;
6862 
6863   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6864   // allocated by the caller.
6865   } else if (TySize > CharUnits::fromQuantity(16) &&
6866              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6867              !isHomogeneousAggregate(Ty, Base, Members)) {
6868     IsIndirect = true;
6869 
6870   // Otherwise, bound the type's ABI alignment.
6871   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6872   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6873   // Our callers should be prepared to handle an under-aligned address.
6874   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6875              getABIKind() == ARMABIInfo::AAPCS) {
6876     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6877     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6878   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6879     // ARMv7k allows type alignment up to 16 bytes.
6880     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6881     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6882   } else {
6883     TyAlignForABI = CharUnits::fromQuantity(4);
6884   }
6885 
6886   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6887   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6888                           SlotSize, /*AllowHigherAlign*/ true);
6889 }
6890 
6891 //===----------------------------------------------------------------------===//
6892 // NVPTX ABI Implementation
6893 //===----------------------------------------------------------------------===//
6894 
6895 namespace {
6896 
6897 class NVPTXTargetCodeGenInfo;
6898 
6899 class NVPTXABIInfo : public ABIInfo {
6900   NVPTXTargetCodeGenInfo &CGInfo;
6901 
6902 public:
6903   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6904       : ABIInfo(CGT), CGInfo(Info) {}
6905 
6906   ABIArgInfo classifyReturnType(QualType RetTy) const;
6907   ABIArgInfo classifyArgumentType(QualType Ty) const;
6908 
6909   void computeInfo(CGFunctionInfo &FI) const override;
6910   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6911                     QualType Ty) const override;
6912   bool isUnsupportedType(QualType T) const;
6913   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6914 };
6915 
6916 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6917 public:
6918   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6919       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6920 
6921   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6922                            CodeGen::CodeGenModule &M) const override;
6923   bool shouldEmitStaticExternCAliases() const override;
6924 
6925   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6926     // On the device side, surface reference is represented as an object handle
6927     // in 64-bit integer.
6928     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6929   }
6930 
6931   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6932     // On the device side, texture reference is represented as an object handle
6933     // in 64-bit integer.
6934     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6935   }
6936 
6937   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6938                                               LValue Src) const override {
6939     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6940     return true;
6941   }
6942 
6943   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6944                                               LValue Src) const override {
6945     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6946     return true;
6947   }
6948 
6949 private:
6950   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6951   // resulting MDNode to the nvvm.annotations MDNode.
6952   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6953                               int Operand);
6954 
6955   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6956                                            LValue Src) {
6957     llvm::Value *Handle = nullptr;
6958     llvm::Constant *C =
6959         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6960     // Lookup `addrspacecast` through the constant pointer if any.
6961     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6962       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6963     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6964       // Load the handle from the specific global variable using
6965       // `nvvm.texsurf.handle.internal` intrinsic.
6966       Handle = CGF.EmitRuntimeCall(
6967           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6968                                {GV->getType()}),
6969           {GV}, "texsurf_handle");
6970     } else
6971       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6972     CGF.EmitStoreOfScalar(Handle, Dst);
6973   }
6974 };
6975 
6976 /// Checks if the type is unsupported directly by the current target.
6977 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6978   ASTContext &Context = getContext();
6979   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6980     return true;
6981   if (!Context.getTargetInfo().hasFloat128Type() &&
6982       (T->isFloat128Type() ||
6983        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6984     return true;
6985   if (const auto *EIT = T->getAs<ExtIntType>())
6986     return EIT->getNumBits() >
6987            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6988   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6989       Context.getTypeSize(T) > 64U)
6990     return true;
6991   if (const auto *AT = T->getAsArrayTypeUnsafe())
6992     return isUnsupportedType(AT->getElementType());
6993   const auto *RT = T->getAs<RecordType>();
6994   if (!RT)
6995     return false;
6996   const RecordDecl *RD = RT->getDecl();
6997 
6998   // If this is a C++ record, check the bases first.
6999   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7000     for (const CXXBaseSpecifier &I : CXXRD->bases())
7001       if (isUnsupportedType(I.getType()))
7002         return true;
7003 
7004   for (const FieldDecl *I : RD->fields())
7005     if (isUnsupportedType(I->getType()))
7006       return true;
7007   return false;
7008 }
7009 
7010 /// Coerce the given type into an array with maximum allowed size of elements.
7011 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7012                                                    unsigned MaxSize) const {
7013   // Alignment and Size are measured in bits.
7014   const uint64_t Size = getContext().getTypeSize(Ty);
7015   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7016   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7017   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7018   const uint64_t NumElements = (Size + Div - 1) / Div;
7019   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7020 }
7021 
7022 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7023   if (RetTy->isVoidType())
7024     return ABIArgInfo::getIgnore();
7025 
7026   if (getContext().getLangOpts().OpenMP &&
7027       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7028     return coerceToIntArrayWithLimit(RetTy, 64);
7029 
7030   // note: this is different from default ABI
7031   if (!RetTy->isScalarType())
7032     return ABIArgInfo::getDirect();
7033 
7034   // Treat an enum type as its underlying type.
7035   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7036     RetTy = EnumTy->getDecl()->getIntegerType();
7037 
7038   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7039                                                : ABIArgInfo::getDirect());
7040 }
7041 
7042 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7043   // Treat an enum type as its underlying type.
7044   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7045     Ty = EnumTy->getDecl()->getIntegerType();
7046 
7047   // Return aggregates type as indirect by value
7048   if (isAggregateTypeForABI(Ty)) {
7049     // Under CUDA device compilation, tex/surf builtin types are replaced with
7050     // object types and passed directly.
7051     if (getContext().getLangOpts().CUDAIsDevice) {
7052       if (Ty->isCUDADeviceBuiltinSurfaceType())
7053         return ABIArgInfo::getDirect(
7054             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7055       if (Ty->isCUDADeviceBuiltinTextureType())
7056         return ABIArgInfo::getDirect(
7057             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7058     }
7059     return getNaturalAlignIndirect(Ty, /* byval */ true);
7060   }
7061 
7062   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7063     if ((EIT->getNumBits() > 128) ||
7064         (!getContext().getTargetInfo().hasInt128Type() &&
7065          EIT->getNumBits() > 64))
7066       return getNaturalAlignIndirect(Ty, /* byval */ true);
7067   }
7068 
7069   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7070                                             : ABIArgInfo::getDirect());
7071 }
7072 
7073 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7074   if (!getCXXABI().classifyReturnType(FI))
7075     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7076   for (auto &I : FI.arguments())
7077     I.info = classifyArgumentType(I.type);
7078 
7079   // Always honor user-specified calling convention.
7080   if (FI.getCallingConvention() != llvm::CallingConv::C)
7081     return;
7082 
7083   FI.setEffectiveCallingConvention(getRuntimeCC());
7084 }
7085 
7086 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7087                                 QualType Ty) const {
7088   llvm_unreachable("NVPTX does not support varargs");
7089 }
7090 
7091 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7092     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7093   if (GV->isDeclaration())
7094     return;
7095   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7096   if (VD) {
7097     if (M.getLangOpts().CUDA) {
7098       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7099         addNVVMMetadata(GV, "surface", 1);
7100       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7101         addNVVMMetadata(GV, "texture", 1);
7102       return;
7103     }
7104   }
7105 
7106   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7107   if (!FD) return;
7108 
7109   llvm::Function *F = cast<llvm::Function>(GV);
7110 
7111   // Perform special handling in OpenCL mode
7112   if (M.getLangOpts().OpenCL) {
7113     // Use OpenCL function attributes to check for kernel functions
7114     // By default, all functions are device functions
7115     if (FD->hasAttr<OpenCLKernelAttr>()) {
7116       // OpenCL __kernel functions get kernel metadata
7117       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7118       addNVVMMetadata(F, "kernel", 1);
7119       // And kernel functions are not subject to inlining
7120       F->addFnAttr(llvm::Attribute::NoInline);
7121     }
7122   }
7123 
7124   // Perform special handling in CUDA mode.
7125   if (M.getLangOpts().CUDA) {
7126     // CUDA __global__ functions get a kernel metadata entry.  Since
7127     // __global__ functions cannot be called from the device, we do not
7128     // need to set the noinline attribute.
7129     if (FD->hasAttr<CUDAGlobalAttr>()) {
7130       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7131       addNVVMMetadata(F, "kernel", 1);
7132     }
7133     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7134       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7135       llvm::APSInt MaxThreads(32);
7136       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7137       if (MaxThreads > 0)
7138         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7139 
7140       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7141       // not specified in __launch_bounds__ or if the user specified a 0 value,
7142       // we don't have to add a PTX directive.
7143       if (Attr->getMinBlocks()) {
7144         llvm::APSInt MinBlocks(32);
7145         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7146         if (MinBlocks > 0)
7147           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7148           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7149       }
7150     }
7151   }
7152 }
7153 
7154 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7155                                              StringRef Name, int Operand) {
7156   llvm::Module *M = GV->getParent();
7157   llvm::LLVMContext &Ctx = M->getContext();
7158 
7159   // Get "nvvm.annotations" metadata node
7160   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7161 
7162   llvm::Metadata *MDVals[] = {
7163       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7164       llvm::ConstantAsMetadata::get(
7165           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7166   // Append metadata to nvvm.annotations
7167   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7168 }
7169 
7170 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7171   return false;
7172 }
7173 }
7174 
7175 //===----------------------------------------------------------------------===//
7176 // SystemZ ABI Implementation
7177 //===----------------------------------------------------------------------===//
7178 
7179 namespace {
7180 
7181 class SystemZABIInfo : public SwiftABIInfo {
7182   bool HasVector;
7183   bool IsSoftFloatABI;
7184 
7185 public:
7186   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7187     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7188 
7189   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7190   bool isCompoundType(QualType Ty) const;
7191   bool isVectorArgumentType(QualType Ty) const;
7192   bool isFPArgumentType(QualType Ty) const;
7193   QualType GetSingleElementType(QualType Ty) const;
7194 
7195   ABIArgInfo classifyReturnType(QualType RetTy) const;
7196   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7197 
7198   void computeInfo(CGFunctionInfo &FI) const override {
7199     if (!getCXXABI().classifyReturnType(FI))
7200       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7201     for (auto &I : FI.arguments())
7202       I.info = classifyArgumentType(I.type);
7203   }
7204 
7205   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7206                     QualType Ty) const override;
7207 
7208   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7209                                     bool asReturnValue) const override {
7210     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7211   }
7212   bool isSwiftErrorInRegister() const override {
7213     return false;
7214   }
7215 };
7216 
7217 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7218 public:
7219   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7220       : TargetCodeGenInfo(
7221             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7222 };
7223 
7224 }
7225 
7226 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7227   // Treat an enum type as its underlying type.
7228   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7229     Ty = EnumTy->getDecl()->getIntegerType();
7230 
7231   // Promotable integer types are required to be promoted by the ABI.
7232   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7233     return true;
7234 
7235   if (const auto *EIT = Ty->getAs<ExtIntType>())
7236     if (EIT->getNumBits() < 64)
7237       return true;
7238 
7239   // 32-bit values must also be promoted.
7240   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7241     switch (BT->getKind()) {
7242     case BuiltinType::Int:
7243     case BuiltinType::UInt:
7244       return true;
7245     default:
7246       return false;
7247     }
7248   return false;
7249 }
7250 
7251 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7252   return (Ty->isAnyComplexType() ||
7253           Ty->isVectorType() ||
7254           isAggregateTypeForABI(Ty));
7255 }
7256 
7257 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7258   return (HasVector &&
7259           Ty->isVectorType() &&
7260           getContext().getTypeSize(Ty) <= 128);
7261 }
7262 
7263 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7264   if (IsSoftFloatABI)
7265     return false;
7266 
7267   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7268     switch (BT->getKind()) {
7269     case BuiltinType::Float:
7270     case BuiltinType::Double:
7271       return true;
7272     default:
7273       return false;
7274     }
7275 
7276   return false;
7277 }
7278 
7279 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7280   const RecordType *RT = Ty->getAs<RecordType>();
7281 
7282   if (RT && RT->isStructureOrClassType()) {
7283     const RecordDecl *RD = RT->getDecl();
7284     QualType Found;
7285 
7286     // If this is a C++ record, check the bases first.
7287     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7288       for (const auto &I : CXXRD->bases()) {
7289         QualType Base = I.getType();
7290 
7291         // Empty bases don't affect things either way.
7292         if (isEmptyRecord(getContext(), Base, true))
7293           continue;
7294 
7295         if (!Found.isNull())
7296           return Ty;
7297         Found = GetSingleElementType(Base);
7298       }
7299 
7300     // Check the fields.
7301     for (const auto *FD : RD->fields()) {
7302       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7303       // Unlike isSingleElementStruct(), empty structure and array fields
7304       // do count.  So do anonymous bitfields that aren't zero-sized.
7305       if (getContext().getLangOpts().CPlusPlus &&
7306           FD->isZeroLengthBitField(getContext()))
7307         continue;
7308       // Like isSingleElementStruct(), ignore C++20 empty data members.
7309       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7310           isEmptyRecord(getContext(), FD->getType(), true))
7311         continue;
7312 
7313       // Unlike isSingleElementStruct(), arrays do not count.
7314       // Nested structures still do though.
7315       if (!Found.isNull())
7316         return Ty;
7317       Found = GetSingleElementType(FD->getType());
7318     }
7319 
7320     // Unlike isSingleElementStruct(), trailing padding is allowed.
7321     // An 8-byte aligned struct s { float f; } is passed as a double.
7322     if (!Found.isNull())
7323       return Found;
7324   }
7325 
7326   return Ty;
7327 }
7328 
7329 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7330                                   QualType Ty) const {
7331   // Assume that va_list type is correct; should be pointer to LLVM type:
7332   // struct {
7333   //   i64 __gpr;
7334   //   i64 __fpr;
7335   //   i8 *__overflow_arg_area;
7336   //   i8 *__reg_save_area;
7337   // };
7338 
7339   // Every non-vector argument occupies 8 bytes and is passed by preference
7340   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7341   // always passed on the stack.
7342   Ty = getContext().getCanonicalType(Ty);
7343   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7344   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7345   llvm::Type *DirectTy = ArgTy;
7346   ABIArgInfo AI = classifyArgumentType(Ty);
7347   bool IsIndirect = AI.isIndirect();
7348   bool InFPRs = false;
7349   bool IsVector = false;
7350   CharUnits UnpaddedSize;
7351   CharUnits DirectAlign;
7352   if (IsIndirect) {
7353     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7354     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7355   } else {
7356     if (AI.getCoerceToType())
7357       ArgTy = AI.getCoerceToType();
7358     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7359     IsVector = ArgTy->isVectorTy();
7360     UnpaddedSize = TyInfo.Width;
7361     DirectAlign = TyInfo.Align;
7362   }
7363   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7364   if (IsVector && UnpaddedSize > PaddedSize)
7365     PaddedSize = CharUnits::fromQuantity(16);
7366   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7367 
7368   CharUnits Padding = (PaddedSize - UnpaddedSize);
7369 
7370   llvm::Type *IndexTy = CGF.Int64Ty;
7371   llvm::Value *PaddedSizeV =
7372     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7373 
7374   if (IsVector) {
7375     // Work out the address of a vector argument on the stack.
7376     // Vector arguments are always passed in the high bits of a
7377     // single (8 byte) or double (16 byte) stack slot.
7378     Address OverflowArgAreaPtr =
7379         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7380     Address OverflowArgArea =
7381       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7382               TyInfo.Align);
7383     Address MemAddr =
7384       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7385 
7386     // Update overflow_arg_area_ptr pointer
7387     llvm::Value *NewOverflowArgArea =
7388       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7389                             "overflow_arg_area");
7390     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7391 
7392     return MemAddr;
7393   }
7394 
7395   assert(PaddedSize.getQuantity() == 8);
7396 
7397   unsigned MaxRegs, RegCountField, RegSaveIndex;
7398   CharUnits RegPadding;
7399   if (InFPRs) {
7400     MaxRegs = 4; // Maximum of 4 FPR arguments
7401     RegCountField = 1; // __fpr
7402     RegSaveIndex = 16; // save offset for f0
7403     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7404   } else {
7405     MaxRegs = 5; // Maximum of 5 GPR arguments
7406     RegCountField = 0; // __gpr
7407     RegSaveIndex = 2; // save offset for r2
7408     RegPadding = Padding; // values are passed in the low bits of a GPR
7409   }
7410 
7411   Address RegCountPtr =
7412       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7413   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7414   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7415   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7416                                                  "fits_in_regs");
7417 
7418   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7419   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7420   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7421   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7422 
7423   // Emit code to load the value if it was passed in registers.
7424   CGF.EmitBlock(InRegBlock);
7425 
7426   // Work out the address of an argument register.
7427   llvm::Value *ScaledRegCount =
7428     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7429   llvm::Value *RegBase =
7430     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7431                                       + RegPadding.getQuantity());
7432   llvm::Value *RegOffset =
7433     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7434   Address RegSaveAreaPtr =
7435       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7436   llvm::Value *RegSaveArea =
7437     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7438   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7439                                            "raw_reg_addr"),
7440                      PaddedSize);
7441   Address RegAddr =
7442     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7443 
7444   // Update the register count
7445   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7446   llvm::Value *NewRegCount =
7447     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7448   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7449   CGF.EmitBranch(ContBlock);
7450 
7451   // Emit code to load the value if it was passed in memory.
7452   CGF.EmitBlock(InMemBlock);
7453 
7454   // Work out the address of a stack argument.
7455   Address OverflowArgAreaPtr =
7456       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7457   Address OverflowArgArea =
7458     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7459             PaddedSize);
7460   Address RawMemAddr =
7461     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7462   Address MemAddr =
7463     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7464 
7465   // Update overflow_arg_area_ptr pointer
7466   llvm::Value *NewOverflowArgArea =
7467     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7468                           "overflow_arg_area");
7469   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7470   CGF.EmitBranch(ContBlock);
7471 
7472   // Return the appropriate result.
7473   CGF.EmitBlock(ContBlock);
7474   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7475                                  MemAddr, InMemBlock, "va_arg.addr");
7476 
7477   if (IsIndirect)
7478     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7479                       TyInfo.Align);
7480 
7481   return ResAddr;
7482 }
7483 
7484 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7485   if (RetTy->isVoidType())
7486     return ABIArgInfo::getIgnore();
7487   if (isVectorArgumentType(RetTy))
7488     return ABIArgInfo::getDirect();
7489   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7490     return getNaturalAlignIndirect(RetTy);
7491   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7492                                                : ABIArgInfo::getDirect());
7493 }
7494 
7495 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7496   // Handle the generic C++ ABI.
7497   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7498     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7499 
7500   // Integers and enums are extended to full register width.
7501   if (isPromotableIntegerTypeForABI(Ty))
7502     return ABIArgInfo::getExtend(Ty);
7503 
7504   // Handle vector types and vector-like structure types.  Note that
7505   // as opposed to float-like structure types, we do not allow any
7506   // padding for vector-like structures, so verify the sizes match.
7507   uint64_t Size = getContext().getTypeSize(Ty);
7508   QualType SingleElementTy = GetSingleElementType(Ty);
7509   if (isVectorArgumentType(SingleElementTy) &&
7510       getContext().getTypeSize(SingleElementTy) == Size)
7511     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7512 
7513   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7514   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7515     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7516 
7517   // Handle small structures.
7518   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7519     // Structures with flexible arrays have variable length, so really
7520     // fail the size test above.
7521     const RecordDecl *RD = RT->getDecl();
7522     if (RD->hasFlexibleArrayMember())
7523       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7524 
7525     // The structure is passed as an unextended integer, a float, or a double.
7526     llvm::Type *PassTy;
7527     if (isFPArgumentType(SingleElementTy)) {
7528       assert(Size == 32 || Size == 64);
7529       if (Size == 32)
7530         PassTy = llvm::Type::getFloatTy(getVMContext());
7531       else
7532         PassTy = llvm::Type::getDoubleTy(getVMContext());
7533     } else
7534       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7535     return ABIArgInfo::getDirect(PassTy);
7536   }
7537 
7538   // Non-structure compounds are passed indirectly.
7539   if (isCompoundType(Ty))
7540     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7541 
7542   return ABIArgInfo::getDirect(nullptr);
7543 }
7544 
7545 //===----------------------------------------------------------------------===//
7546 // MSP430 ABI Implementation
7547 //===----------------------------------------------------------------------===//
7548 
7549 namespace {
7550 
7551 class MSP430ABIInfo : public DefaultABIInfo {
7552   static ABIArgInfo complexArgInfo() {
7553     ABIArgInfo Info = ABIArgInfo::getDirect();
7554     Info.setCanBeFlattened(false);
7555     return Info;
7556   }
7557 
7558 public:
7559   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7560 
7561   ABIArgInfo classifyReturnType(QualType RetTy) const {
7562     if (RetTy->isAnyComplexType())
7563       return complexArgInfo();
7564 
7565     return DefaultABIInfo::classifyReturnType(RetTy);
7566   }
7567 
7568   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7569     if (RetTy->isAnyComplexType())
7570       return complexArgInfo();
7571 
7572     return DefaultABIInfo::classifyArgumentType(RetTy);
7573   }
7574 
7575   // Just copy the original implementations because
7576   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7577   void computeInfo(CGFunctionInfo &FI) const override {
7578     if (!getCXXABI().classifyReturnType(FI))
7579       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7580     for (auto &I : FI.arguments())
7581       I.info = classifyArgumentType(I.type);
7582   }
7583 
7584   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7585                     QualType Ty) const override {
7586     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7587   }
7588 };
7589 
7590 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7591 public:
7592   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7593       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7594   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7595                            CodeGen::CodeGenModule &M) const override;
7596 };
7597 
7598 }
7599 
7600 void MSP430TargetCodeGenInfo::setTargetAttributes(
7601     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7602   if (GV->isDeclaration())
7603     return;
7604   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7605     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7606     if (!InterruptAttr)
7607       return;
7608 
7609     // Handle 'interrupt' attribute:
7610     llvm::Function *F = cast<llvm::Function>(GV);
7611 
7612     // Step 1: Set ISR calling convention.
7613     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7614 
7615     // Step 2: Add attributes goodness.
7616     F->addFnAttr(llvm::Attribute::NoInline);
7617     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7618   }
7619 }
7620 
7621 //===----------------------------------------------------------------------===//
7622 // MIPS ABI Implementation.  This works for both little-endian and
7623 // big-endian variants.
7624 //===----------------------------------------------------------------------===//
7625 
7626 namespace {
7627 class MipsABIInfo : public ABIInfo {
7628   bool IsO32;
7629   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7630   void CoerceToIntArgs(uint64_t TySize,
7631                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7632   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7633   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7634   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7635 public:
7636   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7637     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7638     StackAlignInBytes(IsO32 ? 8 : 16) {}
7639 
7640   ABIArgInfo classifyReturnType(QualType RetTy) const;
7641   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7642   void computeInfo(CGFunctionInfo &FI) const override;
7643   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7644                     QualType Ty) const override;
7645   ABIArgInfo extendType(QualType Ty) const;
7646 };
7647 
7648 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7649   unsigned SizeOfUnwindException;
7650 public:
7651   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7652       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7653         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7654 
7655   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7656     return 29;
7657   }
7658 
7659   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7660                            CodeGen::CodeGenModule &CGM) const override {
7661     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7662     if (!FD) return;
7663     llvm::Function *Fn = cast<llvm::Function>(GV);
7664 
7665     if (FD->hasAttr<MipsLongCallAttr>())
7666       Fn->addFnAttr("long-call");
7667     else if (FD->hasAttr<MipsShortCallAttr>())
7668       Fn->addFnAttr("short-call");
7669 
7670     // Other attributes do not have a meaning for declarations.
7671     if (GV->isDeclaration())
7672       return;
7673 
7674     if (FD->hasAttr<Mips16Attr>()) {
7675       Fn->addFnAttr("mips16");
7676     }
7677     else if (FD->hasAttr<NoMips16Attr>()) {
7678       Fn->addFnAttr("nomips16");
7679     }
7680 
7681     if (FD->hasAttr<MicroMipsAttr>())
7682       Fn->addFnAttr("micromips");
7683     else if (FD->hasAttr<NoMicroMipsAttr>())
7684       Fn->addFnAttr("nomicromips");
7685 
7686     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7687     if (!Attr)
7688       return;
7689 
7690     const char *Kind;
7691     switch (Attr->getInterrupt()) {
7692     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7693     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7694     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7695     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7696     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7697     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7698     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7699     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7700     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7701     }
7702 
7703     Fn->addFnAttr("interrupt", Kind);
7704 
7705   }
7706 
7707   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7708                                llvm::Value *Address) const override;
7709 
7710   unsigned getSizeOfUnwindException() const override {
7711     return SizeOfUnwindException;
7712   }
7713 };
7714 }
7715 
7716 void MipsABIInfo::CoerceToIntArgs(
7717     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7718   llvm::IntegerType *IntTy =
7719     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7720 
7721   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7722   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7723     ArgList.push_back(IntTy);
7724 
7725   // If necessary, add one more integer type to ArgList.
7726   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7727 
7728   if (R)
7729     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7730 }
7731 
7732 // In N32/64, an aligned double precision floating point field is passed in
7733 // a register.
7734 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7735   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7736 
7737   if (IsO32) {
7738     CoerceToIntArgs(TySize, ArgList);
7739     return llvm::StructType::get(getVMContext(), ArgList);
7740   }
7741 
7742   if (Ty->isComplexType())
7743     return CGT.ConvertType(Ty);
7744 
7745   const RecordType *RT = Ty->getAs<RecordType>();
7746 
7747   // Unions/vectors are passed in integer registers.
7748   if (!RT || !RT->isStructureOrClassType()) {
7749     CoerceToIntArgs(TySize, ArgList);
7750     return llvm::StructType::get(getVMContext(), ArgList);
7751   }
7752 
7753   const RecordDecl *RD = RT->getDecl();
7754   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7755   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7756 
7757   uint64_t LastOffset = 0;
7758   unsigned idx = 0;
7759   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7760 
7761   // Iterate over fields in the struct/class and check if there are any aligned
7762   // double fields.
7763   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7764        i != e; ++i, ++idx) {
7765     const QualType Ty = i->getType();
7766     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7767 
7768     if (!BT || BT->getKind() != BuiltinType::Double)
7769       continue;
7770 
7771     uint64_t Offset = Layout.getFieldOffset(idx);
7772     if (Offset % 64) // Ignore doubles that are not aligned.
7773       continue;
7774 
7775     // Add ((Offset - LastOffset) / 64) args of type i64.
7776     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7777       ArgList.push_back(I64);
7778 
7779     // Add double type.
7780     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7781     LastOffset = Offset + 64;
7782   }
7783 
7784   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7785   ArgList.append(IntArgList.begin(), IntArgList.end());
7786 
7787   return llvm::StructType::get(getVMContext(), ArgList);
7788 }
7789 
7790 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7791                                         uint64_t Offset) const {
7792   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7793     return nullptr;
7794 
7795   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7796 }
7797 
7798 ABIArgInfo
7799 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7800   Ty = useFirstFieldIfTransparentUnion(Ty);
7801 
7802   uint64_t OrigOffset = Offset;
7803   uint64_t TySize = getContext().getTypeSize(Ty);
7804   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7805 
7806   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7807                    (uint64_t)StackAlignInBytes);
7808   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7809   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7810 
7811   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7812     // Ignore empty aggregates.
7813     if (TySize == 0)
7814       return ABIArgInfo::getIgnore();
7815 
7816     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7817       Offset = OrigOffset + MinABIStackAlignInBytes;
7818       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7819     }
7820 
7821     // If we have reached here, aggregates are passed directly by coercing to
7822     // another structure type. Padding is inserted if the offset of the
7823     // aggregate is unaligned.
7824     ABIArgInfo ArgInfo =
7825         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7826                               getPaddingType(OrigOffset, CurrOffset));
7827     ArgInfo.setInReg(true);
7828     return ArgInfo;
7829   }
7830 
7831   // Treat an enum type as its underlying type.
7832   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7833     Ty = EnumTy->getDecl()->getIntegerType();
7834 
7835   // Make sure we pass indirectly things that are too large.
7836   if (const auto *EIT = Ty->getAs<ExtIntType>())
7837     if (EIT->getNumBits() > 128 ||
7838         (EIT->getNumBits() > 64 &&
7839          !getContext().getTargetInfo().hasInt128Type()))
7840       return getNaturalAlignIndirect(Ty);
7841 
7842   // All integral types are promoted to the GPR width.
7843   if (Ty->isIntegralOrEnumerationType())
7844     return extendType(Ty);
7845 
7846   return ABIArgInfo::getDirect(
7847       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7848 }
7849 
7850 llvm::Type*
7851 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7852   const RecordType *RT = RetTy->getAs<RecordType>();
7853   SmallVector<llvm::Type*, 8> RTList;
7854 
7855   if (RT && RT->isStructureOrClassType()) {
7856     const RecordDecl *RD = RT->getDecl();
7857     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7858     unsigned FieldCnt = Layout.getFieldCount();
7859 
7860     // N32/64 returns struct/classes in floating point registers if the
7861     // following conditions are met:
7862     // 1. The size of the struct/class is no larger than 128-bit.
7863     // 2. The struct/class has one or two fields all of which are floating
7864     //    point types.
7865     // 3. The offset of the first field is zero (this follows what gcc does).
7866     //
7867     // Any other composite results are returned in integer registers.
7868     //
7869     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7870       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7871       for (; b != e; ++b) {
7872         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7873 
7874         if (!BT || !BT->isFloatingPoint())
7875           break;
7876 
7877         RTList.push_back(CGT.ConvertType(b->getType()));
7878       }
7879 
7880       if (b == e)
7881         return llvm::StructType::get(getVMContext(), RTList,
7882                                      RD->hasAttr<PackedAttr>());
7883 
7884       RTList.clear();
7885     }
7886   }
7887 
7888   CoerceToIntArgs(Size, RTList);
7889   return llvm::StructType::get(getVMContext(), RTList);
7890 }
7891 
7892 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7893   uint64_t Size = getContext().getTypeSize(RetTy);
7894 
7895   if (RetTy->isVoidType())
7896     return ABIArgInfo::getIgnore();
7897 
7898   // O32 doesn't treat zero-sized structs differently from other structs.
7899   // However, N32/N64 ignores zero sized return values.
7900   if (!IsO32 && Size == 0)
7901     return ABIArgInfo::getIgnore();
7902 
7903   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7904     if (Size <= 128) {
7905       if (RetTy->isAnyComplexType())
7906         return ABIArgInfo::getDirect();
7907 
7908       // O32 returns integer vectors in registers and N32/N64 returns all small
7909       // aggregates in registers.
7910       if (!IsO32 ||
7911           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7912         ABIArgInfo ArgInfo =
7913             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7914         ArgInfo.setInReg(true);
7915         return ArgInfo;
7916       }
7917     }
7918 
7919     return getNaturalAlignIndirect(RetTy);
7920   }
7921 
7922   // Treat an enum type as its underlying type.
7923   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7924     RetTy = EnumTy->getDecl()->getIntegerType();
7925 
7926   // Make sure we pass indirectly things that are too large.
7927   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7928     if (EIT->getNumBits() > 128 ||
7929         (EIT->getNumBits() > 64 &&
7930          !getContext().getTargetInfo().hasInt128Type()))
7931       return getNaturalAlignIndirect(RetTy);
7932 
7933   if (isPromotableIntegerTypeForABI(RetTy))
7934     return ABIArgInfo::getExtend(RetTy);
7935 
7936   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7937       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7938     return ABIArgInfo::getSignExtend(RetTy);
7939 
7940   return ABIArgInfo::getDirect();
7941 }
7942 
7943 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7944   ABIArgInfo &RetInfo = FI.getReturnInfo();
7945   if (!getCXXABI().classifyReturnType(FI))
7946     RetInfo = classifyReturnType(FI.getReturnType());
7947 
7948   // Check if a pointer to an aggregate is passed as a hidden argument.
7949   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7950 
7951   for (auto &I : FI.arguments())
7952     I.info = classifyArgumentType(I.type, Offset);
7953 }
7954 
7955 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7956                                QualType OrigTy) const {
7957   QualType Ty = OrigTy;
7958 
7959   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7960   // Pointers are also promoted in the same way but this only matters for N32.
7961   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7962   unsigned PtrWidth = getTarget().getPointerWidth(0);
7963   bool DidPromote = false;
7964   if ((Ty->isIntegerType() &&
7965           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7966       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7967     DidPromote = true;
7968     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7969                                             Ty->isSignedIntegerType());
7970   }
7971 
7972   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7973 
7974   // The alignment of things in the argument area is never larger than
7975   // StackAlignInBytes.
7976   TyInfo.Align =
7977     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7978 
7979   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7980   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7981 
7982   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7983                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7984 
7985 
7986   // If there was a promotion, "unpromote" into a temporary.
7987   // TODO: can we just use a pointer into a subset of the original slot?
7988   if (DidPromote) {
7989     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7990     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7991 
7992     // Truncate down to the right width.
7993     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7994                                                  : CGF.IntPtrTy);
7995     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7996     if (OrigTy->isPointerType())
7997       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7998 
7999     CGF.Builder.CreateStore(V, Temp);
8000     Addr = Temp;
8001   }
8002 
8003   return Addr;
8004 }
8005 
8006 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8007   int TySize = getContext().getTypeSize(Ty);
8008 
8009   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8010   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8011     return ABIArgInfo::getSignExtend(Ty);
8012 
8013   return ABIArgInfo::getExtend(Ty);
8014 }
8015 
8016 bool
8017 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8018                                                llvm::Value *Address) const {
8019   // This information comes from gcc's implementation, which seems to
8020   // as canonical as it gets.
8021 
8022   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8023   // are aliased to pairs of single-precision FP registers.
8024   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8025 
8026   // 0-31 are the general purpose registers, $0 - $31.
8027   // 32-63 are the floating-point registers, $f0 - $f31.
8028   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8029   // 66 is the (notional, I think) register for signal-handler return.
8030   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8031 
8032   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8033   // They are one bit wide and ignored here.
8034 
8035   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8036   // (coprocessor 1 is the FP unit)
8037   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8038   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8039   // 176-181 are the DSP accumulator registers.
8040   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8041   return false;
8042 }
8043 
8044 //===----------------------------------------------------------------------===//
8045 // AVR ABI Implementation.
8046 //===----------------------------------------------------------------------===//
8047 
8048 namespace {
8049 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8050 public:
8051   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8052       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8053 
8054   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8055                            CodeGen::CodeGenModule &CGM) const override {
8056     if (GV->isDeclaration())
8057       return;
8058     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8059     if (!FD) return;
8060     auto *Fn = cast<llvm::Function>(GV);
8061 
8062     if (FD->getAttr<AVRInterruptAttr>())
8063       Fn->addFnAttr("interrupt");
8064 
8065     if (FD->getAttr<AVRSignalAttr>())
8066       Fn->addFnAttr("signal");
8067   }
8068 };
8069 }
8070 
8071 //===----------------------------------------------------------------------===//
8072 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8073 // Currently subclassed only to implement custom OpenCL C function attribute
8074 // handling.
8075 //===----------------------------------------------------------------------===//
8076 
8077 namespace {
8078 
8079 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8080 public:
8081   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8082     : DefaultTargetCodeGenInfo(CGT) {}
8083 
8084   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8085                            CodeGen::CodeGenModule &M) const override;
8086 };
8087 
8088 void TCETargetCodeGenInfo::setTargetAttributes(
8089     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8090   if (GV->isDeclaration())
8091     return;
8092   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8093   if (!FD) return;
8094 
8095   llvm::Function *F = cast<llvm::Function>(GV);
8096 
8097   if (M.getLangOpts().OpenCL) {
8098     if (FD->hasAttr<OpenCLKernelAttr>()) {
8099       // OpenCL C Kernel functions are not subject to inlining
8100       F->addFnAttr(llvm::Attribute::NoInline);
8101       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8102       if (Attr) {
8103         // Convert the reqd_work_group_size() attributes to metadata.
8104         llvm::LLVMContext &Context = F->getContext();
8105         llvm::NamedMDNode *OpenCLMetadata =
8106             M.getModule().getOrInsertNamedMetadata(
8107                 "opencl.kernel_wg_size_info");
8108 
8109         SmallVector<llvm::Metadata *, 5> Operands;
8110         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8111 
8112         Operands.push_back(
8113             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8114                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8115         Operands.push_back(
8116             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8117                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8118         Operands.push_back(
8119             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8120                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8121 
8122         // Add a boolean constant operand for "required" (true) or "hint"
8123         // (false) for implementing the work_group_size_hint attr later.
8124         // Currently always true as the hint is not yet implemented.
8125         Operands.push_back(
8126             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8127         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8128       }
8129     }
8130   }
8131 }
8132 
8133 }
8134 
8135 //===----------------------------------------------------------------------===//
8136 // Hexagon ABI Implementation
8137 //===----------------------------------------------------------------------===//
8138 
8139 namespace {
8140 
8141 class HexagonABIInfo : public DefaultABIInfo {
8142 public:
8143   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8144 
8145 private:
8146   ABIArgInfo classifyReturnType(QualType RetTy) const;
8147   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8148   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8149 
8150   void computeInfo(CGFunctionInfo &FI) const override;
8151 
8152   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8153                     QualType Ty) const override;
8154   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8155                               QualType Ty) const;
8156   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8157                               QualType Ty) const;
8158   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8159                                    QualType Ty) const;
8160 };
8161 
8162 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8163 public:
8164   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8165       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8166 
8167   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8168     return 29;
8169   }
8170 
8171   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8172                            CodeGen::CodeGenModule &GCM) const override {
8173     if (GV->isDeclaration())
8174       return;
8175     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8176     if (!FD)
8177       return;
8178   }
8179 };
8180 
8181 } // namespace
8182 
8183 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8184   unsigned RegsLeft = 6;
8185   if (!getCXXABI().classifyReturnType(FI))
8186     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8187   for (auto &I : FI.arguments())
8188     I.info = classifyArgumentType(I.type, &RegsLeft);
8189 }
8190 
8191 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8192   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8193                        " through registers");
8194 
8195   if (*RegsLeft == 0)
8196     return false;
8197 
8198   if (Size <= 32) {
8199     (*RegsLeft)--;
8200     return true;
8201   }
8202 
8203   if (2 <= (*RegsLeft & (~1U))) {
8204     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8205     return true;
8206   }
8207 
8208   // Next available register was r5 but candidate was greater than 32-bits so it
8209   // has to go on the stack. However we still consume r5
8210   if (*RegsLeft == 1)
8211     *RegsLeft = 0;
8212 
8213   return false;
8214 }
8215 
8216 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8217                                                 unsigned *RegsLeft) const {
8218   if (!isAggregateTypeForABI(Ty)) {
8219     // Treat an enum type as its underlying type.
8220     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8221       Ty = EnumTy->getDecl()->getIntegerType();
8222 
8223     uint64_t Size = getContext().getTypeSize(Ty);
8224     if (Size <= 64)
8225       HexagonAdjustRegsLeft(Size, RegsLeft);
8226 
8227     if (Size > 64 && Ty->isExtIntType())
8228       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8229 
8230     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8231                                              : ABIArgInfo::getDirect();
8232   }
8233 
8234   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8235     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8236 
8237   // Ignore empty records.
8238   if (isEmptyRecord(getContext(), Ty, true))
8239     return ABIArgInfo::getIgnore();
8240 
8241   uint64_t Size = getContext().getTypeSize(Ty);
8242   unsigned Align = getContext().getTypeAlign(Ty);
8243 
8244   if (Size > 64)
8245     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8246 
8247   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8248     Align = Size <= 32 ? 32 : 64;
8249   if (Size <= Align) {
8250     // Pass in the smallest viable integer type.
8251     if (!llvm::isPowerOf2_64(Size))
8252       Size = llvm::NextPowerOf2(Size);
8253     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8254   }
8255   return DefaultABIInfo::classifyArgumentType(Ty);
8256 }
8257 
8258 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8259   if (RetTy->isVoidType())
8260     return ABIArgInfo::getIgnore();
8261 
8262   const TargetInfo &T = CGT.getTarget();
8263   uint64_t Size = getContext().getTypeSize(RetTy);
8264 
8265   if (RetTy->getAs<VectorType>()) {
8266     // HVX vectors are returned in vector registers or register pairs.
8267     if (T.hasFeature("hvx")) {
8268       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8269       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8270       if (Size == VecSize || Size == 2*VecSize)
8271         return ABIArgInfo::getDirectInReg();
8272     }
8273     // Large vector types should be returned via memory.
8274     if (Size > 64)
8275       return getNaturalAlignIndirect(RetTy);
8276   }
8277 
8278   if (!isAggregateTypeForABI(RetTy)) {
8279     // Treat an enum type as its underlying type.
8280     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8281       RetTy = EnumTy->getDecl()->getIntegerType();
8282 
8283     if (Size > 64 && RetTy->isExtIntType())
8284       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8285 
8286     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8287                                                 : ABIArgInfo::getDirect();
8288   }
8289 
8290   if (isEmptyRecord(getContext(), RetTy, true))
8291     return ABIArgInfo::getIgnore();
8292 
8293   // Aggregates <= 8 bytes are returned in registers, other aggregates
8294   // are returned indirectly.
8295   if (Size <= 64) {
8296     // Return in the smallest viable integer type.
8297     if (!llvm::isPowerOf2_64(Size))
8298       Size = llvm::NextPowerOf2(Size);
8299     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8300   }
8301   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8302 }
8303 
8304 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8305                                             Address VAListAddr,
8306                                             QualType Ty) const {
8307   // Load the overflow area pointer.
8308   Address __overflow_area_pointer_p =
8309       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8310   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8311       __overflow_area_pointer_p, "__overflow_area_pointer");
8312 
8313   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8314   if (Align > 4) {
8315     // Alignment should be a power of 2.
8316     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8317 
8318     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8319     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8320 
8321     // Add offset to the current pointer to access the argument.
8322     __overflow_area_pointer =
8323         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8324     llvm::Value *AsInt =
8325         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8326 
8327     // Create a mask which should be "AND"ed
8328     // with (overflow_arg_area + align - 1)
8329     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8330     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8331         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8332         "__overflow_area_pointer.align");
8333   }
8334 
8335   // Get the type of the argument from memory and bitcast
8336   // overflow area pointer to the argument type.
8337   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8338   Address AddrTyped = CGF.Builder.CreateBitCast(
8339       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8340       llvm::PointerType::getUnqual(PTy));
8341 
8342   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8343   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8344 
8345   __overflow_area_pointer = CGF.Builder.CreateGEP(
8346       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8347       "__overflow_area_pointer.next");
8348   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8349 
8350   return AddrTyped;
8351 }
8352 
8353 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8354                                             Address VAListAddr,
8355                                             QualType Ty) const {
8356   // FIXME: Need to handle alignment
8357   llvm::Type *BP = CGF.Int8PtrTy;
8358   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8359   CGBuilderTy &Builder = CGF.Builder;
8360   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8361   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8362   // Handle address alignment for type alignment > 32 bits
8363   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8364   if (TyAlign > 4) {
8365     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8366     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8367     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8368     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8369     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8370   }
8371   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8372   Address AddrTyped = Builder.CreateBitCast(
8373       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8374 
8375   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8376   llvm::Value *NextAddr = Builder.CreateGEP(
8377       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8378   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8379 
8380   return AddrTyped;
8381 }
8382 
8383 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8384                                                  Address VAListAddr,
8385                                                  QualType Ty) const {
8386   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8387 
8388   if (ArgSize > 8)
8389     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8390 
8391   // Here we have check if the argument is in register area or
8392   // in overflow area.
8393   // If the saved register area pointer + argsize rounded up to alignment >
8394   // saved register area end pointer, argument is in overflow area.
8395   unsigned RegsLeft = 6;
8396   Ty = CGF.getContext().getCanonicalType(Ty);
8397   (void)classifyArgumentType(Ty, &RegsLeft);
8398 
8399   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8400   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8401   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8402   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8403 
8404   // Get rounded size of the argument.GCC does not allow vararg of
8405   // size < 4 bytes. We follow the same logic here.
8406   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8407   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8408 
8409   // Argument may be in saved register area
8410   CGF.EmitBlock(MaybeRegBlock);
8411 
8412   // Load the current saved register area pointer.
8413   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8414       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8415   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8416       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8417 
8418   // Load the saved register area end pointer.
8419   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8420       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8421   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8422       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8423 
8424   // If the size of argument is > 4 bytes, check if the stack
8425   // location is aligned to 8 bytes
8426   if (ArgAlign > 4) {
8427 
8428     llvm::Value *__current_saved_reg_area_pointer_int =
8429         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8430                                    CGF.Int32Ty);
8431 
8432     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8433         __current_saved_reg_area_pointer_int,
8434         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8435         "align_current_saved_reg_area_pointer");
8436 
8437     __current_saved_reg_area_pointer_int =
8438         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8439                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8440                               "align_current_saved_reg_area_pointer");
8441 
8442     __current_saved_reg_area_pointer =
8443         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8444                                    __current_saved_reg_area_pointer->getType(),
8445                                    "align_current_saved_reg_area_pointer");
8446   }
8447 
8448   llvm::Value *__new_saved_reg_area_pointer =
8449       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8450                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8451                             "__new_saved_reg_area_pointer");
8452 
8453   llvm::Value *UsingStack = 0;
8454   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8455                                          __saved_reg_area_end_pointer);
8456 
8457   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8458 
8459   // Argument in saved register area
8460   // Implement the block where argument is in register saved area
8461   CGF.EmitBlock(InRegBlock);
8462 
8463   llvm::Type *PTy = CGF.ConvertType(Ty);
8464   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8465       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8466 
8467   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8468                           __current_saved_reg_area_pointer_p);
8469 
8470   CGF.EmitBranch(ContBlock);
8471 
8472   // Argument in overflow area
8473   // Implement the block where the argument is in overflow area.
8474   CGF.EmitBlock(OnStackBlock);
8475 
8476   // Load the overflow area pointer
8477   Address __overflow_area_pointer_p =
8478       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8479   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8480       __overflow_area_pointer_p, "__overflow_area_pointer");
8481 
8482   // Align the overflow area pointer according to the alignment of the argument
8483   if (ArgAlign > 4) {
8484     llvm::Value *__overflow_area_pointer_int =
8485         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8486 
8487     __overflow_area_pointer_int =
8488         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8489                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8490                               "align_overflow_area_pointer");
8491 
8492     __overflow_area_pointer_int =
8493         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8494                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8495                               "align_overflow_area_pointer");
8496 
8497     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8498         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8499         "align_overflow_area_pointer");
8500   }
8501 
8502   // Get the pointer for next argument in overflow area and store it
8503   // to overflow area pointer.
8504   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8505       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8506       "__overflow_area_pointer.next");
8507 
8508   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8509                           __overflow_area_pointer_p);
8510 
8511   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8512                           __current_saved_reg_area_pointer_p);
8513 
8514   // Bitcast the overflow area pointer to the type of argument.
8515   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8516   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8517       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8518 
8519   CGF.EmitBranch(ContBlock);
8520 
8521   // Get the correct pointer to load the variable argument
8522   // Implement the ContBlock
8523   CGF.EmitBlock(ContBlock);
8524 
8525   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8526   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8527   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8528   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8529 
8530   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8531 }
8532 
8533 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8534                                   QualType Ty) const {
8535 
8536   if (getTarget().getTriple().isMusl())
8537     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8538 
8539   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8540 }
8541 
8542 //===----------------------------------------------------------------------===//
8543 // Lanai ABI Implementation
8544 //===----------------------------------------------------------------------===//
8545 
8546 namespace {
8547 class LanaiABIInfo : public DefaultABIInfo {
8548 public:
8549   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8550 
8551   bool shouldUseInReg(QualType Ty, CCState &State) const;
8552 
8553   void computeInfo(CGFunctionInfo &FI) const override {
8554     CCState State(FI);
8555     // Lanai uses 4 registers to pass arguments unless the function has the
8556     // regparm attribute set.
8557     if (FI.getHasRegParm()) {
8558       State.FreeRegs = FI.getRegParm();
8559     } else {
8560       State.FreeRegs = 4;
8561     }
8562 
8563     if (!getCXXABI().classifyReturnType(FI))
8564       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8565     for (auto &I : FI.arguments())
8566       I.info = classifyArgumentType(I.type, State);
8567   }
8568 
8569   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8570   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8571 };
8572 } // end anonymous namespace
8573 
8574 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8575   unsigned Size = getContext().getTypeSize(Ty);
8576   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8577 
8578   if (SizeInRegs == 0)
8579     return false;
8580 
8581   if (SizeInRegs > State.FreeRegs) {
8582     State.FreeRegs = 0;
8583     return false;
8584   }
8585 
8586   State.FreeRegs -= SizeInRegs;
8587 
8588   return true;
8589 }
8590 
8591 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8592                                            CCState &State) const {
8593   if (!ByVal) {
8594     if (State.FreeRegs) {
8595       --State.FreeRegs; // Non-byval indirects just use one pointer.
8596       return getNaturalAlignIndirectInReg(Ty);
8597     }
8598     return getNaturalAlignIndirect(Ty, false);
8599   }
8600 
8601   // Compute the byval alignment.
8602   const unsigned MinABIStackAlignInBytes = 4;
8603   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8604   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8605                                  /*Realign=*/TypeAlign >
8606                                      MinABIStackAlignInBytes);
8607 }
8608 
8609 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8610                                               CCState &State) const {
8611   // Check with the C++ ABI first.
8612   const RecordType *RT = Ty->getAs<RecordType>();
8613   if (RT) {
8614     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8615     if (RAA == CGCXXABI::RAA_Indirect) {
8616       return getIndirectResult(Ty, /*ByVal=*/false, State);
8617     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8618       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8619     }
8620   }
8621 
8622   if (isAggregateTypeForABI(Ty)) {
8623     // Structures with flexible arrays are always indirect.
8624     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8625       return getIndirectResult(Ty, /*ByVal=*/true, State);
8626 
8627     // Ignore empty structs/unions.
8628     if (isEmptyRecord(getContext(), Ty, true))
8629       return ABIArgInfo::getIgnore();
8630 
8631     llvm::LLVMContext &LLVMContext = getVMContext();
8632     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8633     if (SizeInRegs <= State.FreeRegs) {
8634       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8635       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8636       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8637       State.FreeRegs -= SizeInRegs;
8638       return ABIArgInfo::getDirectInReg(Result);
8639     } else {
8640       State.FreeRegs = 0;
8641     }
8642     return getIndirectResult(Ty, true, State);
8643   }
8644 
8645   // Treat an enum type as its underlying type.
8646   if (const auto *EnumTy = Ty->getAs<EnumType>())
8647     Ty = EnumTy->getDecl()->getIntegerType();
8648 
8649   bool InReg = shouldUseInReg(Ty, State);
8650 
8651   // Don't pass >64 bit integers in registers.
8652   if (const auto *EIT = Ty->getAs<ExtIntType>())
8653     if (EIT->getNumBits() > 64)
8654       return getIndirectResult(Ty, /*ByVal=*/true, State);
8655 
8656   if (isPromotableIntegerTypeForABI(Ty)) {
8657     if (InReg)
8658       return ABIArgInfo::getDirectInReg();
8659     return ABIArgInfo::getExtend(Ty);
8660   }
8661   if (InReg)
8662     return ABIArgInfo::getDirectInReg();
8663   return ABIArgInfo::getDirect();
8664 }
8665 
8666 namespace {
8667 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8668 public:
8669   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8670       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8671 };
8672 }
8673 
8674 //===----------------------------------------------------------------------===//
8675 // AMDGPU ABI Implementation
8676 //===----------------------------------------------------------------------===//
8677 
8678 namespace {
8679 
8680 class AMDGPUABIInfo final : public DefaultABIInfo {
8681 private:
8682   static const unsigned MaxNumRegsForArgsRet = 16;
8683 
8684   unsigned numRegsForType(QualType Ty) const;
8685 
8686   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8687   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8688                                          uint64_t Members) const override;
8689 
8690   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8691   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8692                                        unsigned ToAS) const {
8693     // Single value types.
8694     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8695       return llvm::PointerType::get(
8696           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8697     return Ty;
8698   }
8699 
8700 public:
8701   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8702     DefaultABIInfo(CGT) {}
8703 
8704   ABIArgInfo classifyReturnType(QualType RetTy) const;
8705   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8706   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8707 
8708   void computeInfo(CGFunctionInfo &FI) const override;
8709   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8710                     QualType Ty) const override;
8711 };
8712 
8713 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8714   return true;
8715 }
8716 
8717 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8718   const Type *Base, uint64_t Members) const {
8719   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8720 
8721   // Homogeneous Aggregates may occupy at most 16 registers.
8722   return Members * NumRegs <= MaxNumRegsForArgsRet;
8723 }
8724 
8725 /// Estimate number of registers the type will use when passed in registers.
8726 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8727   unsigned NumRegs = 0;
8728 
8729   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8730     // Compute from the number of elements. The reported size is based on the
8731     // in-memory size, which includes the padding 4th element for 3-vectors.
8732     QualType EltTy = VT->getElementType();
8733     unsigned EltSize = getContext().getTypeSize(EltTy);
8734 
8735     // 16-bit element vectors should be passed as packed.
8736     if (EltSize == 16)
8737       return (VT->getNumElements() + 1) / 2;
8738 
8739     unsigned EltNumRegs = (EltSize + 31) / 32;
8740     return EltNumRegs * VT->getNumElements();
8741   }
8742 
8743   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8744     const RecordDecl *RD = RT->getDecl();
8745     assert(!RD->hasFlexibleArrayMember());
8746 
8747     for (const FieldDecl *Field : RD->fields()) {
8748       QualType FieldTy = Field->getType();
8749       NumRegs += numRegsForType(FieldTy);
8750     }
8751 
8752     return NumRegs;
8753   }
8754 
8755   return (getContext().getTypeSize(Ty) + 31) / 32;
8756 }
8757 
8758 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8759   llvm::CallingConv::ID CC = FI.getCallingConvention();
8760 
8761   if (!getCXXABI().classifyReturnType(FI))
8762     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8763 
8764   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8765   for (auto &Arg : FI.arguments()) {
8766     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8767       Arg.info = classifyKernelArgumentType(Arg.type);
8768     } else {
8769       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8770     }
8771   }
8772 }
8773 
8774 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8775                                  QualType Ty) const {
8776   llvm_unreachable("AMDGPU does not support varargs");
8777 }
8778 
8779 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8780   if (isAggregateTypeForABI(RetTy)) {
8781     // Records with non-trivial destructors/copy-constructors should not be
8782     // returned by value.
8783     if (!getRecordArgABI(RetTy, getCXXABI())) {
8784       // Ignore empty structs/unions.
8785       if (isEmptyRecord(getContext(), RetTy, true))
8786         return ABIArgInfo::getIgnore();
8787 
8788       // Lower single-element structs to just return a regular value.
8789       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8790         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8791 
8792       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8793         const RecordDecl *RD = RT->getDecl();
8794         if (RD->hasFlexibleArrayMember())
8795           return DefaultABIInfo::classifyReturnType(RetTy);
8796       }
8797 
8798       // Pack aggregates <= 4 bytes into single VGPR or pair.
8799       uint64_t Size = getContext().getTypeSize(RetTy);
8800       if (Size <= 16)
8801         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8802 
8803       if (Size <= 32)
8804         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8805 
8806       if (Size <= 64) {
8807         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8808         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8809       }
8810 
8811       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8812         return ABIArgInfo::getDirect();
8813     }
8814   }
8815 
8816   // Otherwise just do the default thing.
8817   return DefaultABIInfo::classifyReturnType(RetTy);
8818 }
8819 
8820 /// For kernels all parameters are really passed in a special buffer. It doesn't
8821 /// make sense to pass anything byval, so everything must be direct.
8822 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8823   Ty = useFirstFieldIfTransparentUnion(Ty);
8824 
8825   // TODO: Can we omit empty structs?
8826 
8827   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8828     Ty = QualType(SeltTy, 0);
8829 
8830   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8831   llvm::Type *LTy = OrigLTy;
8832   if (getContext().getLangOpts().HIP) {
8833     LTy = coerceKernelArgumentType(
8834         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8835         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8836   }
8837 
8838   // FIXME: Should also use this for OpenCL, but it requires addressing the
8839   // problem of kernels being called.
8840   //
8841   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8842   // to global address space when using byref. This would require implementing a
8843   // new kind of coercion of the in-memory type when for indirect arguments.
8844   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8845       isAggregateTypeForABI(Ty)) {
8846     return ABIArgInfo::getIndirectAliased(
8847         getContext().getTypeAlignInChars(Ty),
8848         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8849         false /*Realign*/, nullptr /*Padding*/);
8850   }
8851 
8852   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8853   // individual elements, which confuses the Clover OpenCL backend; therefore we
8854   // have to set it to false here. Other args of getDirect() are just defaults.
8855   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8856 }
8857 
8858 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8859                                                unsigned &NumRegsLeft) const {
8860   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8861 
8862   Ty = useFirstFieldIfTransparentUnion(Ty);
8863 
8864   if (isAggregateTypeForABI(Ty)) {
8865     // Records with non-trivial destructors/copy-constructors should not be
8866     // passed by value.
8867     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8868       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8869 
8870     // Ignore empty structs/unions.
8871     if (isEmptyRecord(getContext(), Ty, true))
8872       return ABIArgInfo::getIgnore();
8873 
8874     // Lower single-element structs to just pass a regular value. TODO: We
8875     // could do reasonable-size multiple-element structs too, using getExpand(),
8876     // though watch out for things like bitfields.
8877     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8878       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8879 
8880     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8881       const RecordDecl *RD = RT->getDecl();
8882       if (RD->hasFlexibleArrayMember())
8883         return DefaultABIInfo::classifyArgumentType(Ty);
8884     }
8885 
8886     // Pack aggregates <= 8 bytes into single VGPR or pair.
8887     uint64_t Size = getContext().getTypeSize(Ty);
8888     if (Size <= 64) {
8889       unsigned NumRegs = (Size + 31) / 32;
8890       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8891 
8892       if (Size <= 16)
8893         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8894 
8895       if (Size <= 32)
8896         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8897 
8898       // XXX: Should this be i64 instead, and should the limit increase?
8899       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8900       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8901     }
8902 
8903     if (NumRegsLeft > 0) {
8904       unsigned NumRegs = numRegsForType(Ty);
8905       if (NumRegsLeft >= NumRegs) {
8906         NumRegsLeft -= NumRegs;
8907         return ABIArgInfo::getDirect();
8908       }
8909     }
8910   }
8911 
8912   // Otherwise just do the default thing.
8913   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8914   if (!ArgInfo.isIndirect()) {
8915     unsigned NumRegs = numRegsForType(Ty);
8916     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8917   }
8918 
8919   return ArgInfo;
8920 }
8921 
8922 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8923 public:
8924   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8925       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8926   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8927                            CodeGen::CodeGenModule &M) const override;
8928   unsigned getOpenCLKernelCallingConv() const override;
8929 
8930   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8931       llvm::PointerType *T, QualType QT) const override;
8932 
8933   LangAS getASTAllocaAddressSpace() const override {
8934     return getLangASFromTargetAS(
8935         getABIInfo().getDataLayout().getAllocaAddrSpace());
8936   }
8937   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8938                                   const VarDecl *D) const override;
8939   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8940                                          SyncScope Scope,
8941                                          llvm::AtomicOrdering Ordering,
8942                                          llvm::LLVMContext &Ctx) const override;
8943   llvm::Function *
8944   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8945                             llvm::Function *BlockInvokeFunc,
8946                             llvm::Value *BlockLiteral) const override;
8947   bool shouldEmitStaticExternCAliases() const override;
8948   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8949 };
8950 }
8951 
8952 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8953                                               llvm::GlobalValue *GV) {
8954   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8955     return false;
8956 
8957   return D->hasAttr<OpenCLKernelAttr>() ||
8958          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8959          (isa<VarDecl>(D) &&
8960           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8961            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8962            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8963 }
8964 
8965 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8966     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8967   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8968     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8969     GV->setDSOLocal(true);
8970   }
8971 
8972   if (GV->isDeclaration())
8973     return;
8974   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8975   if (!FD)
8976     return;
8977 
8978   llvm::Function *F = cast<llvm::Function>(GV);
8979 
8980   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8981     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8982 
8983 
8984   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8985                               FD->hasAttr<OpenCLKernelAttr>();
8986   const bool IsHIPKernel = M.getLangOpts().HIP &&
8987                            FD->hasAttr<CUDAGlobalAttr>();
8988   if ((IsOpenCLKernel || IsHIPKernel) &&
8989       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8990     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8991 
8992   if (IsHIPKernel)
8993     F->addFnAttr("uniform-work-group-size", "true");
8994 
8995 
8996   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8997   if (ReqdWGS || FlatWGS) {
8998     unsigned Min = 0;
8999     unsigned Max = 0;
9000     if (FlatWGS) {
9001       Min = FlatWGS->getMin()
9002                 ->EvaluateKnownConstInt(M.getContext())
9003                 .getExtValue();
9004       Max = FlatWGS->getMax()
9005                 ->EvaluateKnownConstInt(M.getContext())
9006                 .getExtValue();
9007     }
9008     if (ReqdWGS && Min == 0 && Max == 0)
9009       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9010 
9011     if (Min != 0) {
9012       assert(Min <= Max && "Min must be less than or equal Max");
9013 
9014       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9015       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9016     } else
9017       assert(Max == 0 && "Max must be zero");
9018   } else if (IsOpenCLKernel || IsHIPKernel) {
9019     // By default, restrict the maximum size to a value specified by
9020     // --gpu-max-threads-per-block=n or its default value.
9021     std::string AttrVal =
9022         std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
9023     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9024   }
9025 
9026   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9027     unsigned Min =
9028         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9029     unsigned Max = Attr->getMax() ? Attr->getMax()
9030                                         ->EvaluateKnownConstInt(M.getContext())
9031                                         .getExtValue()
9032                                   : 0;
9033 
9034     if (Min != 0) {
9035       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9036 
9037       std::string AttrVal = llvm::utostr(Min);
9038       if (Max != 0)
9039         AttrVal = AttrVal + "," + llvm::utostr(Max);
9040       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9041     } else
9042       assert(Max == 0 && "Max must be zero");
9043   }
9044 
9045   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9046     unsigned NumSGPR = Attr->getNumSGPR();
9047 
9048     if (NumSGPR != 0)
9049       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9050   }
9051 
9052   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9053     uint32_t NumVGPR = Attr->getNumVGPR();
9054 
9055     if (NumVGPR != 0)
9056       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9057   }
9058 
9059   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9060     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9061 }
9062 
9063 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9064   return llvm::CallingConv::AMDGPU_KERNEL;
9065 }
9066 
9067 // Currently LLVM assumes null pointers always have value 0,
9068 // which results in incorrectly transformed IR. Therefore, instead of
9069 // emitting null pointers in private and local address spaces, a null
9070 // pointer in generic address space is emitted which is casted to a
9071 // pointer in local or private address space.
9072 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9073     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9074     QualType QT) const {
9075   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9076     return llvm::ConstantPointerNull::get(PT);
9077 
9078   auto &Ctx = CGM.getContext();
9079   auto NPT = llvm::PointerType::get(PT->getElementType(),
9080       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9081   return llvm::ConstantExpr::getAddrSpaceCast(
9082       llvm::ConstantPointerNull::get(NPT), PT);
9083 }
9084 
9085 LangAS
9086 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9087                                                   const VarDecl *D) const {
9088   assert(!CGM.getLangOpts().OpenCL &&
9089          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9090          "Address space agnostic languages only");
9091   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9092       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9093   if (!D)
9094     return DefaultGlobalAS;
9095 
9096   LangAS AddrSpace = D->getType().getAddressSpace();
9097   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9098   if (AddrSpace != LangAS::Default)
9099     return AddrSpace;
9100 
9101   if (CGM.isTypeConstant(D->getType(), false)) {
9102     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9103       return ConstAS.getValue();
9104   }
9105   return DefaultGlobalAS;
9106 }
9107 
9108 llvm::SyncScope::ID
9109 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9110                                             SyncScope Scope,
9111                                             llvm::AtomicOrdering Ordering,
9112                                             llvm::LLVMContext &Ctx) const {
9113   std::string Name;
9114   switch (Scope) {
9115   case SyncScope::OpenCLWorkGroup:
9116     Name = "workgroup";
9117     break;
9118   case SyncScope::OpenCLDevice:
9119     Name = "agent";
9120     break;
9121   case SyncScope::OpenCLAllSVMDevices:
9122     Name = "";
9123     break;
9124   case SyncScope::OpenCLSubGroup:
9125     Name = "wavefront";
9126   }
9127 
9128   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9129     if (!Name.empty())
9130       Name = Twine(Twine(Name) + Twine("-")).str();
9131 
9132     Name = Twine(Twine(Name) + Twine("one-as")).str();
9133   }
9134 
9135   return Ctx.getOrInsertSyncScopeID(Name);
9136 }
9137 
9138 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9139   return false;
9140 }
9141 
9142 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9143     const FunctionType *&FT) const {
9144   FT = getABIInfo().getContext().adjustFunctionType(
9145       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9146 }
9147 
9148 //===----------------------------------------------------------------------===//
9149 // SPARC v8 ABI Implementation.
9150 // Based on the SPARC Compliance Definition version 2.4.1.
9151 //
9152 // Ensures that complex values are passed in registers.
9153 //
9154 namespace {
9155 class SparcV8ABIInfo : public DefaultABIInfo {
9156 public:
9157   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9158 
9159 private:
9160   ABIArgInfo classifyReturnType(QualType RetTy) const;
9161   void computeInfo(CGFunctionInfo &FI) const override;
9162 };
9163 } // end anonymous namespace
9164 
9165 
9166 ABIArgInfo
9167 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9168   if (Ty->isAnyComplexType()) {
9169     return ABIArgInfo::getDirect();
9170   }
9171   else {
9172     return DefaultABIInfo::classifyReturnType(Ty);
9173   }
9174 }
9175 
9176 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9177 
9178   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9179   for (auto &Arg : FI.arguments())
9180     Arg.info = classifyArgumentType(Arg.type);
9181 }
9182 
9183 namespace {
9184 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9185 public:
9186   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9187       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9188 };
9189 } // end anonymous namespace
9190 
9191 //===----------------------------------------------------------------------===//
9192 // SPARC v9 ABI Implementation.
9193 // Based on the SPARC Compliance Definition version 2.4.1.
9194 //
9195 // Function arguments a mapped to a nominal "parameter array" and promoted to
9196 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9197 // the array, structs larger than 16 bytes are passed indirectly.
9198 //
9199 // One case requires special care:
9200 //
9201 //   struct mixed {
9202 //     int i;
9203 //     float f;
9204 //   };
9205 //
9206 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9207 // parameter array, but the int is passed in an integer register, and the float
9208 // is passed in a floating point register. This is represented as two arguments
9209 // with the LLVM IR inreg attribute:
9210 //
9211 //   declare void f(i32 inreg %i, float inreg %f)
9212 //
9213 // The code generator will only allocate 4 bytes from the parameter array for
9214 // the inreg arguments. All other arguments are allocated a multiple of 8
9215 // bytes.
9216 //
9217 namespace {
9218 class SparcV9ABIInfo : public ABIInfo {
9219 public:
9220   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9221 
9222 private:
9223   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9224   void computeInfo(CGFunctionInfo &FI) const override;
9225   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9226                     QualType Ty) const override;
9227 
9228   // Coercion type builder for structs passed in registers. The coercion type
9229   // serves two purposes:
9230   //
9231   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9232   //    in registers.
9233   // 2. Expose aligned floating point elements as first-level elements, so the
9234   //    code generator knows to pass them in floating point registers.
9235   //
9236   // We also compute the InReg flag which indicates that the struct contains
9237   // aligned 32-bit floats.
9238   //
9239   struct CoerceBuilder {
9240     llvm::LLVMContext &Context;
9241     const llvm::DataLayout &DL;
9242     SmallVector<llvm::Type*, 8> Elems;
9243     uint64_t Size;
9244     bool InReg;
9245 
9246     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9247       : Context(c), DL(dl), Size(0), InReg(false) {}
9248 
9249     // Pad Elems with integers until Size is ToSize.
9250     void pad(uint64_t ToSize) {
9251       assert(ToSize >= Size && "Cannot remove elements");
9252       if (ToSize == Size)
9253         return;
9254 
9255       // Finish the current 64-bit word.
9256       uint64_t Aligned = llvm::alignTo(Size, 64);
9257       if (Aligned > Size && Aligned <= ToSize) {
9258         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9259         Size = Aligned;
9260       }
9261 
9262       // Add whole 64-bit words.
9263       while (Size + 64 <= ToSize) {
9264         Elems.push_back(llvm::Type::getInt64Ty(Context));
9265         Size += 64;
9266       }
9267 
9268       // Final in-word padding.
9269       if (Size < ToSize) {
9270         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9271         Size = ToSize;
9272       }
9273     }
9274 
9275     // Add a floating point element at Offset.
9276     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9277       // Unaligned floats are treated as integers.
9278       if (Offset % Bits)
9279         return;
9280       // The InReg flag is only required if there are any floats < 64 bits.
9281       if (Bits < 64)
9282         InReg = true;
9283       pad(Offset);
9284       Elems.push_back(Ty);
9285       Size = Offset + Bits;
9286     }
9287 
9288     // Add a struct type to the coercion type, starting at Offset (in bits).
9289     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9290       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9291       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9292         llvm::Type *ElemTy = StrTy->getElementType(i);
9293         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9294         switch (ElemTy->getTypeID()) {
9295         case llvm::Type::StructTyID:
9296           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9297           break;
9298         case llvm::Type::FloatTyID:
9299           addFloat(ElemOffset, ElemTy, 32);
9300           break;
9301         case llvm::Type::DoubleTyID:
9302           addFloat(ElemOffset, ElemTy, 64);
9303           break;
9304         case llvm::Type::FP128TyID:
9305           addFloat(ElemOffset, ElemTy, 128);
9306           break;
9307         case llvm::Type::PointerTyID:
9308           if (ElemOffset % 64 == 0) {
9309             pad(ElemOffset);
9310             Elems.push_back(ElemTy);
9311             Size += 64;
9312           }
9313           break;
9314         default:
9315           break;
9316         }
9317       }
9318     }
9319 
9320     // Check if Ty is a usable substitute for the coercion type.
9321     bool isUsableType(llvm::StructType *Ty) const {
9322       return llvm::makeArrayRef(Elems) == Ty->elements();
9323     }
9324 
9325     // Get the coercion type as a literal struct type.
9326     llvm::Type *getType() const {
9327       if (Elems.size() == 1)
9328         return Elems.front();
9329       else
9330         return llvm::StructType::get(Context, Elems);
9331     }
9332   };
9333 };
9334 } // end anonymous namespace
9335 
9336 ABIArgInfo
9337 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9338   if (Ty->isVoidType())
9339     return ABIArgInfo::getIgnore();
9340 
9341   uint64_t Size = getContext().getTypeSize(Ty);
9342 
9343   // Anything too big to fit in registers is passed with an explicit indirect
9344   // pointer / sret pointer.
9345   if (Size > SizeLimit)
9346     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9347 
9348   // Treat an enum type as its underlying type.
9349   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9350     Ty = EnumTy->getDecl()->getIntegerType();
9351 
9352   // Integer types smaller than a register are extended.
9353   if (Size < 64 && Ty->isIntegerType())
9354     return ABIArgInfo::getExtend(Ty);
9355 
9356   if (const auto *EIT = Ty->getAs<ExtIntType>())
9357     if (EIT->getNumBits() < 64)
9358       return ABIArgInfo::getExtend(Ty);
9359 
9360   // Other non-aggregates go in registers.
9361   if (!isAggregateTypeForABI(Ty))
9362     return ABIArgInfo::getDirect();
9363 
9364   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9365   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9366   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9367     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9368 
9369   // This is a small aggregate type that should be passed in registers.
9370   // Build a coercion type from the LLVM struct type.
9371   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9372   if (!StrTy)
9373     return ABIArgInfo::getDirect();
9374 
9375   CoerceBuilder CB(getVMContext(), getDataLayout());
9376   CB.addStruct(0, StrTy);
9377   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9378 
9379   // Try to use the original type for coercion.
9380   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9381 
9382   if (CB.InReg)
9383     return ABIArgInfo::getDirectInReg(CoerceTy);
9384   else
9385     return ABIArgInfo::getDirect(CoerceTy);
9386 }
9387 
9388 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9389                                   QualType Ty) const {
9390   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9391   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9392   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9393     AI.setCoerceToType(ArgTy);
9394 
9395   CharUnits SlotSize = CharUnits::fromQuantity(8);
9396 
9397   CGBuilderTy &Builder = CGF.Builder;
9398   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9399   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9400 
9401   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9402 
9403   Address ArgAddr = Address::invalid();
9404   CharUnits Stride;
9405   switch (AI.getKind()) {
9406   case ABIArgInfo::Expand:
9407   case ABIArgInfo::CoerceAndExpand:
9408   case ABIArgInfo::InAlloca:
9409     llvm_unreachable("Unsupported ABI kind for va_arg");
9410 
9411   case ABIArgInfo::Extend: {
9412     Stride = SlotSize;
9413     CharUnits Offset = SlotSize - TypeInfo.Width;
9414     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9415     break;
9416   }
9417 
9418   case ABIArgInfo::Direct: {
9419     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9420     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9421     ArgAddr = Addr;
9422     break;
9423   }
9424 
9425   case ABIArgInfo::Indirect:
9426   case ABIArgInfo::IndirectAliased:
9427     Stride = SlotSize;
9428     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9429     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9430                       TypeInfo.Align);
9431     break;
9432 
9433   case ABIArgInfo::Ignore:
9434     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9435   }
9436 
9437   // Update VAList.
9438   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9439   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9440 
9441   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9442 }
9443 
9444 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9445   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9446   for (auto &I : FI.arguments())
9447     I.info = classifyType(I.type, 16 * 8);
9448 }
9449 
9450 namespace {
9451 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9452 public:
9453   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9454       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9455 
9456   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9457     return 14;
9458   }
9459 
9460   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9461                                llvm::Value *Address) const override;
9462 };
9463 } // end anonymous namespace
9464 
9465 bool
9466 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9467                                                 llvm::Value *Address) const {
9468   // This is calculated from the LLVM and GCC tables and verified
9469   // against gcc output.  AFAIK all ABIs use the same encoding.
9470 
9471   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9472 
9473   llvm::IntegerType *i8 = CGF.Int8Ty;
9474   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9475   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9476 
9477   // 0-31: the 8-byte general-purpose registers
9478   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9479 
9480   // 32-63: f0-31, the 4-byte floating-point registers
9481   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9482 
9483   //   Y   = 64
9484   //   PSR = 65
9485   //   WIM = 66
9486   //   TBR = 67
9487   //   PC  = 68
9488   //   NPC = 69
9489   //   FSR = 70
9490   //   CSR = 71
9491   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9492 
9493   // 72-87: d0-15, the 8-byte floating-point registers
9494   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9495 
9496   return false;
9497 }
9498 
9499 // ARC ABI implementation.
9500 namespace {
9501 
9502 class ARCABIInfo : public DefaultABIInfo {
9503 public:
9504   using DefaultABIInfo::DefaultABIInfo;
9505 
9506 private:
9507   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9508                     QualType Ty) const override;
9509 
9510   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9511     if (!State.FreeRegs)
9512       return;
9513     if (Info.isIndirect() && Info.getInReg())
9514       State.FreeRegs--;
9515     else if (Info.isDirect() && Info.getInReg()) {
9516       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9517       if (sz < State.FreeRegs)
9518         State.FreeRegs -= sz;
9519       else
9520         State.FreeRegs = 0;
9521     }
9522   }
9523 
9524   void computeInfo(CGFunctionInfo &FI) const override {
9525     CCState State(FI);
9526     // ARC uses 8 registers to pass arguments.
9527     State.FreeRegs = 8;
9528 
9529     if (!getCXXABI().classifyReturnType(FI))
9530       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9531     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9532     for (auto &I : FI.arguments()) {
9533       I.info = classifyArgumentType(I.type, State.FreeRegs);
9534       updateState(I.info, I.type, State);
9535     }
9536   }
9537 
9538   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9539   ABIArgInfo getIndirectByValue(QualType Ty) const;
9540   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9541   ABIArgInfo classifyReturnType(QualType RetTy) const;
9542 };
9543 
9544 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9545 public:
9546   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9547       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9548 };
9549 
9550 
9551 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9552   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9553                        getNaturalAlignIndirect(Ty, false);
9554 }
9555 
9556 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9557   // Compute the byval alignment.
9558   const unsigned MinABIStackAlignInBytes = 4;
9559   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9560   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9561                                  TypeAlign > MinABIStackAlignInBytes);
9562 }
9563 
9564 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9565                               QualType Ty) const {
9566   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9567                           getContext().getTypeInfoInChars(Ty),
9568                           CharUnits::fromQuantity(4), true);
9569 }
9570 
9571 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9572                                             uint8_t FreeRegs) const {
9573   // Handle the generic C++ ABI.
9574   const RecordType *RT = Ty->getAs<RecordType>();
9575   if (RT) {
9576     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9577     if (RAA == CGCXXABI::RAA_Indirect)
9578       return getIndirectByRef(Ty, FreeRegs > 0);
9579 
9580     if (RAA == CGCXXABI::RAA_DirectInMemory)
9581       return getIndirectByValue(Ty);
9582   }
9583 
9584   // Treat an enum type as its underlying type.
9585   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9586     Ty = EnumTy->getDecl()->getIntegerType();
9587 
9588   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9589 
9590   if (isAggregateTypeForABI(Ty)) {
9591     // Structures with flexible arrays are always indirect.
9592     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9593       return getIndirectByValue(Ty);
9594 
9595     // Ignore empty structs/unions.
9596     if (isEmptyRecord(getContext(), Ty, true))
9597       return ABIArgInfo::getIgnore();
9598 
9599     llvm::LLVMContext &LLVMContext = getVMContext();
9600 
9601     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9602     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9603     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9604 
9605     return FreeRegs >= SizeInRegs ?
9606         ABIArgInfo::getDirectInReg(Result) :
9607         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9608   }
9609 
9610   if (const auto *EIT = Ty->getAs<ExtIntType>())
9611     if (EIT->getNumBits() > 64)
9612       return getIndirectByValue(Ty);
9613 
9614   return isPromotableIntegerTypeForABI(Ty)
9615              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9616                                        : ABIArgInfo::getExtend(Ty))
9617              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9618                                        : ABIArgInfo::getDirect());
9619 }
9620 
9621 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9622   if (RetTy->isAnyComplexType())
9623     return ABIArgInfo::getDirectInReg();
9624 
9625   // Arguments of size > 4 registers are indirect.
9626   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9627   if (RetSize > 4)
9628     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9629 
9630   return DefaultABIInfo::classifyReturnType(RetTy);
9631 }
9632 
9633 } // End anonymous namespace.
9634 
9635 //===----------------------------------------------------------------------===//
9636 // XCore ABI Implementation
9637 //===----------------------------------------------------------------------===//
9638 
9639 namespace {
9640 
9641 /// A SmallStringEnc instance is used to build up the TypeString by passing
9642 /// it by reference between functions that append to it.
9643 typedef llvm::SmallString<128> SmallStringEnc;
9644 
9645 /// TypeStringCache caches the meta encodings of Types.
9646 ///
9647 /// The reason for caching TypeStrings is two fold:
9648 ///   1. To cache a type's encoding for later uses;
9649 ///   2. As a means to break recursive member type inclusion.
9650 ///
9651 /// A cache Entry can have a Status of:
9652 ///   NonRecursive:   The type encoding is not recursive;
9653 ///   Recursive:      The type encoding is recursive;
9654 ///   Incomplete:     An incomplete TypeString;
9655 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9656 ///                   Recursive type encoding.
9657 ///
9658 /// A NonRecursive entry will have all of its sub-members expanded as fully
9659 /// as possible. Whilst it may contain types which are recursive, the type
9660 /// itself is not recursive and thus its encoding may be safely used whenever
9661 /// the type is encountered.
9662 ///
9663 /// A Recursive entry will have all of its sub-members expanded as fully as
9664 /// possible. The type itself is recursive and it may contain other types which
9665 /// are recursive. The Recursive encoding must not be used during the expansion
9666 /// of a recursive type's recursive branch. For simplicity the code uses
9667 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9668 ///
9669 /// An Incomplete entry is always a RecordType and only encodes its
9670 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9671 /// are placed into the cache during type expansion as a means to identify and
9672 /// handle recursive inclusion of types as sub-members. If there is recursion
9673 /// the entry becomes IncompleteUsed.
9674 ///
9675 /// During the expansion of a RecordType's members:
9676 ///
9677 ///   If the cache contains a NonRecursive encoding for the member type, the
9678 ///   cached encoding is used;
9679 ///
9680 ///   If the cache contains a Recursive encoding for the member type, the
9681 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9682 ///
9683 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9684 ///   cache to break potential recursive inclusion of itself as a sub-member;
9685 ///
9686 ///   Once a member RecordType has been expanded, its temporary incomplete
9687 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9688 ///   it is swapped back in;
9689 ///
9690 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9691 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9692 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9693 ///
9694 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9695 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9696 ///   Else the member is part of a recursive type and thus the recursion has
9697 ///   been exited too soon for the encoding to be correct for the member.
9698 ///
9699 class TypeStringCache {
9700   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9701   struct Entry {
9702     std::string Str;     // The encoded TypeString for the type.
9703     enum Status State;   // Information about the encoding in 'Str'.
9704     std::string Swapped; // A temporary place holder for a Recursive encoding
9705                          // during the expansion of RecordType's members.
9706   };
9707   std::map<const IdentifierInfo *, struct Entry> Map;
9708   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9709   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9710 public:
9711   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9712   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9713   bool removeIncomplete(const IdentifierInfo *ID);
9714   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9715                      bool IsRecursive);
9716   StringRef lookupStr(const IdentifierInfo *ID);
9717 };
9718 
9719 /// TypeString encodings for enum & union fields must be order.
9720 /// FieldEncoding is a helper for this ordering process.
9721 class FieldEncoding {
9722   bool HasName;
9723   std::string Enc;
9724 public:
9725   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9726   StringRef str() { return Enc; }
9727   bool operator<(const FieldEncoding &rhs) const {
9728     if (HasName != rhs.HasName) return HasName;
9729     return Enc < rhs.Enc;
9730   }
9731 };
9732 
9733 class XCoreABIInfo : public DefaultABIInfo {
9734 public:
9735   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9736   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9737                     QualType Ty) const override;
9738 };
9739 
9740 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9741   mutable TypeStringCache TSC;
9742   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9743                     const CodeGen::CodeGenModule &M) const;
9744 
9745 public:
9746   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9747       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9748   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9749                           const llvm::MapVector<GlobalDecl, StringRef>
9750                               &MangledDeclNames) const override;
9751 };
9752 
9753 } // End anonymous namespace.
9754 
9755 // TODO: this implementation is likely now redundant with the default
9756 // EmitVAArg.
9757 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9758                                 QualType Ty) const {
9759   CGBuilderTy &Builder = CGF.Builder;
9760 
9761   // Get the VAList.
9762   CharUnits SlotSize = CharUnits::fromQuantity(4);
9763   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9764 
9765   // Handle the argument.
9766   ABIArgInfo AI = classifyArgumentType(Ty);
9767   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9768   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9769   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9770     AI.setCoerceToType(ArgTy);
9771   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9772 
9773   Address Val = Address::invalid();
9774   CharUnits ArgSize = CharUnits::Zero();
9775   switch (AI.getKind()) {
9776   case ABIArgInfo::Expand:
9777   case ABIArgInfo::CoerceAndExpand:
9778   case ABIArgInfo::InAlloca:
9779     llvm_unreachable("Unsupported ABI kind for va_arg");
9780   case ABIArgInfo::Ignore:
9781     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9782     ArgSize = CharUnits::Zero();
9783     break;
9784   case ABIArgInfo::Extend:
9785   case ABIArgInfo::Direct:
9786     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9787     ArgSize = CharUnits::fromQuantity(
9788                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9789     ArgSize = ArgSize.alignTo(SlotSize);
9790     break;
9791   case ABIArgInfo::Indirect:
9792   case ABIArgInfo::IndirectAliased:
9793     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9794     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9795     ArgSize = SlotSize;
9796     break;
9797   }
9798 
9799   // Increment the VAList.
9800   if (!ArgSize.isZero()) {
9801     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9802     Builder.CreateStore(APN.getPointer(), VAListAddr);
9803   }
9804 
9805   return Val;
9806 }
9807 
9808 /// During the expansion of a RecordType, an incomplete TypeString is placed
9809 /// into the cache as a means to identify and break recursion.
9810 /// If there is a Recursive encoding in the cache, it is swapped out and will
9811 /// be reinserted by removeIncomplete().
9812 /// All other types of encoding should have been used rather than arriving here.
9813 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9814                                     std::string StubEnc) {
9815   if (!ID)
9816     return;
9817   Entry &E = Map[ID];
9818   assert( (E.Str.empty() || E.State == Recursive) &&
9819          "Incorrectly use of addIncomplete");
9820   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9821   E.Swapped.swap(E.Str); // swap out the Recursive
9822   E.Str.swap(StubEnc);
9823   E.State = Incomplete;
9824   ++IncompleteCount;
9825 }
9826 
9827 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9828 /// must be removed from the cache.
9829 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9830 /// Returns true if the RecordType was defined recursively.
9831 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9832   if (!ID)
9833     return false;
9834   auto I = Map.find(ID);
9835   assert(I != Map.end() && "Entry not present");
9836   Entry &E = I->second;
9837   assert( (E.State == Incomplete ||
9838            E.State == IncompleteUsed) &&
9839          "Entry must be an incomplete type");
9840   bool IsRecursive = false;
9841   if (E.State == IncompleteUsed) {
9842     // We made use of our Incomplete encoding, thus we are recursive.
9843     IsRecursive = true;
9844     --IncompleteUsedCount;
9845   }
9846   if (E.Swapped.empty())
9847     Map.erase(I);
9848   else {
9849     // Swap the Recursive back.
9850     E.Swapped.swap(E.Str);
9851     E.Swapped.clear();
9852     E.State = Recursive;
9853   }
9854   --IncompleteCount;
9855   return IsRecursive;
9856 }
9857 
9858 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9859 /// Recursive (viz: all sub-members were expanded as fully as possible).
9860 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9861                                     bool IsRecursive) {
9862   if (!ID || IncompleteUsedCount)
9863     return; // No key or it is is an incomplete sub-type so don't add.
9864   Entry &E = Map[ID];
9865   if (IsRecursive && !E.Str.empty()) {
9866     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9867            "This is not the same Recursive entry");
9868     // The parent container was not recursive after all, so we could have used
9869     // this Recursive sub-member entry after all, but we assumed the worse when
9870     // we started viz: IncompleteCount!=0.
9871     return;
9872   }
9873   assert(E.Str.empty() && "Entry already present");
9874   E.Str = Str.str();
9875   E.State = IsRecursive? Recursive : NonRecursive;
9876 }
9877 
9878 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9879 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9880 /// encoding is Recursive, return an empty StringRef.
9881 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9882   if (!ID)
9883     return StringRef();   // We have no key.
9884   auto I = Map.find(ID);
9885   if (I == Map.end())
9886     return StringRef();   // We have no encoding.
9887   Entry &E = I->second;
9888   if (E.State == Recursive && IncompleteCount)
9889     return StringRef();   // We don't use Recursive encodings for member types.
9890 
9891   if (E.State == Incomplete) {
9892     // The incomplete type is being used to break out of recursion.
9893     E.State = IncompleteUsed;
9894     ++IncompleteUsedCount;
9895   }
9896   return E.Str;
9897 }
9898 
9899 /// The XCore ABI includes a type information section that communicates symbol
9900 /// type information to the linker. The linker uses this information to verify
9901 /// safety/correctness of things such as array bound and pointers et al.
9902 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9903 /// This type information (TypeString) is emitted into meta data for all global
9904 /// symbols: definitions, declarations, functions & variables.
9905 ///
9906 /// The TypeString carries type, qualifier, name, size & value details.
9907 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9908 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9909 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9910 ///
9911 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9912                           const CodeGen::CodeGenModule &CGM,
9913                           TypeStringCache &TSC);
9914 
9915 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9916 void XCoreTargetCodeGenInfo::emitTargetMD(
9917     const Decl *D, llvm::GlobalValue *GV,
9918     const CodeGen::CodeGenModule &CGM) const {
9919   SmallStringEnc Enc;
9920   if (getTypeString(Enc, D, CGM, TSC)) {
9921     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9922     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9923                                 llvm::MDString::get(Ctx, Enc.str())};
9924     llvm::NamedMDNode *MD =
9925       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9926     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9927   }
9928 }
9929 
9930 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9931     CodeGen::CodeGenModule &CGM,
9932     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9933   // Warning, new MangledDeclNames may be appended within this loop.
9934   // We rely on MapVector insertions adding new elements to the end
9935   // of the container.
9936   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9937     auto Val = *(MangledDeclNames.begin() + I);
9938     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9939     if (GV) {
9940       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9941       emitTargetMD(D, GV, CGM);
9942     }
9943   }
9944 }
9945 //===----------------------------------------------------------------------===//
9946 // SPIR ABI Implementation
9947 //===----------------------------------------------------------------------===//
9948 
9949 namespace {
9950 class SPIRABIInfo : public DefaultABIInfo {
9951 public:
9952   SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
9953 
9954 private:
9955   void setCCs();
9956 };
9957 } // end anonymous namespace
9958 namespace {
9959 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9960 public:
9961   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9962       : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
9963   unsigned getOpenCLKernelCallingConv() const override;
9964 };
9965 
9966 } // End anonymous namespace.
9967 void SPIRABIInfo::setCCs() {
9968   assert(getRuntimeCC() == llvm::CallingConv::C);
9969   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
9970 }
9971 
9972 namespace clang {
9973 namespace CodeGen {
9974 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9975   DefaultABIInfo SPIRABI(CGM.getTypes());
9976   SPIRABI.computeInfo(FI);
9977 }
9978 }
9979 }
9980 
9981 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9982   return llvm::CallingConv::SPIR_KERNEL;
9983 }
9984 
9985 static bool appendType(SmallStringEnc &Enc, QualType QType,
9986                        const CodeGen::CodeGenModule &CGM,
9987                        TypeStringCache &TSC);
9988 
9989 /// Helper function for appendRecordType().
9990 /// Builds a SmallVector containing the encoded field types in declaration
9991 /// order.
9992 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9993                              const RecordDecl *RD,
9994                              const CodeGen::CodeGenModule &CGM,
9995                              TypeStringCache &TSC) {
9996   for (const auto *Field : RD->fields()) {
9997     SmallStringEnc Enc;
9998     Enc += "m(";
9999     Enc += Field->getName();
10000     Enc += "){";
10001     if (Field->isBitField()) {
10002       Enc += "b(";
10003       llvm::raw_svector_ostream OS(Enc);
10004       OS << Field->getBitWidthValue(CGM.getContext());
10005       Enc += ':';
10006     }
10007     if (!appendType(Enc, Field->getType(), CGM, TSC))
10008       return false;
10009     if (Field->isBitField())
10010       Enc += ')';
10011     Enc += '}';
10012     FE.emplace_back(!Field->getName().empty(), Enc);
10013   }
10014   return true;
10015 }
10016 
10017 /// Appends structure and union types to Enc and adds encoding to cache.
10018 /// Recursively calls appendType (via extractFieldType) for each field.
10019 /// Union types have their fields ordered according to the ABI.
10020 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10021                              const CodeGen::CodeGenModule &CGM,
10022                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10023   // Append the cached TypeString if we have one.
10024   StringRef TypeString = TSC.lookupStr(ID);
10025   if (!TypeString.empty()) {
10026     Enc += TypeString;
10027     return true;
10028   }
10029 
10030   // Start to emit an incomplete TypeString.
10031   size_t Start = Enc.size();
10032   Enc += (RT->isUnionType()? 'u' : 's');
10033   Enc += '(';
10034   if (ID)
10035     Enc += ID->getName();
10036   Enc += "){";
10037 
10038   // We collect all encoded fields and order as necessary.
10039   bool IsRecursive = false;
10040   const RecordDecl *RD = RT->getDecl()->getDefinition();
10041   if (RD && !RD->field_empty()) {
10042     // An incomplete TypeString stub is placed in the cache for this RecordType
10043     // so that recursive calls to this RecordType will use it whilst building a
10044     // complete TypeString for this RecordType.
10045     SmallVector<FieldEncoding, 16> FE;
10046     std::string StubEnc(Enc.substr(Start).str());
10047     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10048     TSC.addIncomplete(ID, std::move(StubEnc));
10049     if (!extractFieldType(FE, RD, CGM, TSC)) {
10050       (void) TSC.removeIncomplete(ID);
10051       return false;
10052     }
10053     IsRecursive = TSC.removeIncomplete(ID);
10054     // The ABI requires unions to be sorted but not structures.
10055     // See FieldEncoding::operator< for sort algorithm.
10056     if (RT->isUnionType())
10057       llvm::sort(FE);
10058     // We can now complete the TypeString.
10059     unsigned E = FE.size();
10060     for (unsigned I = 0; I != E; ++I) {
10061       if (I)
10062         Enc += ',';
10063       Enc += FE[I].str();
10064     }
10065   }
10066   Enc += '}';
10067   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10068   return true;
10069 }
10070 
10071 /// Appends enum types to Enc and adds the encoding to the cache.
10072 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10073                            TypeStringCache &TSC,
10074                            const IdentifierInfo *ID) {
10075   // Append the cached TypeString if we have one.
10076   StringRef TypeString = TSC.lookupStr(ID);
10077   if (!TypeString.empty()) {
10078     Enc += TypeString;
10079     return true;
10080   }
10081 
10082   size_t Start = Enc.size();
10083   Enc += "e(";
10084   if (ID)
10085     Enc += ID->getName();
10086   Enc += "){";
10087 
10088   // We collect all encoded enumerations and order them alphanumerically.
10089   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10090     SmallVector<FieldEncoding, 16> FE;
10091     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10092          ++I) {
10093       SmallStringEnc EnumEnc;
10094       EnumEnc += "m(";
10095       EnumEnc += I->getName();
10096       EnumEnc += "){";
10097       I->getInitVal().toString(EnumEnc);
10098       EnumEnc += '}';
10099       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10100     }
10101     llvm::sort(FE);
10102     unsigned E = FE.size();
10103     for (unsigned I = 0; I != E; ++I) {
10104       if (I)
10105         Enc += ',';
10106       Enc += FE[I].str();
10107     }
10108   }
10109   Enc += '}';
10110   TSC.addIfComplete(ID, Enc.substr(Start), false);
10111   return true;
10112 }
10113 
10114 /// Appends type's qualifier to Enc.
10115 /// This is done prior to appending the type's encoding.
10116 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10117   // Qualifiers are emitted in alphabetical order.
10118   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10119   int Lookup = 0;
10120   if (QT.isConstQualified())
10121     Lookup += 1<<0;
10122   if (QT.isRestrictQualified())
10123     Lookup += 1<<1;
10124   if (QT.isVolatileQualified())
10125     Lookup += 1<<2;
10126   Enc += Table[Lookup];
10127 }
10128 
10129 /// Appends built-in types to Enc.
10130 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10131   const char *EncType;
10132   switch (BT->getKind()) {
10133     case BuiltinType::Void:
10134       EncType = "0";
10135       break;
10136     case BuiltinType::Bool:
10137       EncType = "b";
10138       break;
10139     case BuiltinType::Char_U:
10140       EncType = "uc";
10141       break;
10142     case BuiltinType::UChar:
10143       EncType = "uc";
10144       break;
10145     case BuiltinType::SChar:
10146       EncType = "sc";
10147       break;
10148     case BuiltinType::UShort:
10149       EncType = "us";
10150       break;
10151     case BuiltinType::Short:
10152       EncType = "ss";
10153       break;
10154     case BuiltinType::UInt:
10155       EncType = "ui";
10156       break;
10157     case BuiltinType::Int:
10158       EncType = "si";
10159       break;
10160     case BuiltinType::ULong:
10161       EncType = "ul";
10162       break;
10163     case BuiltinType::Long:
10164       EncType = "sl";
10165       break;
10166     case BuiltinType::ULongLong:
10167       EncType = "ull";
10168       break;
10169     case BuiltinType::LongLong:
10170       EncType = "sll";
10171       break;
10172     case BuiltinType::Float:
10173       EncType = "ft";
10174       break;
10175     case BuiltinType::Double:
10176       EncType = "d";
10177       break;
10178     case BuiltinType::LongDouble:
10179       EncType = "ld";
10180       break;
10181     default:
10182       return false;
10183   }
10184   Enc += EncType;
10185   return true;
10186 }
10187 
10188 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10189 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10190                               const CodeGen::CodeGenModule &CGM,
10191                               TypeStringCache &TSC) {
10192   Enc += "p(";
10193   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10194     return false;
10195   Enc += ')';
10196   return true;
10197 }
10198 
10199 /// Appends array encoding to Enc before calling appendType for the element.
10200 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10201                             const ArrayType *AT,
10202                             const CodeGen::CodeGenModule &CGM,
10203                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10204   if (AT->getSizeModifier() != ArrayType::Normal)
10205     return false;
10206   Enc += "a(";
10207   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10208     CAT->getSize().toStringUnsigned(Enc);
10209   else
10210     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10211   Enc += ':';
10212   // The Qualifiers should be attached to the type rather than the array.
10213   appendQualifier(Enc, QT);
10214   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10215     return false;
10216   Enc += ')';
10217   return true;
10218 }
10219 
10220 /// Appends a function encoding to Enc, calling appendType for the return type
10221 /// and the arguments.
10222 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10223                              const CodeGen::CodeGenModule &CGM,
10224                              TypeStringCache &TSC) {
10225   Enc += "f{";
10226   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10227     return false;
10228   Enc += "}(";
10229   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10230     // N.B. we are only interested in the adjusted param types.
10231     auto I = FPT->param_type_begin();
10232     auto E = FPT->param_type_end();
10233     if (I != E) {
10234       do {
10235         if (!appendType(Enc, *I, CGM, TSC))
10236           return false;
10237         ++I;
10238         if (I != E)
10239           Enc += ',';
10240       } while (I != E);
10241       if (FPT->isVariadic())
10242         Enc += ",va";
10243     } else {
10244       if (FPT->isVariadic())
10245         Enc += "va";
10246       else
10247         Enc += '0';
10248     }
10249   }
10250   Enc += ')';
10251   return true;
10252 }
10253 
10254 /// Handles the type's qualifier before dispatching a call to handle specific
10255 /// type encodings.
10256 static bool appendType(SmallStringEnc &Enc, QualType QType,
10257                        const CodeGen::CodeGenModule &CGM,
10258                        TypeStringCache &TSC) {
10259 
10260   QualType QT = QType.getCanonicalType();
10261 
10262   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10263     // The Qualifiers should be attached to the type rather than the array.
10264     // Thus we don't call appendQualifier() here.
10265     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10266 
10267   appendQualifier(Enc, QT);
10268 
10269   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10270     return appendBuiltinType(Enc, BT);
10271 
10272   if (const PointerType *PT = QT->getAs<PointerType>())
10273     return appendPointerType(Enc, PT, CGM, TSC);
10274 
10275   if (const EnumType *ET = QT->getAs<EnumType>())
10276     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10277 
10278   if (const RecordType *RT = QT->getAsStructureType())
10279     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10280 
10281   if (const RecordType *RT = QT->getAsUnionType())
10282     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10283 
10284   if (const FunctionType *FT = QT->getAs<FunctionType>())
10285     return appendFunctionType(Enc, FT, CGM, TSC);
10286 
10287   return false;
10288 }
10289 
10290 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10291                           const CodeGen::CodeGenModule &CGM,
10292                           TypeStringCache &TSC) {
10293   if (!D)
10294     return false;
10295 
10296   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10297     if (FD->getLanguageLinkage() != CLanguageLinkage)
10298       return false;
10299     return appendType(Enc, FD->getType(), CGM, TSC);
10300   }
10301 
10302   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10303     if (VD->getLanguageLinkage() != CLanguageLinkage)
10304       return false;
10305     QualType QT = VD->getType().getCanonicalType();
10306     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10307       // Global ArrayTypes are given a size of '*' if the size is unknown.
10308       // The Qualifiers should be attached to the type rather than the array.
10309       // Thus we don't call appendQualifier() here.
10310       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10311     }
10312     return appendType(Enc, QT, CGM, TSC);
10313   }
10314   return false;
10315 }
10316 
10317 //===----------------------------------------------------------------------===//
10318 // RISCV ABI Implementation
10319 //===----------------------------------------------------------------------===//
10320 
10321 namespace {
10322 class RISCVABIInfo : public DefaultABIInfo {
10323 private:
10324   // Size of the integer ('x') registers in bits.
10325   unsigned XLen;
10326   // Size of the floating point ('f') registers in bits. Note that the target
10327   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10328   // with soft float ABI has FLen==0).
10329   unsigned FLen;
10330   static const int NumArgGPRs = 8;
10331   static const int NumArgFPRs = 8;
10332   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10333                                       llvm::Type *&Field1Ty,
10334                                       CharUnits &Field1Off,
10335                                       llvm::Type *&Field2Ty,
10336                                       CharUnits &Field2Off) const;
10337 
10338 public:
10339   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10340       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10341 
10342   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10343   // non-virtual, but computeInfo is virtual, so we overload it.
10344   void computeInfo(CGFunctionInfo &FI) const override;
10345 
10346   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10347                                   int &ArgFPRsLeft) const;
10348   ABIArgInfo classifyReturnType(QualType RetTy) const;
10349 
10350   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10351                     QualType Ty) const override;
10352 
10353   ABIArgInfo extendType(QualType Ty) const;
10354 
10355   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10356                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10357                                 CharUnits &Field2Off, int &NeededArgGPRs,
10358                                 int &NeededArgFPRs) const;
10359   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10360                                                CharUnits Field1Off,
10361                                                llvm::Type *Field2Ty,
10362                                                CharUnits Field2Off) const;
10363 };
10364 } // end anonymous namespace
10365 
10366 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10367   QualType RetTy = FI.getReturnType();
10368   if (!getCXXABI().classifyReturnType(FI))
10369     FI.getReturnInfo() = classifyReturnType(RetTy);
10370 
10371   // IsRetIndirect is true if classifyArgumentType indicated the value should
10372   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10373   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10374   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10375   // list and pass indirectly on RV32.
10376   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10377   if (!IsRetIndirect && RetTy->isScalarType() &&
10378       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10379     if (RetTy->isComplexType() && FLen) {
10380       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10381       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10382     } else {
10383       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10384       IsRetIndirect = true;
10385     }
10386   }
10387 
10388   // We must track the number of GPRs used in order to conform to the RISC-V
10389   // ABI, as integer scalars passed in registers should have signext/zeroext
10390   // when promoted, but are anyext if passed on the stack. As GPR usage is
10391   // different for variadic arguments, we must also track whether we are
10392   // examining a vararg or not.
10393   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10394   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10395   int NumFixedArgs = FI.getNumRequiredArgs();
10396 
10397   int ArgNum = 0;
10398   for (auto &ArgInfo : FI.arguments()) {
10399     bool IsFixed = ArgNum < NumFixedArgs;
10400     ArgInfo.info =
10401         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10402     ArgNum++;
10403   }
10404 }
10405 
10406 // Returns true if the struct is a potential candidate for the floating point
10407 // calling convention. If this function returns true, the caller is
10408 // responsible for checking that if there is only a single field then that
10409 // field is a float.
10410 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10411                                                   llvm::Type *&Field1Ty,
10412                                                   CharUnits &Field1Off,
10413                                                   llvm::Type *&Field2Ty,
10414                                                   CharUnits &Field2Off) const {
10415   bool IsInt = Ty->isIntegralOrEnumerationType();
10416   bool IsFloat = Ty->isRealFloatingType();
10417 
10418   if (IsInt || IsFloat) {
10419     uint64_t Size = getContext().getTypeSize(Ty);
10420     if (IsInt && Size > XLen)
10421       return false;
10422     // Can't be eligible if larger than the FP registers. Half precision isn't
10423     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10424     // default to the integer ABI in that case.
10425     if (IsFloat && (Size > FLen || Size < 32))
10426       return false;
10427     // Can't be eligible if an integer type was already found (int+int pairs
10428     // are not eligible).
10429     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10430       return false;
10431     if (!Field1Ty) {
10432       Field1Ty = CGT.ConvertType(Ty);
10433       Field1Off = CurOff;
10434       return true;
10435     }
10436     if (!Field2Ty) {
10437       Field2Ty = CGT.ConvertType(Ty);
10438       Field2Off = CurOff;
10439       return true;
10440     }
10441     return false;
10442   }
10443 
10444   if (auto CTy = Ty->getAs<ComplexType>()) {
10445     if (Field1Ty)
10446       return false;
10447     QualType EltTy = CTy->getElementType();
10448     if (getContext().getTypeSize(EltTy) > FLen)
10449       return false;
10450     Field1Ty = CGT.ConvertType(EltTy);
10451     Field1Off = CurOff;
10452     Field2Ty = Field1Ty;
10453     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10454     return true;
10455   }
10456 
10457   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10458     uint64_t ArraySize = ATy->getSize().getZExtValue();
10459     QualType EltTy = ATy->getElementType();
10460     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10461     for (uint64_t i = 0; i < ArraySize; ++i) {
10462       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10463                                                 Field1Off, Field2Ty, Field2Off);
10464       if (!Ret)
10465         return false;
10466       CurOff += EltSize;
10467     }
10468     return true;
10469   }
10470 
10471   if (const auto *RTy = Ty->getAs<RecordType>()) {
10472     // Structures with either a non-trivial destructor or a non-trivial
10473     // copy constructor are not eligible for the FP calling convention.
10474     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10475       return false;
10476     if (isEmptyRecord(getContext(), Ty, true))
10477       return true;
10478     const RecordDecl *RD = RTy->getDecl();
10479     // Unions aren't eligible unless they're empty (which is caught above).
10480     if (RD->isUnion())
10481       return false;
10482     int ZeroWidthBitFieldCount = 0;
10483     for (const FieldDecl *FD : RD->fields()) {
10484       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10485       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10486       QualType QTy = FD->getType();
10487       if (FD->isBitField()) {
10488         unsigned BitWidth = FD->getBitWidthValue(getContext());
10489         // Allow a bitfield with a type greater than XLen as long as the
10490         // bitwidth is XLen or less.
10491         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10492           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10493         if (BitWidth == 0) {
10494           ZeroWidthBitFieldCount++;
10495           continue;
10496         }
10497       }
10498 
10499       bool Ret = detectFPCCEligibleStructHelper(
10500           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10501           Field1Ty, Field1Off, Field2Ty, Field2Off);
10502       if (!Ret)
10503         return false;
10504 
10505       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10506       // or int+fp structs, but are ignored for a struct with an fp field and
10507       // any number of zero-width bitfields.
10508       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10509         return false;
10510     }
10511     return Field1Ty != nullptr;
10512   }
10513 
10514   return false;
10515 }
10516 
10517 // Determine if a struct is eligible for passing according to the floating
10518 // point calling convention (i.e., when flattened it contains a single fp
10519 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10520 // NeededArgGPRs are incremented appropriately.
10521 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10522                                             CharUnits &Field1Off,
10523                                             llvm::Type *&Field2Ty,
10524                                             CharUnits &Field2Off,
10525                                             int &NeededArgGPRs,
10526                                             int &NeededArgFPRs) const {
10527   Field1Ty = nullptr;
10528   Field2Ty = nullptr;
10529   NeededArgGPRs = 0;
10530   NeededArgFPRs = 0;
10531   bool IsCandidate = detectFPCCEligibleStructHelper(
10532       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10533   // Not really a candidate if we have a single int but no float.
10534   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10535     return false;
10536   if (!IsCandidate)
10537     return false;
10538   if (Field1Ty && Field1Ty->isFloatingPointTy())
10539     NeededArgFPRs++;
10540   else if (Field1Ty)
10541     NeededArgGPRs++;
10542   if (Field2Ty && Field2Ty->isFloatingPointTy())
10543     NeededArgFPRs++;
10544   else if (Field2Ty)
10545     NeededArgGPRs++;
10546   return true;
10547 }
10548 
10549 // Call getCoerceAndExpand for the two-element flattened struct described by
10550 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10551 // appropriate coerceToType and unpaddedCoerceToType.
10552 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10553     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10554     CharUnits Field2Off) const {
10555   SmallVector<llvm::Type *, 3> CoerceElts;
10556   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10557   if (!Field1Off.isZero())
10558     CoerceElts.push_back(llvm::ArrayType::get(
10559         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10560 
10561   CoerceElts.push_back(Field1Ty);
10562   UnpaddedCoerceElts.push_back(Field1Ty);
10563 
10564   if (!Field2Ty) {
10565     return ABIArgInfo::getCoerceAndExpand(
10566         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10567         UnpaddedCoerceElts[0]);
10568   }
10569 
10570   CharUnits Field2Align =
10571       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10572   CharUnits Field1End = Field1Off +
10573       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10574   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10575 
10576   CharUnits Padding = CharUnits::Zero();
10577   if (Field2Off > Field2OffNoPadNoPack)
10578     Padding = Field2Off - Field2OffNoPadNoPack;
10579   else if (Field2Off != Field2Align && Field2Off > Field1End)
10580     Padding = Field2Off - Field1End;
10581 
10582   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10583 
10584   if (!Padding.isZero())
10585     CoerceElts.push_back(llvm::ArrayType::get(
10586         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10587 
10588   CoerceElts.push_back(Field2Ty);
10589   UnpaddedCoerceElts.push_back(Field2Ty);
10590 
10591   auto CoerceToType =
10592       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10593   auto UnpaddedCoerceToType =
10594       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10595 
10596   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10597 }
10598 
10599 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10600                                               int &ArgGPRsLeft,
10601                                               int &ArgFPRsLeft) const {
10602   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10603   Ty = useFirstFieldIfTransparentUnion(Ty);
10604 
10605   // Structures with either a non-trivial destructor or a non-trivial
10606   // copy constructor are always passed indirectly.
10607   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10608     if (ArgGPRsLeft)
10609       ArgGPRsLeft -= 1;
10610     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10611                                            CGCXXABI::RAA_DirectInMemory);
10612   }
10613 
10614   // Ignore empty structs/unions.
10615   if (isEmptyRecord(getContext(), Ty, true))
10616     return ABIArgInfo::getIgnore();
10617 
10618   uint64_t Size = getContext().getTypeSize(Ty);
10619 
10620   // Pass floating point values via FPRs if possible.
10621   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10622       FLen >= Size && ArgFPRsLeft) {
10623     ArgFPRsLeft--;
10624     return ABIArgInfo::getDirect();
10625   }
10626 
10627   // Complex types for the hard float ABI must be passed direct rather than
10628   // using CoerceAndExpand.
10629   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10630     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10631     if (getContext().getTypeSize(EltTy) <= FLen) {
10632       ArgFPRsLeft -= 2;
10633       return ABIArgInfo::getDirect();
10634     }
10635   }
10636 
10637   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10638     llvm::Type *Field1Ty = nullptr;
10639     llvm::Type *Field2Ty = nullptr;
10640     CharUnits Field1Off = CharUnits::Zero();
10641     CharUnits Field2Off = CharUnits::Zero();
10642     int NeededArgGPRs;
10643     int NeededArgFPRs;
10644     bool IsCandidate =
10645         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10646                                  NeededArgGPRs, NeededArgFPRs);
10647     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10648         NeededArgFPRs <= ArgFPRsLeft) {
10649       ArgGPRsLeft -= NeededArgGPRs;
10650       ArgFPRsLeft -= NeededArgFPRs;
10651       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10652                                                Field2Off);
10653     }
10654   }
10655 
10656   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10657   bool MustUseStack = false;
10658   // Determine the number of GPRs needed to pass the current argument
10659   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10660   // register pairs, so may consume 3 registers.
10661   int NeededArgGPRs = 1;
10662   if (!IsFixed && NeededAlign == 2 * XLen)
10663     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10664   else if (Size > XLen && Size <= 2 * XLen)
10665     NeededArgGPRs = 2;
10666 
10667   if (NeededArgGPRs > ArgGPRsLeft) {
10668     MustUseStack = true;
10669     NeededArgGPRs = ArgGPRsLeft;
10670   }
10671 
10672   ArgGPRsLeft -= NeededArgGPRs;
10673 
10674   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10675     // Treat an enum type as its underlying type.
10676     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10677       Ty = EnumTy->getDecl()->getIntegerType();
10678 
10679     // All integral types are promoted to XLen width, unless passed on the
10680     // stack.
10681     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10682       return extendType(Ty);
10683     }
10684 
10685     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10686       if (EIT->getNumBits() < XLen && !MustUseStack)
10687         return extendType(Ty);
10688       if (EIT->getNumBits() > 128 ||
10689           (!getContext().getTargetInfo().hasInt128Type() &&
10690            EIT->getNumBits() > 64))
10691         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10692     }
10693 
10694     return ABIArgInfo::getDirect();
10695   }
10696 
10697   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10698   // so coerce to integers.
10699   if (Size <= 2 * XLen) {
10700     unsigned Alignment = getContext().getTypeAlign(Ty);
10701 
10702     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10703     // required, and a 2-element XLen array if only XLen alignment is required.
10704     if (Size <= XLen) {
10705       return ABIArgInfo::getDirect(
10706           llvm::IntegerType::get(getVMContext(), XLen));
10707     } else if (Alignment == 2 * XLen) {
10708       return ABIArgInfo::getDirect(
10709           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10710     } else {
10711       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10712           llvm::IntegerType::get(getVMContext(), XLen), 2));
10713     }
10714   }
10715   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10716 }
10717 
10718 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10719   if (RetTy->isVoidType())
10720     return ABIArgInfo::getIgnore();
10721 
10722   int ArgGPRsLeft = 2;
10723   int ArgFPRsLeft = FLen ? 2 : 0;
10724 
10725   // The rules for return and argument types are the same, so defer to
10726   // classifyArgumentType.
10727   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10728                               ArgFPRsLeft);
10729 }
10730 
10731 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10732                                 QualType Ty) const {
10733   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10734 
10735   // Empty records are ignored for parameter passing purposes.
10736   if (isEmptyRecord(getContext(), Ty, true)) {
10737     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10738     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10739     return Addr;
10740   }
10741 
10742   auto TInfo = getContext().getTypeInfoInChars(Ty);
10743 
10744   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10745   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10746 
10747   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10748                           SlotSize, /*AllowHigherAlign=*/true);
10749 }
10750 
10751 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10752   int TySize = getContext().getTypeSize(Ty);
10753   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10754   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10755     return ABIArgInfo::getSignExtend(Ty);
10756   return ABIArgInfo::getExtend(Ty);
10757 }
10758 
10759 namespace {
10760 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10761 public:
10762   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10763                          unsigned FLen)
10764       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10765 
10766   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10767                            CodeGen::CodeGenModule &CGM) const override {
10768     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10769     if (!FD) return;
10770 
10771     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10772     if (!Attr)
10773       return;
10774 
10775     const char *Kind;
10776     switch (Attr->getInterrupt()) {
10777     case RISCVInterruptAttr::user: Kind = "user"; break;
10778     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10779     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10780     }
10781 
10782     auto *Fn = cast<llvm::Function>(GV);
10783 
10784     Fn->addFnAttr("interrupt", Kind);
10785   }
10786 };
10787 } // namespace
10788 
10789 //===----------------------------------------------------------------------===//
10790 // VE ABI Implementation.
10791 //
10792 namespace {
10793 class VEABIInfo : public DefaultABIInfo {
10794 public:
10795   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10796 
10797 private:
10798   ABIArgInfo classifyReturnType(QualType RetTy) const;
10799   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10800   void computeInfo(CGFunctionInfo &FI) const override;
10801 };
10802 } // end anonymous namespace
10803 
10804 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10805   if (Ty->isAnyComplexType())
10806     return ABIArgInfo::getDirect();
10807   uint64_t Size = getContext().getTypeSize(Ty);
10808   if (Size < 64 && Ty->isIntegerType())
10809     return ABIArgInfo::getExtend(Ty);
10810   return DefaultABIInfo::classifyReturnType(Ty);
10811 }
10812 
10813 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10814   if (Ty->isAnyComplexType())
10815     return ABIArgInfo::getDirect();
10816   uint64_t Size = getContext().getTypeSize(Ty);
10817   if (Size < 64 && Ty->isIntegerType())
10818     return ABIArgInfo::getExtend(Ty);
10819   return DefaultABIInfo::classifyArgumentType(Ty);
10820 }
10821 
10822 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10823   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10824   for (auto &Arg : FI.arguments())
10825     Arg.info = classifyArgumentType(Arg.type);
10826 }
10827 
10828 namespace {
10829 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10830 public:
10831   VETargetCodeGenInfo(CodeGenTypes &CGT)
10832       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10833   // VE ABI requires the arguments of variadic and prototype-less functions
10834   // are passed in both registers and memory.
10835   bool isNoProtoCallVariadic(const CallArgList &args,
10836                              const FunctionNoProtoType *fnType) const override {
10837     return true;
10838   }
10839 };
10840 } // end anonymous namespace
10841 
10842 //===----------------------------------------------------------------------===//
10843 // Driver code
10844 //===----------------------------------------------------------------------===//
10845 
10846 bool CodeGenModule::supportsCOMDAT() const {
10847   return getTriple().supportsCOMDAT();
10848 }
10849 
10850 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10851   if (TheTargetCodeGenInfo)
10852     return *TheTargetCodeGenInfo;
10853 
10854   // Helper to set the unique_ptr while still keeping the return value.
10855   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10856     this->TheTargetCodeGenInfo.reset(P);
10857     return *P;
10858   };
10859 
10860   const llvm::Triple &Triple = getTarget().getTriple();
10861   switch (Triple.getArch()) {
10862   default:
10863     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10864 
10865   case llvm::Triple::le32:
10866     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10867   case llvm::Triple::mips:
10868   case llvm::Triple::mipsel:
10869     if (Triple.getOS() == llvm::Triple::NaCl)
10870       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10871     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10872 
10873   case llvm::Triple::mips64:
10874   case llvm::Triple::mips64el:
10875     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10876 
10877   case llvm::Triple::avr:
10878     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10879 
10880   case llvm::Triple::aarch64:
10881   case llvm::Triple::aarch64_32:
10882   case llvm::Triple::aarch64_be: {
10883     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10884     if (getTarget().getABI() == "darwinpcs")
10885       Kind = AArch64ABIInfo::DarwinPCS;
10886     else if (Triple.isOSWindows())
10887       return SetCGInfo(
10888           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10889 
10890     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10891   }
10892 
10893   case llvm::Triple::wasm32:
10894   case llvm::Triple::wasm64: {
10895     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10896     if (getTarget().getABI() == "experimental-mv")
10897       Kind = WebAssemblyABIInfo::ExperimentalMV;
10898     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10899   }
10900 
10901   case llvm::Triple::arm:
10902   case llvm::Triple::armeb:
10903   case llvm::Triple::thumb:
10904   case llvm::Triple::thumbeb: {
10905     if (Triple.getOS() == llvm::Triple::Win32) {
10906       return SetCGInfo(
10907           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10908     }
10909 
10910     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10911     StringRef ABIStr = getTarget().getABI();
10912     if (ABIStr == "apcs-gnu")
10913       Kind = ARMABIInfo::APCS;
10914     else if (ABIStr == "aapcs16")
10915       Kind = ARMABIInfo::AAPCS16_VFP;
10916     else if (CodeGenOpts.FloatABI == "hard" ||
10917              (CodeGenOpts.FloatABI != "soft" &&
10918               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10919                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10920                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10921       Kind = ARMABIInfo::AAPCS_VFP;
10922 
10923     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10924   }
10925 
10926   case llvm::Triple::ppc: {
10927     if (Triple.isOSAIX())
10928       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10929 
10930     bool IsSoftFloat =
10931         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10932     bool RetSmallStructInRegABI =
10933         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10934     return SetCGInfo(
10935         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10936   }
10937   case llvm::Triple::ppc64:
10938     if (Triple.isOSAIX())
10939       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10940 
10941     if (Triple.isOSBinFormatELF()) {
10942       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10943       if (getTarget().getABI() == "elfv2")
10944         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10945       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10946 
10947       return SetCGInfo(
10948           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10949     }
10950     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10951   case llvm::Triple::ppc64le: {
10952     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10953     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10954     if (getTarget().getABI() == "elfv1")
10955       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10956     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10957 
10958     return SetCGInfo(
10959         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10960   }
10961 
10962   case llvm::Triple::nvptx:
10963   case llvm::Triple::nvptx64:
10964     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10965 
10966   case llvm::Triple::msp430:
10967     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10968 
10969   case llvm::Triple::riscv32:
10970   case llvm::Triple::riscv64: {
10971     StringRef ABIStr = getTarget().getABI();
10972     unsigned XLen = getTarget().getPointerWidth(0);
10973     unsigned ABIFLen = 0;
10974     if (ABIStr.endswith("f"))
10975       ABIFLen = 32;
10976     else if (ABIStr.endswith("d"))
10977       ABIFLen = 64;
10978     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10979   }
10980 
10981   case llvm::Triple::systemz: {
10982     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
10983     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
10984     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
10985   }
10986 
10987   case llvm::Triple::tce:
10988   case llvm::Triple::tcele:
10989     return SetCGInfo(new TCETargetCodeGenInfo(Types));
10990 
10991   case llvm::Triple::x86: {
10992     bool IsDarwinVectorABI = Triple.isOSDarwin();
10993     bool RetSmallStructInRegABI =
10994         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10995     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
10996 
10997     if (Triple.getOS() == llvm::Triple::Win32) {
10998       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
10999           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11000           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11001     } else {
11002       return SetCGInfo(new X86_32TargetCodeGenInfo(
11003           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11004           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11005           CodeGenOpts.FloatABI == "soft"));
11006     }
11007   }
11008 
11009   case llvm::Triple::x86_64: {
11010     StringRef ABI = getTarget().getABI();
11011     X86AVXABILevel AVXLevel =
11012         (ABI == "avx512"
11013              ? X86AVXABILevel::AVX512
11014              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11015 
11016     switch (Triple.getOS()) {
11017     case llvm::Triple::Win32:
11018       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11019     default:
11020       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11021     }
11022   }
11023   case llvm::Triple::hexagon:
11024     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11025   case llvm::Triple::lanai:
11026     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11027   case llvm::Triple::r600:
11028     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11029   case llvm::Triple::amdgcn:
11030     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11031   case llvm::Triple::sparc:
11032     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11033   case llvm::Triple::sparcv9:
11034     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11035   case llvm::Triple::xcore:
11036     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11037   case llvm::Triple::arc:
11038     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11039   case llvm::Triple::spir:
11040   case llvm::Triple::spir64:
11041     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11042   case llvm::Triple::ve:
11043     return SetCGInfo(new VETargetCodeGenInfo(Types));
11044   }
11045 }
11046 
11047 /// Create an OpenCL kernel for an enqueued block.
11048 ///
11049 /// The kernel has the same function type as the block invoke function. Its
11050 /// name is the name of the block invoke function postfixed with "_kernel".
11051 /// It simply calls the block invoke function then returns.
11052 llvm::Function *
11053 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11054                                              llvm::Function *Invoke,
11055                                              llvm::Value *BlockLiteral) const {
11056   auto *InvokeFT = Invoke->getFunctionType();
11057   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11058   for (auto &P : InvokeFT->params())
11059     ArgTys.push_back(P);
11060   auto &C = CGF.getLLVMContext();
11061   std::string Name = Invoke->getName().str() + "_kernel";
11062   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11063   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11064                                    &CGF.CGM.getModule());
11065   auto IP = CGF.Builder.saveIP();
11066   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11067   auto &Builder = CGF.Builder;
11068   Builder.SetInsertPoint(BB);
11069   llvm::SmallVector<llvm::Value *, 2> Args;
11070   for (auto &A : F->args())
11071     Args.push_back(&A);
11072   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11073   call->setCallingConv(Invoke->getCallingConv());
11074   Builder.CreateRetVoid();
11075   Builder.restoreIP(IP);
11076   return F;
11077 }
11078 
11079 /// Create an OpenCL kernel for an enqueued block.
11080 ///
11081 /// The type of the first argument (the block literal) is the struct type
11082 /// of the block literal instead of a pointer type. The first argument
11083 /// (block literal) is passed directly by value to the kernel. The kernel
11084 /// allocates the same type of struct on stack and stores the block literal
11085 /// to it and passes its pointer to the block invoke function. The kernel
11086 /// has "enqueued-block" function attribute and kernel argument metadata.
11087 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11088     CodeGenFunction &CGF, llvm::Function *Invoke,
11089     llvm::Value *BlockLiteral) const {
11090   auto &Builder = CGF.Builder;
11091   auto &C = CGF.getLLVMContext();
11092 
11093   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11094   auto *InvokeFT = Invoke->getFunctionType();
11095   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11096   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11097   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11098   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11099   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11100   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11101   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11102 
11103   ArgTys.push_back(BlockTy);
11104   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11105   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11106   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11107   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11108   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11109   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11110   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11111     ArgTys.push_back(InvokeFT->getParamType(I));
11112     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11113     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11114     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11115     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11116     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11117     ArgNames.push_back(
11118         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11119   }
11120   std::string Name = Invoke->getName().str() + "_kernel";
11121   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11122   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11123                                    &CGF.CGM.getModule());
11124   F->addFnAttr("enqueued-block");
11125   auto IP = CGF.Builder.saveIP();
11126   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11127   Builder.SetInsertPoint(BB);
11128   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11129   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11130   BlockPtr->setAlignment(BlockAlign);
11131   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11132   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11133   llvm::SmallVector<llvm::Value *, 2> Args;
11134   Args.push_back(Cast);
11135   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11136     Args.push_back(I);
11137   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11138   call->setCallingConv(Invoke->getCallingConv());
11139   Builder.CreateRetVoid();
11140   Builder.restoreIP(IP);
11141 
11142   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11143   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11144   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11145   F->setMetadata("kernel_arg_base_type",
11146                  llvm::MDNode::get(C, ArgBaseTypeNames));
11147   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11148   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11149     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11150 
11151   return F;
11152 }
11153