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 /// X86_32ABIInfo - The X86-32 ABI information.
1093 class X86_32ABIInfo : public SwiftABIInfo {
1094   enum Class {
1095     Integer,
1096     Float
1097   };
1098 
1099   static const unsigned MinABIStackAlignInBytes = 4;
1100 
1101   bool IsDarwinVectorABI;
1102   bool IsRetSmallStructInRegABI;
1103   bool IsWin32StructABI;
1104   bool IsSoftFloatABI;
1105   bool IsMCUABI;
1106   unsigned DefaultNumRegisterParameters;
1107 
1108   static bool isRegisterSize(unsigned Size) {
1109     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1110   }
1111 
1112   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1113     // FIXME: Assumes vectorcall is in use.
1114     return isX86VectorTypeForVectorCall(getContext(), Ty);
1115   }
1116 
1117   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1118                                          uint64_t NumMembers) const override {
1119     // FIXME: Assumes vectorcall is in use.
1120     return isX86VectorCallAggregateSmallEnough(NumMembers);
1121   }
1122 
1123   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1124 
1125   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1126   /// such that the argument will be passed in memory.
1127   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1128 
1129   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1130 
1131   /// Return the alignment to use for the given type on the stack.
1132   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1133 
1134   Class classify(QualType Ty) const;
1135   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1136   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1137 
1138   /// Updates the number of available free registers, returns
1139   /// true if any registers were allocated.
1140   bool updateFreeRegs(QualType Ty, CCState &State) const;
1141 
1142   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1143                                 bool &NeedsPadding) const;
1144   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1145 
1146   bool canExpandIndirectArgument(QualType Ty) const;
1147 
1148   /// Rewrite the function info so that all memory arguments use
1149   /// inalloca.
1150   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1151 
1152   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1153                            CharUnits &StackOffset, ABIArgInfo &Info,
1154                            QualType Type) const;
1155   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1156 
1157 public:
1158 
1159   void computeInfo(CGFunctionInfo &FI) const override;
1160   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1161                     QualType Ty) const override;
1162 
1163   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1164                 bool RetSmallStructInRegABI, bool Win32StructABI,
1165                 unsigned NumRegisterParameters, bool SoftFloatABI)
1166     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1167       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1168       IsWin32StructABI(Win32StructABI),
1169       IsSoftFloatABI(SoftFloatABI),
1170       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1171       DefaultNumRegisterParameters(NumRegisterParameters) {}
1172 
1173   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1174                                     bool asReturnValue) const override {
1175     // LLVM's x86-32 lowering currently only assigns up to three
1176     // integer registers and three fp registers.  Oddly, it'll use up to
1177     // four vector registers for vectors, but those can overlap with the
1178     // scalar registers.
1179     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1180   }
1181 
1182   bool isSwiftErrorInRegister() const override {
1183     // x86-32 lowering does not support passing swifterror in a register.
1184     return false;
1185   }
1186 };
1187 
1188 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1189 public:
1190   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1191                           bool RetSmallStructInRegABI, bool Win32StructABI,
1192                           unsigned NumRegisterParameters, bool SoftFloatABI)
1193       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1194             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1195             NumRegisterParameters, SoftFloatABI)) {}
1196 
1197   static bool isStructReturnInRegABI(
1198       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1199 
1200   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1201                            CodeGen::CodeGenModule &CGM) const override;
1202 
1203   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1204     // Darwin uses different dwarf register numbers for EH.
1205     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1206     return 4;
1207   }
1208 
1209   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1210                                llvm::Value *Address) const override;
1211 
1212   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1213                                   StringRef Constraint,
1214                                   llvm::Type* Ty) const override {
1215     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1216   }
1217 
1218   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1219                                 std::string &Constraints,
1220                                 std::vector<llvm::Type *> &ResultRegTypes,
1221                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1222                                 std::vector<LValue> &ResultRegDests,
1223                                 std::string &AsmString,
1224                                 unsigned NumOutputs) const override;
1225 
1226   llvm::Constant *
1227   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1228     unsigned Sig = (0xeb << 0) |  // jmp rel8
1229                    (0x06 << 8) |  //           .+0x08
1230                    ('v' << 16) |
1231                    ('2' << 24);
1232     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1233   }
1234 
1235   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1236     return "movl\t%ebp, %ebp"
1237            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1238   }
1239 };
1240 
1241 }
1242 
1243 /// Rewrite input constraint references after adding some output constraints.
1244 /// In the case where there is one output and one input and we add one output,
1245 /// we need to replace all operand references greater than or equal to 1:
1246 ///     mov $0, $1
1247 ///     mov eax, $1
1248 /// The result will be:
1249 ///     mov $0, $2
1250 ///     mov eax, $2
1251 static void rewriteInputConstraintReferences(unsigned FirstIn,
1252                                              unsigned NumNewOuts,
1253                                              std::string &AsmString) {
1254   std::string Buf;
1255   llvm::raw_string_ostream OS(Buf);
1256   size_t Pos = 0;
1257   while (Pos < AsmString.size()) {
1258     size_t DollarStart = AsmString.find('$', Pos);
1259     if (DollarStart == std::string::npos)
1260       DollarStart = AsmString.size();
1261     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1262     if (DollarEnd == std::string::npos)
1263       DollarEnd = AsmString.size();
1264     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1265     Pos = DollarEnd;
1266     size_t NumDollars = DollarEnd - DollarStart;
1267     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1268       // We have an operand reference.
1269       size_t DigitStart = Pos;
1270       if (AsmString[DigitStart] == '{') {
1271         OS << '{';
1272         ++DigitStart;
1273       }
1274       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1275       if (DigitEnd == std::string::npos)
1276         DigitEnd = AsmString.size();
1277       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1278       unsigned OperandIndex;
1279       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1280         if (OperandIndex >= FirstIn)
1281           OperandIndex += NumNewOuts;
1282         OS << OperandIndex;
1283       } else {
1284         OS << OperandStr;
1285       }
1286       Pos = DigitEnd;
1287     }
1288   }
1289   AsmString = std::move(OS.str());
1290 }
1291 
1292 /// Add output constraints for EAX:EDX because they are return registers.
1293 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1294     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1295     std::vector<llvm::Type *> &ResultRegTypes,
1296     std::vector<llvm::Type *> &ResultTruncRegTypes,
1297     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1298     unsigned NumOutputs) const {
1299   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1300 
1301   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1302   // larger.
1303   if (!Constraints.empty())
1304     Constraints += ',';
1305   if (RetWidth <= 32) {
1306     Constraints += "={eax}";
1307     ResultRegTypes.push_back(CGF.Int32Ty);
1308   } else {
1309     // Use the 'A' constraint for EAX:EDX.
1310     Constraints += "=A";
1311     ResultRegTypes.push_back(CGF.Int64Ty);
1312   }
1313 
1314   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1315   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1316   ResultTruncRegTypes.push_back(CoerceTy);
1317 
1318   // Coerce the integer by bitcasting the return slot pointer.
1319   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1320                                                   CoerceTy->getPointerTo()));
1321   ResultRegDests.push_back(ReturnSlot);
1322 
1323   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1324 }
1325 
1326 /// shouldReturnTypeInRegister - Determine if the given type should be
1327 /// returned in a register (for the Darwin and MCU ABI).
1328 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1329                                                ASTContext &Context) const {
1330   uint64_t Size = Context.getTypeSize(Ty);
1331 
1332   // For i386, type must be register sized.
1333   // For the MCU ABI, it only needs to be <= 8-byte
1334   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1335    return false;
1336 
1337   if (Ty->isVectorType()) {
1338     // 64- and 128- bit vectors inside structures are not returned in
1339     // registers.
1340     if (Size == 64 || Size == 128)
1341       return false;
1342 
1343     return true;
1344   }
1345 
1346   // If this is a builtin, pointer, enum, complex type, member pointer, or
1347   // member function pointer it is ok.
1348   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1349       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1350       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1351     return true;
1352 
1353   // Arrays are treated like records.
1354   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1355     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1356 
1357   // Otherwise, it must be a record type.
1358   const RecordType *RT = Ty->getAs<RecordType>();
1359   if (!RT) return false;
1360 
1361   // FIXME: Traverse bases here too.
1362 
1363   // Structure types are passed in register if all fields would be
1364   // passed in a register.
1365   for (const auto *FD : RT->getDecl()->fields()) {
1366     // Empty fields are ignored.
1367     if (isEmptyField(Context, FD, true))
1368       continue;
1369 
1370     // Check fields recursively.
1371     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1372       return false;
1373   }
1374   return true;
1375 }
1376 
1377 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1378   // Treat complex types as the element type.
1379   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1380     Ty = CTy->getElementType();
1381 
1382   // Check for a type which we know has a simple scalar argument-passing
1383   // convention without any padding.  (We're specifically looking for 32
1384   // and 64-bit integer and integer-equivalents, float, and double.)
1385   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1386       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1387     return false;
1388 
1389   uint64_t Size = Context.getTypeSize(Ty);
1390   return Size == 32 || Size == 64;
1391 }
1392 
1393 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1394                           uint64_t &Size) {
1395   for (const auto *FD : RD->fields()) {
1396     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1397     // argument is smaller than 32-bits, expanding the struct will create
1398     // alignment padding.
1399     if (!is32Or64BitBasicType(FD->getType(), Context))
1400       return false;
1401 
1402     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1403     // how to expand them yet, and the predicate for telling if a bitfield still
1404     // counts as "basic" is more complicated than what we were doing previously.
1405     if (FD->isBitField())
1406       return false;
1407 
1408     Size += Context.getTypeSize(FD->getType());
1409   }
1410   return true;
1411 }
1412 
1413 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1414                                  uint64_t &Size) {
1415   // Don't do this if there are any non-empty bases.
1416   for (const CXXBaseSpecifier &Base : RD->bases()) {
1417     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1418                               Size))
1419       return false;
1420   }
1421   if (!addFieldSizes(Context, RD, Size))
1422     return false;
1423   return true;
1424 }
1425 
1426 /// Test whether an argument type which is to be passed indirectly (on the
1427 /// stack) would have the equivalent layout if it was expanded into separate
1428 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1429 /// optimizations.
1430 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1431   // We can only expand structure types.
1432   const RecordType *RT = Ty->getAs<RecordType>();
1433   if (!RT)
1434     return false;
1435   const RecordDecl *RD = RT->getDecl();
1436   uint64_t Size = 0;
1437   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1438     if (!IsWin32StructABI) {
1439       // On non-Windows, we have to conservatively match our old bitcode
1440       // prototypes in order to be ABI-compatible at the bitcode level.
1441       if (!CXXRD->isCLike())
1442         return false;
1443     } else {
1444       // Don't do this for dynamic classes.
1445       if (CXXRD->isDynamicClass())
1446         return false;
1447     }
1448     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1449       return false;
1450   } else {
1451     if (!addFieldSizes(getContext(), RD, Size))
1452       return false;
1453   }
1454 
1455   // We can do this if there was no alignment padding.
1456   return Size == getContext().getTypeSize(Ty);
1457 }
1458 
1459 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1460   // If the return value is indirect, then the hidden argument is consuming one
1461   // integer register.
1462   if (State.FreeRegs) {
1463     --State.FreeRegs;
1464     if (!IsMCUABI)
1465       return getNaturalAlignIndirectInReg(RetTy);
1466   }
1467   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1468 }
1469 
1470 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1471                                              CCState &State) const {
1472   if (RetTy->isVoidType())
1473     return ABIArgInfo::getIgnore();
1474 
1475   const Type *Base = nullptr;
1476   uint64_t NumElts = 0;
1477   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1478        State.CC == llvm::CallingConv::X86_RegCall) &&
1479       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1480     // The LLVM struct type for such an aggregate should lower properly.
1481     return ABIArgInfo::getDirect();
1482   }
1483 
1484   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1485     // On Darwin, some vectors are returned in registers.
1486     if (IsDarwinVectorABI) {
1487       uint64_t Size = getContext().getTypeSize(RetTy);
1488 
1489       // 128-bit vectors are a special case; they are returned in
1490       // registers and we need to make sure to pick a type the LLVM
1491       // backend will like.
1492       if (Size == 128)
1493         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1494             llvm::Type::getInt64Ty(getVMContext()), 2));
1495 
1496       // Always return in register if it fits in a general purpose
1497       // register, or if it is 64 bits and has a single element.
1498       if ((Size == 8 || Size == 16 || Size == 32) ||
1499           (Size == 64 && VT->getNumElements() == 1))
1500         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1501                                                             Size));
1502 
1503       return getIndirectReturnResult(RetTy, State);
1504     }
1505 
1506     return ABIArgInfo::getDirect();
1507   }
1508 
1509   if (isAggregateTypeForABI(RetTy)) {
1510     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1511       // Structures with flexible arrays are always indirect.
1512       if (RT->getDecl()->hasFlexibleArrayMember())
1513         return getIndirectReturnResult(RetTy, State);
1514     }
1515 
1516     // If specified, structs and unions are always indirect.
1517     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1518       return getIndirectReturnResult(RetTy, State);
1519 
1520     // Ignore empty structs/unions.
1521     if (isEmptyRecord(getContext(), RetTy, true))
1522       return ABIArgInfo::getIgnore();
1523 
1524     // Small structures which are register sized are generally returned
1525     // in a register.
1526     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1527       uint64_t Size = getContext().getTypeSize(RetTy);
1528 
1529       // As a special-case, if the struct is a "single-element" struct, and
1530       // the field is of type "float" or "double", return it in a
1531       // floating-point register. (MSVC does not apply this special case.)
1532       // We apply a similar transformation for pointer types to improve the
1533       // quality of the generated IR.
1534       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1535         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1536             || SeltTy->hasPointerRepresentation())
1537           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1538 
1539       // FIXME: We should be able to narrow this integer in cases with dead
1540       // padding.
1541       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1542     }
1543 
1544     return getIndirectReturnResult(RetTy, State);
1545   }
1546 
1547   // Treat an enum type as its underlying type.
1548   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1549     RetTy = EnumTy->getDecl()->getIntegerType();
1550 
1551   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1552     if (EIT->getNumBits() > 64)
1553       return getIndirectReturnResult(RetTy, State);
1554 
1555   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1556                                                : ABIArgInfo::getDirect());
1557 }
1558 
1559 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1560   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1561 }
1562 
1563 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1564   const RecordType *RT = Ty->getAs<RecordType>();
1565   if (!RT)
1566     return 0;
1567   const RecordDecl *RD = RT->getDecl();
1568 
1569   // If this is a C++ record, check the bases first.
1570   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1571     for (const auto &I : CXXRD->bases())
1572       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1573         return false;
1574 
1575   for (const auto *i : RD->fields()) {
1576     QualType FT = i->getType();
1577 
1578     if (isSIMDVectorType(Context, FT))
1579       return true;
1580 
1581     if (isRecordWithSIMDVectorType(Context, FT))
1582       return true;
1583   }
1584 
1585   return false;
1586 }
1587 
1588 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1589                                                  unsigned Align) const {
1590   // Otherwise, if the alignment is less than or equal to the minimum ABI
1591   // alignment, just use the default; the backend will handle this.
1592   if (Align <= MinABIStackAlignInBytes)
1593     return 0; // Use default alignment.
1594 
1595   // On non-Darwin, the stack type alignment is always 4.
1596   if (!IsDarwinVectorABI) {
1597     // Set explicit alignment, since we may need to realign the top.
1598     return MinABIStackAlignInBytes;
1599   }
1600 
1601   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1602   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1603                       isRecordWithSIMDVectorType(getContext(), Ty)))
1604     return 16;
1605 
1606   return MinABIStackAlignInBytes;
1607 }
1608 
1609 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1610                                             CCState &State) const {
1611   if (!ByVal) {
1612     if (State.FreeRegs) {
1613       --State.FreeRegs; // Non-byval indirects just use one pointer.
1614       if (!IsMCUABI)
1615         return getNaturalAlignIndirectInReg(Ty);
1616     }
1617     return getNaturalAlignIndirect(Ty, false);
1618   }
1619 
1620   // Compute the byval alignment.
1621   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1622   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1623   if (StackAlign == 0)
1624     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1625 
1626   // If the stack alignment is less than the type alignment, realign the
1627   // argument.
1628   bool Realign = TypeAlign > StackAlign;
1629   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1630                                  /*ByVal=*/true, Realign);
1631 }
1632 
1633 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1634   const Type *T = isSingleElementStruct(Ty, getContext());
1635   if (!T)
1636     T = Ty.getTypePtr();
1637 
1638   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1639     BuiltinType::Kind K = BT->getKind();
1640     if (K == BuiltinType::Float || K == BuiltinType::Double)
1641       return Float;
1642   }
1643   return Integer;
1644 }
1645 
1646 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1647   if (!IsSoftFloatABI) {
1648     Class C = classify(Ty);
1649     if (C == Float)
1650       return false;
1651   }
1652 
1653   unsigned Size = getContext().getTypeSize(Ty);
1654   unsigned SizeInRegs = (Size + 31) / 32;
1655 
1656   if (SizeInRegs == 0)
1657     return false;
1658 
1659   if (!IsMCUABI) {
1660     if (SizeInRegs > State.FreeRegs) {
1661       State.FreeRegs = 0;
1662       return false;
1663     }
1664   } else {
1665     // The MCU psABI allows passing parameters in-reg even if there are
1666     // earlier parameters that are passed on the stack. Also,
1667     // it does not allow passing >8-byte structs in-register,
1668     // even if there are 3 free registers available.
1669     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1670       return false;
1671   }
1672 
1673   State.FreeRegs -= SizeInRegs;
1674   return true;
1675 }
1676 
1677 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1678                                              bool &InReg,
1679                                              bool &NeedsPadding) const {
1680   // On Windows, aggregates other than HFAs are never passed in registers, and
1681   // they do not consume register slots. Homogenous floating-point aggregates
1682   // (HFAs) have already been dealt with at this point.
1683   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1684     return false;
1685 
1686   NeedsPadding = false;
1687   InReg = !IsMCUABI;
1688 
1689   if (!updateFreeRegs(Ty, State))
1690     return false;
1691 
1692   if (IsMCUABI)
1693     return true;
1694 
1695   if (State.CC == llvm::CallingConv::X86_FastCall ||
1696       State.CC == llvm::CallingConv::X86_VectorCall ||
1697       State.CC == llvm::CallingConv::X86_RegCall) {
1698     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1699       NeedsPadding = true;
1700 
1701     return false;
1702   }
1703 
1704   return true;
1705 }
1706 
1707 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1708   if (!updateFreeRegs(Ty, State))
1709     return false;
1710 
1711   if (IsMCUABI)
1712     return false;
1713 
1714   if (State.CC == llvm::CallingConv::X86_FastCall ||
1715       State.CC == llvm::CallingConv::X86_VectorCall ||
1716       State.CC == llvm::CallingConv::X86_RegCall) {
1717     if (getContext().getTypeSize(Ty) > 32)
1718       return false;
1719 
1720     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1721         Ty->isReferenceType());
1722   }
1723 
1724   return true;
1725 }
1726 
1727 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1728   // Vectorcall x86 works subtly different than in x64, so the format is
1729   // a bit different than the x64 version.  First, all vector types (not HVAs)
1730   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1731   // This differs from the x64 implementation, where the first 6 by INDEX get
1732   // registers.
1733   // In the second pass over the arguments, HVAs are passed in the remaining
1734   // vector registers if possible, or indirectly by address. The address will be
1735   // passed in ECX/EDX if available. Any other arguments are passed according to
1736   // the usual fastcall rules.
1737   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1738   for (int I = 0, E = Args.size(); I < E; ++I) {
1739     const Type *Base = nullptr;
1740     uint64_t NumElts = 0;
1741     const QualType &Ty = Args[I].type;
1742     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1743         isHomogeneousAggregate(Ty, Base, NumElts)) {
1744       if (State.FreeSSERegs >= NumElts) {
1745         State.FreeSSERegs -= NumElts;
1746         Args[I].info = ABIArgInfo::getDirectInReg();
1747         State.IsPreassigned.set(I);
1748       }
1749     }
1750   }
1751 }
1752 
1753 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1754                                                CCState &State) const {
1755   // FIXME: Set alignment on indirect arguments.
1756   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1757   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1758   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1759 
1760   Ty = useFirstFieldIfTransparentUnion(Ty);
1761   TypeInfo TI = getContext().getTypeInfo(Ty);
1762 
1763   // Check with the C++ ABI first.
1764   const RecordType *RT = Ty->getAs<RecordType>();
1765   if (RT) {
1766     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1767     if (RAA == CGCXXABI::RAA_Indirect) {
1768       return getIndirectResult(Ty, false, State);
1769     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1770       // The field index doesn't matter, we'll fix it up later.
1771       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1772     }
1773   }
1774 
1775   // Regcall uses the concept of a homogenous vector aggregate, similar
1776   // to other targets.
1777   const Type *Base = nullptr;
1778   uint64_t NumElts = 0;
1779   if ((IsRegCall || IsVectorCall) &&
1780       isHomogeneousAggregate(Ty, Base, NumElts)) {
1781     if (State.FreeSSERegs >= NumElts) {
1782       State.FreeSSERegs -= NumElts;
1783 
1784       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1785       // does.
1786       if (IsVectorCall)
1787         return getDirectX86Hva();
1788 
1789       if (Ty->isBuiltinType() || Ty->isVectorType())
1790         return ABIArgInfo::getDirect();
1791       return ABIArgInfo::getExpand();
1792     }
1793     return getIndirectResult(Ty, /*ByVal=*/false, State);
1794   }
1795 
1796   if (isAggregateTypeForABI(Ty)) {
1797     // Structures with flexible arrays are always indirect.
1798     // FIXME: This should not be byval!
1799     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1800       return getIndirectResult(Ty, true, State);
1801 
1802     // Ignore empty structs/unions on non-Windows.
1803     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1804       return ABIArgInfo::getIgnore();
1805 
1806     llvm::LLVMContext &LLVMContext = getVMContext();
1807     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1808     bool NeedsPadding = false;
1809     bool InReg;
1810     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1811       unsigned SizeInRegs = (TI.Width + 31) / 32;
1812       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1813       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1814       if (InReg)
1815         return ABIArgInfo::getDirectInReg(Result);
1816       else
1817         return ABIArgInfo::getDirect(Result);
1818     }
1819     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1820 
1821     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1822     // added in MSVC 2015.
1823     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1824       return getIndirectResult(Ty, /*ByVal=*/false, State);
1825 
1826     // Expand small (<= 128-bit) record types when we know that the stack layout
1827     // of those arguments will match the struct. This is important because the
1828     // LLVM backend isn't smart enough to remove byval, which inhibits many
1829     // optimizations.
1830     // Don't do this for the MCU if there are still free integer registers
1831     // (see X86_64 ABI for full explanation).
1832     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1833         canExpandIndirectArgument(Ty))
1834       return ABIArgInfo::getExpandWithPadding(
1835           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1836 
1837     return getIndirectResult(Ty, true, State);
1838   }
1839 
1840   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1841     // On Windows, vectors are passed directly if registers are available, or
1842     // indirectly if not. This avoids the need to align argument memory. Pass
1843     // user-defined vector types larger than 512 bits indirectly for simplicity.
1844     if (IsWin32StructABI) {
1845       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1846         --State.FreeSSERegs;
1847         return ABIArgInfo::getDirectInReg();
1848       }
1849       return getIndirectResult(Ty, /*ByVal=*/false, State);
1850     }
1851 
1852     // On Darwin, some vectors are passed in memory, we handle this by passing
1853     // it as an i8/i16/i32/i64.
1854     if (IsDarwinVectorABI) {
1855       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1856           (TI.Width == 64 && VT->getNumElements() == 1))
1857         return ABIArgInfo::getDirect(
1858             llvm::IntegerType::get(getVMContext(), TI.Width));
1859     }
1860 
1861     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1862       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1863 
1864     return ABIArgInfo::getDirect();
1865   }
1866 
1867 
1868   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1869     Ty = EnumTy->getDecl()->getIntegerType();
1870 
1871   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1872 
1873   if (isPromotableIntegerTypeForABI(Ty)) {
1874     if (InReg)
1875       return ABIArgInfo::getExtendInReg(Ty);
1876     return ABIArgInfo::getExtend(Ty);
1877   }
1878 
1879   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1880     if (EIT->getNumBits() <= 64) {
1881       if (InReg)
1882         return ABIArgInfo::getDirectInReg();
1883       return ABIArgInfo::getDirect();
1884     }
1885     return getIndirectResult(Ty, /*ByVal=*/false, State);
1886   }
1887 
1888   if (InReg)
1889     return ABIArgInfo::getDirectInReg();
1890   return ABIArgInfo::getDirect();
1891 }
1892 
1893 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1894   CCState State(FI);
1895   if (IsMCUABI)
1896     State.FreeRegs = 3;
1897   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1898     State.FreeRegs = 2;
1899     State.FreeSSERegs = 3;
1900   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1901     State.FreeRegs = 2;
1902     State.FreeSSERegs = 6;
1903   } else if (FI.getHasRegParm())
1904     State.FreeRegs = FI.getRegParm();
1905   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1906     State.FreeRegs = 5;
1907     State.FreeSSERegs = 8;
1908   } else if (IsWin32StructABI) {
1909     // Since MSVC 2015, the first three SSE vectors have been passed in
1910     // registers. The rest are passed indirectly.
1911     State.FreeRegs = DefaultNumRegisterParameters;
1912     State.FreeSSERegs = 3;
1913   } else
1914     State.FreeRegs = DefaultNumRegisterParameters;
1915 
1916   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1917     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1918   } else if (FI.getReturnInfo().isIndirect()) {
1919     // The C++ ABI is not aware of register usage, so we have to check if the
1920     // return value was sret and put it in a register ourselves if appropriate.
1921     if (State.FreeRegs) {
1922       --State.FreeRegs;  // The sret parameter consumes a register.
1923       if (!IsMCUABI)
1924         FI.getReturnInfo().setInReg(true);
1925     }
1926   }
1927 
1928   // The chain argument effectively gives us another free register.
1929   if (FI.isChainCall())
1930     ++State.FreeRegs;
1931 
1932   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1933   // arguments to XMM registers as available.
1934   if (State.CC == llvm::CallingConv::X86_VectorCall)
1935     runVectorCallFirstPass(FI, State);
1936 
1937   bool UsedInAlloca = false;
1938   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1939   for (int I = 0, E = Args.size(); I < E; ++I) {
1940     // Skip arguments that have already been assigned.
1941     if (State.IsPreassigned.test(I))
1942       continue;
1943 
1944     Args[I].info = classifyArgumentType(Args[I].type, State);
1945     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1946   }
1947 
1948   // If we needed to use inalloca for any argument, do a second pass and rewrite
1949   // all the memory arguments to use inalloca.
1950   if (UsedInAlloca)
1951     rewriteWithInAlloca(FI);
1952 }
1953 
1954 void
1955 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1956                                    CharUnits &StackOffset, ABIArgInfo &Info,
1957                                    QualType Type) const {
1958   // Arguments are always 4-byte-aligned.
1959   CharUnits WordSize = CharUnits::fromQuantity(4);
1960   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1961 
1962   // sret pointers and indirect things will require an extra pointer
1963   // indirection, unless they are byval. Most things are byval, and will not
1964   // require this indirection.
1965   bool IsIndirect = false;
1966   if (Info.isIndirect() && !Info.getIndirectByVal())
1967     IsIndirect = true;
1968   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1969   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1970   if (IsIndirect)
1971     LLTy = LLTy->getPointerTo(0);
1972   FrameFields.push_back(LLTy);
1973   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1974 
1975   // Insert padding bytes to respect alignment.
1976   CharUnits FieldEnd = StackOffset;
1977   StackOffset = FieldEnd.alignTo(WordSize);
1978   if (StackOffset != FieldEnd) {
1979     CharUnits NumBytes = StackOffset - FieldEnd;
1980     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1981     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1982     FrameFields.push_back(Ty);
1983   }
1984 }
1985 
1986 static bool isArgInAlloca(const ABIArgInfo &Info) {
1987   // Leave ignored and inreg arguments alone.
1988   switch (Info.getKind()) {
1989   case ABIArgInfo::InAlloca:
1990     return true;
1991   case ABIArgInfo::Ignore:
1992   case ABIArgInfo::IndirectAliased:
1993     return false;
1994   case ABIArgInfo::Indirect:
1995   case ABIArgInfo::Direct:
1996   case ABIArgInfo::Extend:
1997     return !Info.getInReg();
1998   case ABIArgInfo::Expand:
1999   case ABIArgInfo::CoerceAndExpand:
2000     // These are aggregate types which are never passed in registers when
2001     // inalloca is involved.
2002     return true;
2003   }
2004   llvm_unreachable("invalid enum");
2005 }
2006 
2007 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2008   assert(IsWin32StructABI && "inalloca only supported on win32");
2009 
2010   // Build a packed struct type for all of the arguments in memory.
2011   SmallVector<llvm::Type *, 6> FrameFields;
2012 
2013   // The stack alignment is always 4.
2014   CharUnits StackAlign = CharUnits::fromQuantity(4);
2015 
2016   CharUnits StackOffset;
2017   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2018 
2019   // Put 'this' into the struct before 'sret', if necessary.
2020   bool IsThisCall =
2021       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2022   ABIArgInfo &Ret = FI.getReturnInfo();
2023   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2024       isArgInAlloca(I->info)) {
2025     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2026     ++I;
2027   }
2028 
2029   // Put the sret parameter into the inalloca struct if it's in memory.
2030   if (Ret.isIndirect() && !Ret.getInReg()) {
2031     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2032     // On Windows, the hidden sret parameter is always returned in eax.
2033     Ret.setInAllocaSRet(IsWin32StructABI);
2034   }
2035 
2036   // Skip the 'this' parameter in ecx.
2037   if (IsThisCall)
2038     ++I;
2039 
2040   // Put arguments passed in memory into the struct.
2041   for (; I != E; ++I) {
2042     if (isArgInAlloca(I->info))
2043       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2044   }
2045 
2046   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2047                                         /*isPacked=*/true),
2048                   StackAlign);
2049 }
2050 
2051 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2052                                  Address VAListAddr, QualType Ty) const {
2053 
2054   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2055 
2056   // x86-32 changes the alignment of certain arguments on the stack.
2057   //
2058   // Just messing with TypeInfo like this works because we never pass
2059   // anything indirectly.
2060   TypeInfo.Align = CharUnits::fromQuantity(
2061                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2062 
2063   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2064                           TypeInfo, CharUnits::fromQuantity(4),
2065                           /*AllowHigherAlign*/ true);
2066 }
2067 
2068 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2069     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2070   assert(Triple.getArch() == llvm::Triple::x86);
2071 
2072   switch (Opts.getStructReturnConvention()) {
2073   case CodeGenOptions::SRCK_Default:
2074     break;
2075   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2076     return false;
2077   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2078     return true;
2079   }
2080 
2081   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2082     return true;
2083 
2084   switch (Triple.getOS()) {
2085   case llvm::Triple::DragonFly:
2086   case llvm::Triple::FreeBSD:
2087   case llvm::Triple::OpenBSD:
2088   case llvm::Triple::Win32:
2089     return true;
2090   default:
2091     return false;
2092   }
2093 }
2094 
2095 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2096                                  CodeGen::CodeGenModule &CGM) {
2097   if (!FD->hasAttr<AnyX86InterruptAttr>())
2098     return;
2099 
2100   llvm::Function *Fn = cast<llvm::Function>(GV);
2101   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2102   if (FD->getNumParams() == 0)
2103     return;
2104 
2105   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2106   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2107   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2108     Fn->getContext(), ByValTy);
2109   Fn->addParamAttr(0, NewAttr);
2110 }
2111 
2112 void X86_32TargetCodeGenInfo::setTargetAttributes(
2113     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2114   if (GV->isDeclaration())
2115     return;
2116   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2117     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2118       llvm::Function *Fn = cast<llvm::Function>(GV);
2119       Fn->addFnAttr("stackrealign");
2120     }
2121 
2122     addX86InterruptAttrs(FD, GV, CGM);
2123   }
2124 }
2125 
2126 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2127                                                CodeGen::CodeGenFunction &CGF,
2128                                                llvm::Value *Address) const {
2129   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2130 
2131   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2132 
2133   // 0-7 are the eight integer registers;  the order is different
2134   //   on Darwin (for EH), but the range is the same.
2135   // 8 is %eip.
2136   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2137 
2138   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2139     // 12-16 are st(0..4).  Not sure why we stop at 4.
2140     // These have size 16, which is sizeof(long double) on
2141     // platforms with 8-byte alignment for that type.
2142     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2143     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2144 
2145   } else {
2146     // 9 is %eflags, which doesn't get a size on Darwin for some
2147     // reason.
2148     Builder.CreateAlignedStore(
2149         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2150                                CharUnits::One());
2151 
2152     // 11-16 are st(0..5).  Not sure why we stop at 5.
2153     // These have size 12, which is sizeof(long double) on
2154     // platforms with 4-byte alignment for that type.
2155     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2156     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2157   }
2158 
2159   return false;
2160 }
2161 
2162 //===----------------------------------------------------------------------===//
2163 // X86-64 ABI Implementation
2164 //===----------------------------------------------------------------------===//
2165 
2166 
2167 namespace {
2168 /// The AVX ABI level for X86 targets.
2169 enum class X86AVXABILevel {
2170   None,
2171   AVX,
2172   AVX512
2173 };
2174 
2175 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2176 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2177   switch (AVXLevel) {
2178   case X86AVXABILevel::AVX512:
2179     return 512;
2180   case X86AVXABILevel::AVX:
2181     return 256;
2182   case X86AVXABILevel::None:
2183     return 128;
2184   }
2185   llvm_unreachable("Unknown AVXLevel");
2186 }
2187 
2188 /// X86_64ABIInfo - The X86_64 ABI information.
2189 class X86_64ABIInfo : public SwiftABIInfo {
2190   enum Class {
2191     Integer = 0,
2192     SSE,
2193     SSEUp,
2194     X87,
2195     X87Up,
2196     ComplexX87,
2197     NoClass,
2198     Memory
2199   };
2200 
2201   /// merge - Implement the X86_64 ABI merging algorithm.
2202   ///
2203   /// Merge an accumulating classification \arg Accum with a field
2204   /// classification \arg Field.
2205   ///
2206   /// \param Accum - The accumulating classification. This should
2207   /// always be either NoClass or the result of a previous merge
2208   /// call. In addition, this should never be Memory (the caller
2209   /// should just return Memory for the aggregate).
2210   static Class merge(Class Accum, Class Field);
2211 
2212   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2213   ///
2214   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2215   /// final MEMORY or SSE classes when necessary.
2216   ///
2217   /// \param AggregateSize - The size of the current aggregate in
2218   /// the classification process.
2219   ///
2220   /// \param Lo - The classification for the parts of the type
2221   /// residing in the low word of the containing object.
2222   ///
2223   /// \param Hi - The classification for the parts of the type
2224   /// residing in the higher words of the containing object.
2225   ///
2226   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2227 
2228   /// classify - Determine the x86_64 register classes in which the
2229   /// given type T should be passed.
2230   ///
2231   /// \param Lo - The classification for the parts of the type
2232   /// residing in the low word of the containing object.
2233   ///
2234   /// \param Hi - The classification for the parts of the type
2235   /// residing in the high word of the containing object.
2236   ///
2237   /// \param OffsetBase - The bit offset of this type in the
2238   /// containing object.  Some parameters are classified different
2239   /// depending on whether they straddle an eightbyte boundary.
2240   ///
2241   /// \param isNamedArg - Whether the argument in question is a "named"
2242   /// argument, as used in AMD64-ABI 3.5.7.
2243   ///
2244   /// If a word is unused its result will be NoClass; if a type should
2245   /// be passed in Memory then at least the classification of \arg Lo
2246   /// will be Memory.
2247   ///
2248   /// The \arg Lo class will be NoClass iff the argument is ignored.
2249   ///
2250   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2251   /// also be ComplexX87.
2252   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2253                 bool isNamedArg) const;
2254 
2255   llvm::Type *GetByteVectorType(QualType Ty) const;
2256   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2257                                  unsigned IROffset, QualType SourceTy,
2258                                  unsigned SourceOffset) const;
2259   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2260                                      unsigned IROffset, QualType SourceTy,
2261                                      unsigned SourceOffset) const;
2262 
2263   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2264   /// such that the argument will be returned in memory.
2265   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2266 
2267   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2268   /// such that the argument will be passed in memory.
2269   ///
2270   /// \param freeIntRegs - The number of free integer registers remaining
2271   /// available.
2272   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2273 
2274   ABIArgInfo classifyReturnType(QualType RetTy) const;
2275 
2276   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2277                                   unsigned &neededInt, unsigned &neededSSE,
2278                                   bool isNamedArg) const;
2279 
2280   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2281                                        unsigned &NeededSSE) const;
2282 
2283   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2284                                            unsigned &NeededSSE) const;
2285 
2286   bool IsIllegalVectorType(QualType Ty) const;
2287 
2288   /// The 0.98 ABI revision clarified a lot of ambiguities,
2289   /// unfortunately in ways that were not always consistent with
2290   /// certain previous compilers.  In particular, platforms which
2291   /// required strict binary compatibility with older versions of GCC
2292   /// may need to exempt themselves.
2293   bool honorsRevision0_98() const {
2294     return !getTarget().getTriple().isOSDarwin();
2295   }
2296 
2297   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2298   /// classify it as INTEGER (for compatibility with older clang compilers).
2299   bool classifyIntegerMMXAsSSE() const {
2300     // Clang <= 3.8 did not do this.
2301     if (getContext().getLangOpts().getClangABICompat() <=
2302         LangOptions::ClangABI::Ver3_8)
2303       return false;
2304 
2305     const llvm::Triple &Triple = getTarget().getTriple();
2306     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2307       return false;
2308     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2309       return false;
2310     return true;
2311   }
2312 
2313   // GCC classifies vectors of __int128 as memory.
2314   bool passInt128VectorsInMem() const {
2315     // Clang <= 9.0 did not do this.
2316     if (getContext().getLangOpts().getClangABICompat() <=
2317         LangOptions::ClangABI::Ver9)
2318       return false;
2319 
2320     const llvm::Triple &T = getTarget().getTriple();
2321     return T.isOSLinux() || T.isOSNetBSD();
2322   }
2323 
2324   X86AVXABILevel AVXLevel;
2325   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2326   // 64-bit hardware.
2327   bool Has64BitPointers;
2328 
2329 public:
2330   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2331       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2332       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2333   }
2334 
2335   bool isPassedUsingAVXType(QualType type) const {
2336     unsigned neededInt, neededSSE;
2337     // The freeIntRegs argument doesn't matter here.
2338     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2339                                            /*isNamedArg*/true);
2340     if (info.isDirect()) {
2341       llvm::Type *ty = info.getCoerceToType();
2342       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2343         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2344     }
2345     return false;
2346   }
2347 
2348   void computeInfo(CGFunctionInfo &FI) const override;
2349 
2350   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2351                     QualType Ty) const override;
2352   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2353                       QualType Ty) const override;
2354 
2355   bool has64BitPointers() const {
2356     return Has64BitPointers;
2357   }
2358 
2359   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2360                                     bool asReturnValue) const override {
2361     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2362   }
2363   bool isSwiftErrorInRegister() const override {
2364     return true;
2365   }
2366 };
2367 
2368 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2369 class WinX86_64ABIInfo : public SwiftABIInfo {
2370 public:
2371   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2372       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2373         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2374 
2375   void computeInfo(CGFunctionInfo &FI) const override;
2376 
2377   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2378                     QualType Ty) const override;
2379 
2380   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2381     // FIXME: Assumes vectorcall is in use.
2382     return isX86VectorTypeForVectorCall(getContext(), Ty);
2383   }
2384 
2385   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2386                                          uint64_t NumMembers) const override {
2387     // FIXME: Assumes vectorcall is in use.
2388     return isX86VectorCallAggregateSmallEnough(NumMembers);
2389   }
2390 
2391   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2392                                     bool asReturnValue) const override {
2393     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2394   }
2395 
2396   bool isSwiftErrorInRegister() const override {
2397     return true;
2398   }
2399 
2400 private:
2401   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2402                       bool IsVectorCall, bool IsRegCall) const;
2403   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2404                                            const ABIArgInfo &current) const;
2405 
2406   X86AVXABILevel AVXLevel;
2407 
2408   bool IsMingw64;
2409 };
2410 
2411 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2412 public:
2413   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2414       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2415 
2416   const X86_64ABIInfo &getABIInfo() const {
2417     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2418   }
2419 
2420   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2421   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2422   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2423 
2424   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2425     return 7;
2426   }
2427 
2428   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2429                                llvm::Value *Address) const override {
2430     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2431 
2432     // 0-15 are the 16 integer registers.
2433     // 16 is %rip.
2434     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2435     return false;
2436   }
2437 
2438   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2439                                   StringRef Constraint,
2440                                   llvm::Type* Ty) const override {
2441     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2442   }
2443 
2444   bool isNoProtoCallVariadic(const CallArgList &args,
2445                              const FunctionNoProtoType *fnType) const override {
2446     // The default CC on x86-64 sets %al to the number of SSA
2447     // registers used, and GCC sets this when calling an unprototyped
2448     // function, so we override the default behavior.  However, don't do
2449     // that when AVX types are involved: the ABI explicitly states it is
2450     // undefined, and it doesn't work in practice because of how the ABI
2451     // defines varargs anyway.
2452     if (fnType->getCallConv() == CC_C) {
2453       bool HasAVXType = false;
2454       for (CallArgList::const_iterator
2455              it = args.begin(), ie = args.end(); it != ie; ++it) {
2456         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2457           HasAVXType = true;
2458           break;
2459         }
2460       }
2461 
2462       if (!HasAVXType)
2463         return true;
2464     }
2465 
2466     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2467   }
2468 
2469   llvm::Constant *
2470   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2471     unsigned Sig = (0xeb << 0) | // jmp rel8
2472                    (0x06 << 8) | //           .+0x08
2473                    ('v' << 16) |
2474                    ('2' << 24);
2475     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2476   }
2477 
2478   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2479                            CodeGen::CodeGenModule &CGM) const override {
2480     if (GV->isDeclaration())
2481       return;
2482     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2483       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2484         llvm::Function *Fn = cast<llvm::Function>(GV);
2485         Fn->addFnAttr("stackrealign");
2486       }
2487 
2488       addX86InterruptAttrs(FD, GV, CGM);
2489     }
2490   }
2491 
2492   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2493                             const FunctionDecl *Caller,
2494                             const FunctionDecl *Callee,
2495                             const CallArgList &Args) const override;
2496 };
2497 
2498 static void initFeatureMaps(const ASTContext &Ctx,
2499                             llvm::StringMap<bool> &CallerMap,
2500                             const FunctionDecl *Caller,
2501                             llvm::StringMap<bool> &CalleeMap,
2502                             const FunctionDecl *Callee) {
2503   if (CalleeMap.empty() && CallerMap.empty()) {
2504     // The caller is potentially nullptr in the case where the call isn't in a
2505     // function.  In this case, the getFunctionFeatureMap ensures we just get
2506     // the TU level setting (since it cannot be modified by 'target'..
2507     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2508     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2509   }
2510 }
2511 
2512 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2513                                  SourceLocation CallLoc,
2514                                  const llvm::StringMap<bool> &CallerMap,
2515                                  const llvm::StringMap<bool> &CalleeMap,
2516                                  QualType Ty, StringRef Feature,
2517                                  bool IsArgument) {
2518   bool CallerHasFeat = CallerMap.lookup(Feature);
2519   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2520   if (!CallerHasFeat && !CalleeHasFeat)
2521     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2522            << IsArgument << Ty << Feature;
2523 
2524   // Mixing calling conventions here is very clearly an error.
2525   if (!CallerHasFeat || !CalleeHasFeat)
2526     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2527            << IsArgument << Ty << Feature;
2528 
2529   // Else, both caller and callee have the required feature, so there is no need
2530   // to diagnose.
2531   return false;
2532 }
2533 
2534 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2535                           SourceLocation CallLoc,
2536                           const llvm::StringMap<bool> &CallerMap,
2537                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2538                           bool IsArgument) {
2539   uint64_t Size = Ctx.getTypeSize(Ty);
2540   if (Size > 256)
2541     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2542                                 "avx512f", IsArgument);
2543 
2544   if (Size > 128)
2545     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2546                                 IsArgument);
2547 
2548   return false;
2549 }
2550 
2551 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2552     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2553     const FunctionDecl *Callee, const CallArgList &Args) const {
2554   llvm::StringMap<bool> CallerMap;
2555   llvm::StringMap<bool> CalleeMap;
2556   unsigned ArgIndex = 0;
2557 
2558   // We need to loop through the actual call arguments rather than the the
2559   // function's parameters, in case this variadic.
2560   for (const CallArg &Arg : Args) {
2561     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2562     // additionally changes how vectors >256 in size are passed. Like GCC, we
2563     // warn when a function is called with an argument where this will change.
2564     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2565     // the caller and callee features are mismatched.
2566     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2567     // change its ABI with attribute-target after this call.
2568     if (Arg.getType()->isVectorType() &&
2569         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2570       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2571       QualType Ty = Arg.getType();
2572       // The CallArg seems to have desugared the type already, so for clearer
2573       // diagnostics, replace it with the type in the FunctionDecl if possible.
2574       if (ArgIndex < Callee->getNumParams())
2575         Ty = Callee->getParamDecl(ArgIndex)->getType();
2576 
2577       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2578                         CalleeMap, Ty, /*IsArgument*/ true))
2579         return;
2580     }
2581     ++ArgIndex;
2582   }
2583 
2584   // Check return always, as we don't have a good way of knowing in codegen
2585   // whether this value is used, tail-called, etc.
2586   if (Callee->getReturnType()->isVectorType() &&
2587       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2588     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2589     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2590                   CalleeMap, Callee->getReturnType(),
2591                   /*IsArgument*/ false);
2592   }
2593 }
2594 
2595 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2596   // If the argument does not end in .lib, automatically add the suffix.
2597   // If the argument contains a space, enclose it in quotes.
2598   // This matches the behavior of MSVC.
2599   bool Quote = (Lib.find(' ') != StringRef::npos);
2600   std::string ArgStr = Quote ? "\"" : "";
2601   ArgStr += Lib;
2602   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2603     ArgStr += ".lib";
2604   ArgStr += Quote ? "\"" : "";
2605   return ArgStr;
2606 }
2607 
2608 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2609 public:
2610   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2611         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2612         unsigned NumRegisterParameters)
2613     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2614         Win32StructABI, NumRegisterParameters, false) {}
2615 
2616   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2617                            CodeGen::CodeGenModule &CGM) const override;
2618 
2619   void getDependentLibraryOption(llvm::StringRef Lib,
2620                                  llvm::SmallString<24> &Opt) const override {
2621     Opt = "/DEFAULTLIB:";
2622     Opt += qualifyWindowsLibrary(Lib);
2623   }
2624 
2625   void getDetectMismatchOption(llvm::StringRef Name,
2626                                llvm::StringRef Value,
2627                                llvm::SmallString<32> &Opt) const override {
2628     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2629   }
2630 };
2631 
2632 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2633                                           CodeGen::CodeGenModule &CGM) {
2634   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2635 
2636     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2637       Fn->addFnAttr("stack-probe-size",
2638                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2639     if (CGM.getCodeGenOpts().NoStackArgProbe)
2640       Fn->addFnAttr("no-stack-arg-probe");
2641   }
2642 }
2643 
2644 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2645     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2646   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2647   if (GV->isDeclaration())
2648     return;
2649   addStackProbeTargetAttributes(D, GV, CGM);
2650 }
2651 
2652 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2653 public:
2654   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2655                              X86AVXABILevel AVXLevel)
2656       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2657 
2658   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2659                            CodeGen::CodeGenModule &CGM) const override;
2660 
2661   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2662     return 7;
2663   }
2664 
2665   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2666                                llvm::Value *Address) const override {
2667     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2668 
2669     // 0-15 are the 16 integer registers.
2670     // 16 is %rip.
2671     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2672     return false;
2673   }
2674 
2675   void getDependentLibraryOption(llvm::StringRef Lib,
2676                                  llvm::SmallString<24> &Opt) const override {
2677     Opt = "/DEFAULTLIB:";
2678     Opt += qualifyWindowsLibrary(Lib);
2679   }
2680 
2681   void getDetectMismatchOption(llvm::StringRef Name,
2682                                llvm::StringRef Value,
2683                                llvm::SmallString<32> &Opt) const override {
2684     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2685   }
2686 };
2687 
2688 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2689     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2690   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2691   if (GV->isDeclaration())
2692     return;
2693   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2694     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2695       llvm::Function *Fn = cast<llvm::Function>(GV);
2696       Fn->addFnAttr("stackrealign");
2697     }
2698 
2699     addX86InterruptAttrs(FD, GV, CGM);
2700   }
2701 
2702   addStackProbeTargetAttributes(D, GV, CGM);
2703 }
2704 }
2705 
2706 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2707                               Class &Hi) const {
2708   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2709   //
2710   // (a) If one of the classes is Memory, the whole argument is passed in
2711   //     memory.
2712   //
2713   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2714   //     memory.
2715   //
2716   // (c) If the size of the aggregate exceeds two eightbytes and the first
2717   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2718   //     argument is passed in memory. NOTE: This is necessary to keep the
2719   //     ABI working for processors that don't support the __m256 type.
2720   //
2721   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2722   //
2723   // Some of these are enforced by the merging logic.  Others can arise
2724   // only with unions; for example:
2725   //   union { _Complex double; unsigned; }
2726   //
2727   // Note that clauses (b) and (c) were added in 0.98.
2728   //
2729   if (Hi == Memory)
2730     Lo = Memory;
2731   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2732     Lo = Memory;
2733   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2734     Lo = Memory;
2735   if (Hi == SSEUp && Lo != SSE)
2736     Hi = SSE;
2737 }
2738 
2739 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2740   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2741   // classified recursively so that always two fields are
2742   // considered. The resulting class is calculated according to
2743   // the classes of the fields in the eightbyte:
2744   //
2745   // (a) If both classes are equal, this is the resulting class.
2746   //
2747   // (b) If one of the classes is NO_CLASS, the resulting class is
2748   // the other class.
2749   //
2750   // (c) If one of the classes is MEMORY, the result is the MEMORY
2751   // class.
2752   //
2753   // (d) If one of the classes is INTEGER, the result is the
2754   // INTEGER.
2755   //
2756   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2757   // MEMORY is used as class.
2758   //
2759   // (f) Otherwise class SSE is used.
2760 
2761   // Accum should never be memory (we should have returned) or
2762   // ComplexX87 (because this cannot be passed in a structure).
2763   assert((Accum != Memory && Accum != ComplexX87) &&
2764          "Invalid accumulated classification during merge.");
2765   if (Accum == Field || Field == NoClass)
2766     return Accum;
2767   if (Field == Memory)
2768     return Memory;
2769   if (Accum == NoClass)
2770     return Field;
2771   if (Accum == Integer || Field == Integer)
2772     return Integer;
2773   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2774       Accum == X87 || Accum == X87Up)
2775     return Memory;
2776   return SSE;
2777 }
2778 
2779 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2780                              Class &Lo, Class &Hi, bool isNamedArg) const {
2781   // FIXME: This code can be simplified by introducing a simple value class for
2782   // Class pairs with appropriate constructor methods for the various
2783   // situations.
2784 
2785   // FIXME: Some of the split computations are wrong; unaligned vectors
2786   // shouldn't be passed in registers for example, so there is no chance they
2787   // can straddle an eightbyte. Verify & simplify.
2788 
2789   Lo = Hi = NoClass;
2790 
2791   Class &Current = OffsetBase < 64 ? Lo : Hi;
2792   Current = Memory;
2793 
2794   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2795     BuiltinType::Kind k = BT->getKind();
2796 
2797     if (k == BuiltinType::Void) {
2798       Current = NoClass;
2799     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2800       Lo = Integer;
2801       Hi = Integer;
2802     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2803       Current = Integer;
2804     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2805       Current = SSE;
2806     } else if (k == BuiltinType::LongDouble) {
2807       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2808       if (LDF == &llvm::APFloat::IEEEquad()) {
2809         Lo = SSE;
2810         Hi = SSEUp;
2811       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2812         Lo = X87;
2813         Hi = X87Up;
2814       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2815         Current = SSE;
2816       } else
2817         llvm_unreachable("unexpected long double representation!");
2818     }
2819     // FIXME: _Decimal32 and _Decimal64 are SSE.
2820     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2821     return;
2822   }
2823 
2824   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2825     // Classify the underlying integer type.
2826     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2827     return;
2828   }
2829 
2830   if (Ty->hasPointerRepresentation()) {
2831     Current = Integer;
2832     return;
2833   }
2834 
2835   if (Ty->isMemberPointerType()) {
2836     if (Ty->isMemberFunctionPointerType()) {
2837       if (Has64BitPointers) {
2838         // If Has64BitPointers, this is an {i64, i64}, so classify both
2839         // Lo and Hi now.
2840         Lo = Hi = Integer;
2841       } else {
2842         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2843         // straddles an eightbyte boundary, Hi should be classified as well.
2844         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2845         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2846         if (EB_FuncPtr != EB_ThisAdj) {
2847           Lo = Hi = Integer;
2848         } else {
2849           Current = Integer;
2850         }
2851       }
2852     } else {
2853       Current = Integer;
2854     }
2855     return;
2856   }
2857 
2858   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2859     uint64_t Size = getContext().getTypeSize(VT);
2860     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2861       // gcc passes the following as integer:
2862       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2863       // 2 bytes - <2 x char>, <1 x short>
2864       // 1 byte  - <1 x char>
2865       Current = Integer;
2866 
2867       // If this type crosses an eightbyte boundary, it should be
2868       // split.
2869       uint64_t EB_Lo = (OffsetBase) / 64;
2870       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2871       if (EB_Lo != EB_Hi)
2872         Hi = Lo;
2873     } else if (Size == 64) {
2874       QualType ElementType = VT->getElementType();
2875 
2876       // gcc passes <1 x double> in memory. :(
2877       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2878         return;
2879 
2880       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2881       // pass them as integer.  For platforms where clang is the de facto
2882       // platform compiler, we must continue to use integer.
2883       if (!classifyIntegerMMXAsSSE() &&
2884           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2885            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2886            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2887            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2888         Current = Integer;
2889       else
2890         Current = SSE;
2891 
2892       // If this type crosses an eightbyte boundary, it should be
2893       // split.
2894       if (OffsetBase && OffsetBase != 64)
2895         Hi = Lo;
2896     } else if (Size == 128 ||
2897                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2898       QualType ElementType = VT->getElementType();
2899 
2900       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2901       if (passInt128VectorsInMem() && Size != 128 &&
2902           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2903            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2904         return;
2905 
2906       // Arguments of 256-bits are split into four eightbyte chunks. The
2907       // least significant one belongs to class SSE and all the others to class
2908       // SSEUP. The original Lo and Hi design considers that types can't be
2909       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2910       // This design isn't correct for 256-bits, but since there're no cases
2911       // where the upper parts would need to be inspected, avoid adding
2912       // complexity and just consider Hi to match the 64-256 part.
2913       //
2914       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2915       // registers if they are "named", i.e. not part of the "..." of a
2916       // variadic function.
2917       //
2918       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2919       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2920       Lo = SSE;
2921       Hi = SSEUp;
2922     }
2923     return;
2924   }
2925 
2926   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2927     QualType ET = getContext().getCanonicalType(CT->getElementType());
2928 
2929     uint64_t Size = getContext().getTypeSize(Ty);
2930     if (ET->isIntegralOrEnumerationType()) {
2931       if (Size <= 64)
2932         Current = Integer;
2933       else if (Size <= 128)
2934         Lo = Hi = Integer;
2935     } else if (ET == getContext().FloatTy) {
2936       Current = SSE;
2937     } else if (ET == getContext().DoubleTy) {
2938       Lo = Hi = SSE;
2939     } else if (ET == getContext().LongDoubleTy) {
2940       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2941       if (LDF == &llvm::APFloat::IEEEquad())
2942         Current = Memory;
2943       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2944         Current = ComplexX87;
2945       else if (LDF == &llvm::APFloat::IEEEdouble())
2946         Lo = Hi = SSE;
2947       else
2948         llvm_unreachable("unexpected long double representation!");
2949     }
2950 
2951     // If this complex type crosses an eightbyte boundary then it
2952     // should be split.
2953     uint64_t EB_Real = (OffsetBase) / 64;
2954     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2955     if (Hi == NoClass && EB_Real != EB_Imag)
2956       Hi = Lo;
2957 
2958     return;
2959   }
2960 
2961   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2962     if (EITy->getNumBits() <= 64)
2963       Current = Integer;
2964     else if (EITy->getNumBits() <= 128)
2965       Lo = Hi = Integer;
2966     // Larger values need to get passed in memory.
2967     return;
2968   }
2969 
2970   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2971     // Arrays are treated like structures.
2972 
2973     uint64_t Size = getContext().getTypeSize(Ty);
2974 
2975     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2976     // than eight eightbytes, ..., it has class MEMORY.
2977     if (Size > 512)
2978       return;
2979 
2980     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2981     // fields, it has class MEMORY.
2982     //
2983     // Only need to check alignment of array base.
2984     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2985       return;
2986 
2987     // Otherwise implement simplified merge. We could be smarter about
2988     // this, but it isn't worth it and would be harder to verify.
2989     Current = NoClass;
2990     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2991     uint64_t ArraySize = AT->getSize().getZExtValue();
2992 
2993     // The only case a 256-bit wide vector could be used is when the array
2994     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2995     // to work for sizes wider than 128, early check and fallback to memory.
2996     //
2997     if (Size > 128 &&
2998         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2999       return;
3000 
3001     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3002       Class FieldLo, FieldHi;
3003       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3004       Lo = merge(Lo, FieldLo);
3005       Hi = merge(Hi, FieldHi);
3006       if (Lo == Memory || Hi == Memory)
3007         break;
3008     }
3009 
3010     postMerge(Size, Lo, Hi);
3011     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3012     return;
3013   }
3014 
3015   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3016     uint64_t Size = getContext().getTypeSize(Ty);
3017 
3018     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3019     // than eight eightbytes, ..., it has class MEMORY.
3020     if (Size > 512)
3021       return;
3022 
3023     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3024     // copy constructor or a non-trivial destructor, it is passed by invisible
3025     // reference.
3026     if (getRecordArgABI(RT, getCXXABI()))
3027       return;
3028 
3029     const RecordDecl *RD = RT->getDecl();
3030 
3031     // Assume variable sized types are passed in memory.
3032     if (RD->hasFlexibleArrayMember())
3033       return;
3034 
3035     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3036 
3037     // Reset Lo class, this will be recomputed.
3038     Current = NoClass;
3039 
3040     // If this is a C++ record, classify the bases first.
3041     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3042       for (const auto &I : CXXRD->bases()) {
3043         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3044                "Unexpected base class!");
3045         const auto *Base =
3046             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3047 
3048         // Classify this field.
3049         //
3050         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3051         // single eightbyte, each is classified separately. Each eightbyte gets
3052         // initialized to class NO_CLASS.
3053         Class FieldLo, FieldHi;
3054         uint64_t Offset =
3055           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3056         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3057         Lo = merge(Lo, FieldLo);
3058         Hi = merge(Hi, FieldHi);
3059         if (Lo == Memory || Hi == Memory) {
3060           postMerge(Size, Lo, Hi);
3061           return;
3062         }
3063       }
3064     }
3065 
3066     // Classify the fields one at a time, merging the results.
3067     unsigned idx = 0;
3068     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3069                                 LangOptions::ClangABI::Ver11 ||
3070                             getContext().getTargetInfo().getTriple().isPS4();
3071     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3072 
3073     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3074            i != e; ++i, ++idx) {
3075       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3076       bool BitField = i->isBitField();
3077 
3078       // Ignore padding bit-fields.
3079       if (BitField && i->isUnnamedBitfield())
3080         continue;
3081 
3082       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3083       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3084       //
3085       // The only case a 256-bit or a 512-bit wide vector could be used is when
3086       // the struct contains a single 256-bit or 512-bit element. Early check
3087       // and fallback to memory.
3088       //
3089       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3090       // than 128.
3091       if (Size > 128 &&
3092           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3093            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3094         Lo = Memory;
3095         postMerge(Size, Lo, Hi);
3096         return;
3097       }
3098       // Note, skip this test for bit-fields, see below.
3099       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3100         Lo = Memory;
3101         postMerge(Size, Lo, Hi);
3102         return;
3103       }
3104 
3105       // Classify this field.
3106       //
3107       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3108       // exceeds a single eightbyte, each is classified
3109       // separately. Each eightbyte gets initialized to class
3110       // NO_CLASS.
3111       Class FieldLo, FieldHi;
3112 
3113       // Bit-fields require special handling, they do not force the
3114       // structure to be passed in memory even if unaligned, and
3115       // therefore they can straddle an eightbyte.
3116       if (BitField) {
3117         assert(!i->isUnnamedBitfield());
3118         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3119         uint64_t Size = i->getBitWidthValue(getContext());
3120 
3121         uint64_t EB_Lo = Offset / 64;
3122         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3123 
3124         if (EB_Lo) {
3125           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3126           FieldLo = NoClass;
3127           FieldHi = Integer;
3128         } else {
3129           FieldLo = Integer;
3130           FieldHi = EB_Hi ? Integer : NoClass;
3131         }
3132       } else
3133         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3134       Lo = merge(Lo, FieldLo);
3135       Hi = merge(Hi, FieldHi);
3136       if (Lo == Memory || Hi == Memory)
3137         break;
3138     }
3139 
3140     postMerge(Size, Lo, Hi);
3141   }
3142 }
3143 
3144 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3145   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3146   // place naturally.
3147   if (!isAggregateTypeForABI(Ty)) {
3148     // Treat an enum type as its underlying type.
3149     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3150       Ty = EnumTy->getDecl()->getIntegerType();
3151 
3152     if (Ty->isExtIntType())
3153       return getNaturalAlignIndirect(Ty);
3154 
3155     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3156                                               : ABIArgInfo::getDirect());
3157   }
3158 
3159   return getNaturalAlignIndirect(Ty);
3160 }
3161 
3162 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3163   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3164     uint64_t Size = getContext().getTypeSize(VecTy);
3165     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3166     if (Size <= 64 || Size > LargestVector)
3167       return true;
3168     QualType EltTy = VecTy->getElementType();
3169     if (passInt128VectorsInMem() &&
3170         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3171          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3172       return true;
3173   }
3174 
3175   return false;
3176 }
3177 
3178 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3179                                             unsigned freeIntRegs) const {
3180   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3181   // place naturally.
3182   //
3183   // This assumption is optimistic, as there could be free registers available
3184   // when we need to pass this argument in memory, and LLVM could try to pass
3185   // the argument in the free register. This does not seem to happen currently,
3186   // but this code would be much safer if we could mark the argument with
3187   // 'onstack'. See PR12193.
3188   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3189       !Ty->isExtIntType()) {
3190     // Treat an enum type as its underlying type.
3191     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3192       Ty = EnumTy->getDecl()->getIntegerType();
3193 
3194     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3195                                               : ABIArgInfo::getDirect());
3196   }
3197 
3198   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3199     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3200 
3201   // Compute the byval alignment. We specify the alignment of the byval in all
3202   // cases so that the mid-level optimizer knows the alignment of the byval.
3203   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3204 
3205   // Attempt to avoid passing indirect results using byval when possible. This
3206   // is important for good codegen.
3207   //
3208   // We do this by coercing the value into a scalar type which the backend can
3209   // handle naturally (i.e., without using byval).
3210   //
3211   // For simplicity, we currently only do this when we have exhausted all of the
3212   // free integer registers. Doing this when there are free integer registers
3213   // would require more care, as we would have to ensure that the coerced value
3214   // did not claim the unused register. That would require either reording the
3215   // arguments to the function (so that any subsequent inreg values came first),
3216   // or only doing this optimization when there were no following arguments that
3217   // might be inreg.
3218   //
3219   // We currently expect it to be rare (particularly in well written code) for
3220   // arguments to be passed on the stack when there are still free integer
3221   // registers available (this would typically imply large structs being passed
3222   // by value), so this seems like a fair tradeoff for now.
3223   //
3224   // We can revisit this if the backend grows support for 'onstack' parameter
3225   // attributes. See PR12193.
3226   if (freeIntRegs == 0) {
3227     uint64_t Size = getContext().getTypeSize(Ty);
3228 
3229     // If this type fits in an eightbyte, coerce it into the matching integral
3230     // type, which will end up on the stack (with alignment 8).
3231     if (Align == 8 && Size <= 64)
3232       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3233                                                           Size));
3234   }
3235 
3236   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3237 }
3238 
3239 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3240 /// register. Pick an LLVM IR type that will be passed as a vector register.
3241 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3242   // Wrapper structs/arrays that only contain vectors are passed just like
3243   // vectors; strip them off if present.
3244   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3245     Ty = QualType(InnerTy, 0);
3246 
3247   llvm::Type *IRType = CGT.ConvertType(Ty);
3248   if (isa<llvm::VectorType>(IRType)) {
3249     // Don't pass vXi128 vectors in their native type, the backend can't
3250     // legalize them.
3251     if (passInt128VectorsInMem() &&
3252         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3253       // Use a vXi64 vector.
3254       uint64_t Size = getContext().getTypeSize(Ty);
3255       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3256                                         Size / 64);
3257     }
3258 
3259     return IRType;
3260   }
3261 
3262   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3263     return IRType;
3264 
3265   // We couldn't find the preferred IR vector type for 'Ty'.
3266   uint64_t Size = getContext().getTypeSize(Ty);
3267   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3268 
3269 
3270   // Return a LLVM IR vector type based on the size of 'Ty'.
3271   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3272                                     Size / 64);
3273 }
3274 
3275 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3276 /// is known to either be off the end of the specified type or being in
3277 /// alignment padding.  The user type specified is known to be at most 128 bits
3278 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3279 /// classification that put one of the two halves in the INTEGER class.
3280 ///
3281 /// It is conservatively correct to return false.
3282 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3283                                   unsigned EndBit, ASTContext &Context) {
3284   // If the bytes being queried are off the end of the type, there is no user
3285   // data hiding here.  This handles analysis of builtins, vectors and other
3286   // types that don't contain interesting padding.
3287   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3288   if (TySize <= StartBit)
3289     return true;
3290 
3291   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3292     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3293     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3294 
3295     // Check each element to see if the element overlaps with the queried range.
3296     for (unsigned i = 0; i != NumElts; ++i) {
3297       // If the element is after the span we care about, then we're done..
3298       unsigned EltOffset = i*EltSize;
3299       if (EltOffset >= EndBit) break;
3300 
3301       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3302       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3303                                  EndBit-EltOffset, Context))
3304         return false;
3305     }
3306     // If it overlaps no elements, then it is safe to process as padding.
3307     return true;
3308   }
3309 
3310   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3311     const RecordDecl *RD = RT->getDecl();
3312     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3313 
3314     // If this is a C++ record, check the bases first.
3315     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3316       for (const auto &I : CXXRD->bases()) {
3317         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3318                "Unexpected base class!");
3319         const auto *Base =
3320             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3321 
3322         // If the base is after the span we care about, ignore it.
3323         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3324         if (BaseOffset >= EndBit) continue;
3325 
3326         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3327         if (!BitsContainNoUserData(I.getType(), BaseStart,
3328                                    EndBit-BaseOffset, Context))
3329           return false;
3330       }
3331     }
3332 
3333     // Verify that no field has data that overlaps the region of interest.  Yes
3334     // this could be sped up a lot by being smarter about queried fields,
3335     // however we're only looking at structs up to 16 bytes, so we don't care
3336     // much.
3337     unsigned idx = 0;
3338     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3339          i != e; ++i, ++idx) {
3340       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3341 
3342       // If we found a field after the region we care about, then we're done.
3343       if (FieldOffset >= EndBit) break;
3344 
3345       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3346       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3347                                  Context))
3348         return false;
3349     }
3350 
3351     // If nothing in this record overlapped the area of interest, then we're
3352     // clean.
3353     return true;
3354   }
3355 
3356   return false;
3357 }
3358 
3359 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3360 /// float member at the specified offset.  For example, {int,{float}} has a
3361 /// float at offset 4.  It is conservatively correct for this routine to return
3362 /// false.
3363 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3364                                   const llvm::DataLayout &TD) {
3365   // Base case if we find a float.
3366   if (IROffset == 0 && IRType->isFloatTy())
3367     return true;
3368 
3369   // If this is a struct, recurse into the field at the specified offset.
3370   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3371     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3372     unsigned Elt = SL->getElementContainingOffset(IROffset);
3373     IROffset -= SL->getElementOffset(Elt);
3374     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3375   }
3376 
3377   // If this is an array, recurse into the field at the specified offset.
3378   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3379     llvm::Type *EltTy = ATy->getElementType();
3380     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3381     IROffset -= IROffset/EltSize*EltSize;
3382     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3383   }
3384 
3385   return false;
3386 }
3387 
3388 
3389 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3390 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3391 llvm::Type *X86_64ABIInfo::
3392 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3393                    QualType SourceTy, unsigned SourceOffset) const {
3394   // The only three choices we have are either double, <2 x float>, or float. We
3395   // pass as float if the last 4 bytes is just padding.  This happens for
3396   // structs that contain 3 floats.
3397   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3398                             SourceOffset*8+64, getContext()))
3399     return llvm::Type::getFloatTy(getVMContext());
3400 
3401   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3402   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3403   // case.
3404   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3405       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3406     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3407                                       2);
3408 
3409   return llvm::Type::getDoubleTy(getVMContext());
3410 }
3411 
3412 
3413 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3414 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3415 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3416 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3417 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3418 /// etc).
3419 ///
3420 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3421 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3422 /// the 8-byte value references.  PrefType may be null.
3423 ///
3424 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3425 /// an offset into this that we're processing (which is always either 0 or 8).
3426 ///
3427 llvm::Type *X86_64ABIInfo::
3428 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3429                        QualType SourceTy, unsigned SourceOffset) const {
3430   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3431   // returning an 8-byte unit starting with it.  See if we can safely use it.
3432   if (IROffset == 0) {
3433     // Pointers and int64's always fill the 8-byte unit.
3434     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3435         IRType->isIntegerTy(64))
3436       return IRType;
3437 
3438     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3439     // goodness in the source type is just tail padding.  This is allowed to
3440     // kick in for struct {double,int} on the int, but not on
3441     // struct{double,int,int} because we wouldn't return the second int.  We
3442     // have to do this analysis on the source type because we can't depend on
3443     // unions being lowered a specific way etc.
3444     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3445         IRType->isIntegerTy(32) ||
3446         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3447       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3448           cast<llvm::IntegerType>(IRType)->getBitWidth();
3449 
3450       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3451                                 SourceOffset*8+64, getContext()))
3452         return IRType;
3453     }
3454   }
3455 
3456   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3457     // If this is a struct, recurse into the field at the specified offset.
3458     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3459     if (IROffset < SL->getSizeInBytes()) {
3460       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3461       IROffset -= SL->getElementOffset(FieldIdx);
3462 
3463       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3464                                     SourceTy, SourceOffset);
3465     }
3466   }
3467 
3468   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3469     llvm::Type *EltTy = ATy->getElementType();
3470     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3471     unsigned EltOffset = IROffset/EltSize*EltSize;
3472     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3473                                   SourceOffset);
3474   }
3475 
3476   // Okay, we don't have any better idea of what to pass, so we pass this in an
3477   // integer register that isn't too big to fit the rest of the struct.
3478   unsigned TySizeInBytes =
3479     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3480 
3481   assert(TySizeInBytes != SourceOffset && "Empty field?");
3482 
3483   // It is always safe to classify this as an integer type up to i64 that
3484   // isn't larger than the structure.
3485   return llvm::IntegerType::get(getVMContext(),
3486                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3487 }
3488 
3489 
3490 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3491 /// be used as elements of a two register pair to pass or return, return a
3492 /// first class aggregate to represent them.  For example, if the low part of
3493 /// a by-value argument should be passed as i32* and the high part as float,
3494 /// return {i32*, float}.
3495 static llvm::Type *
3496 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3497                            const llvm::DataLayout &TD) {
3498   // In order to correctly satisfy the ABI, we need to the high part to start
3499   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3500   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3501   // the second element at offset 8.  Check for this:
3502   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3503   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3504   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3505   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3506 
3507   // To handle this, we have to increase the size of the low part so that the
3508   // second element will start at an 8 byte offset.  We can't increase the size
3509   // of the second element because it might make us access off the end of the
3510   // struct.
3511   if (HiStart != 8) {
3512     // There are usually two sorts of types the ABI generation code can produce
3513     // for the low part of a pair that aren't 8 bytes in size: float or
3514     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3515     // NaCl).
3516     // Promote these to a larger type.
3517     if (Lo->isFloatTy())
3518       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3519     else {
3520       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3521              && "Invalid/unknown lo type");
3522       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3523     }
3524   }
3525 
3526   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3527 
3528   // Verify that the second element is at an 8-byte offset.
3529   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3530          "Invalid x86-64 argument pair!");
3531   return Result;
3532 }
3533 
3534 ABIArgInfo X86_64ABIInfo::
3535 classifyReturnType(QualType RetTy) const {
3536   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3537   // classification algorithm.
3538   X86_64ABIInfo::Class Lo, Hi;
3539   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3540 
3541   // Check some invariants.
3542   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3543   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3544 
3545   llvm::Type *ResType = nullptr;
3546   switch (Lo) {
3547   case NoClass:
3548     if (Hi == NoClass)
3549       return ABIArgInfo::getIgnore();
3550     // If the low part is just padding, it takes no register, leave ResType
3551     // null.
3552     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3553            "Unknown missing lo part");
3554     break;
3555 
3556   case SSEUp:
3557   case X87Up:
3558     llvm_unreachable("Invalid classification for lo word.");
3559 
3560     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3561     // hidden argument.
3562   case Memory:
3563     return getIndirectReturnResult(RetTy);
3564 
3565     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3566     // available register of the sequence %rax, %rdx is used.
3567   case Integer:
3568     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3569 
3570     // If we have a sign or zero extended integer, make sure to return Extend
3571     // so that the parameter gets the right LLVM IR attributes.
3572     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3573       // Treat an enum type as its underlying type.
3574       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3575         RetTy = EnumTy->getDecl()->getIntegerType();
3576 
3577       if (RetTy->isIntegralOrEnumerationType() &&
3578           isPromotableIntegerTypeForABI(RetTy))
3579         return ABIArgInfo::getExtend(RetTy);
3580     }
3581     break;
3582 
3583     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3584     // available SSE register of the sequence %xmm0, %xmm1 is used.
3585   case SSE:
3586     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3587     break;
3588 
3589     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3590     // returned on the X87 stack in %st0 as 80-bit x87 number.
3591   case X87:
3592     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3593     break;
3594 
3595     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3596     // part of the value is returned in %st0 and the imaginary part in
3597     // %st1.
3598   case ComplexX87:
3599     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3600     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3601                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3602     break;
3603   }
3604 
3605   llvm::Type *HighPart = nullptr;
3606   switch (Hi) {
3607     // Memory was handled previously and X87 should
3608     // never occur as a hi class.
3609   case Memory:
3610   case X87:
3611     llvm_unreachable("Invalid classification for hi word.");
3612 
3613   case ComplexX87: // Previously handled.
3614   case NoClass:
3615     break;
3616 
3617   case Integer:
3618     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3619     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3620       return ABIArgInfo::getDirect(HighPart, 8);
3621     break;
3622   case SSE:
3623     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3624     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3625       return ABIArgInfo::getDirect(HighPart, 8);
3626     break;
3627 
3628     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3629     // is passed in the next available eightbyte chunk if the last used
3630     // vector register.
3631     //
3632     // SSEUP should always be preceded by SSE, just widen.
3633   case SSEUp:
3634     assert(Lo == SSE && "Unexpected SSEUp classification.");
3635     ResType = GetByteVectorType(RetTy);
3636     break;
3637 
3638     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3639     // returned together with the previous X87 value in %st0.
3640   case X87Up:
3641     // If X87Up is preceded by X87, we don't need to do
3642     // anything. However, in some cases with unions it may not be
3643     // preceded by X87. In such situations we follow gcc and pass the
3644     // extra bits in an SSE reg.
3645     if (Lo != X87) {
3646       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3647       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3648         return ABIArgInfo::getDirect(HighPart, 8);
3649     }
3650     break;
3651   }
3652 
3653   // If a high part was specified, merge it together with the low part.  It is
3654   // known to pass in the high eightbyte of the result.  We do this by forming a
3655   // first class struct aggregate with the high and low part: {low, high}
3656   if (HighPart)
3657     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3658 
3659   return ABIArgInfo::getDirect(ResType);
3660 }
3661 
3662 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3663   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3664   bool isNamedArg)
3665   const
3666 {
3667   Ty = useFirstFieldIfTransparentUnion(Ty);
3668 
3669   X86_64ABIInfo::Class Lo, Hi;
3670   classify(Ty, 0, Lo, Hi, isNamedArg);
3671 
3672   // Check some invariants.
3673   // FIXME: Enforce these by construction.
3674   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3675   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3676 
3677   neededInt = 0;
3678   neededSSE = 0;
3679   llvm::Type *ResType = nullptr;
3680   switch (Lo) {
3681   case NoClass:
3682     if (Hi == NoClass)
3683       return ABIArgInfo::getIgnore();
3684     // If the low part is just padding, it takes no register, leave ResType
3685     // null.
3686     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3687            "Unknown missing lo part");
3688     break;
3689 
3690     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3691     // on the stack.
3692   case Memory:
3693 
3694     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3695     // COMPLEX_X87, it is passed in memory.
3696   case X87:
3697   case ComplexX87:
3698     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3699       ++neededInt;
3700     return getIndirectResult(Ty, freeIntRegs);
3701 
3702   case SSEUp:
3703   case X87Up:
3704     llvm_unreachable("Invalid classification for lo word.");
3705 
3706     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3707     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3708     // and %r9 is used.
3709   case Integer:
3710     ++neededInt;
3711 
3712     // Pick an 8-byte type based on the preferred type.
3713     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3714 
3715     // If we have a sign or zero extended integer, make sure to return Extend
3716     // so that the parameter gets the right LLVM IR attributes.
3717     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3718       // Treat an enum type as its underlying type.
3719       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3720         Ty = EnumTy->getDecl()->getIntegerType();
3721 
3722       if (Ty->isIntegralOrEnumerationType() &&
3723           isPromotableIntegerTypeForABI(Ty))
3724         return ABIArgInfo::getExtend(Ty);
3725     }
3726 
3727     break;
3728 
3729     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3730     // available SSE register is used, the registers are taken in the
3731     // order from %xmm0 to %xmm7.
3732   case SSE: {
3733     llvm::Type *IRType = CGT.ConvertType(Ty);
3734     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3735     ++neededSSE;
3736     break;
3737   }
3738   }
3739 
3740   llvm::Type *HighPart = nullptr;
3741   switch (Hi) {
3742     // Memory was handled previously, ComplexX87 and X87 should
3743     // never occur as hi classes, and X87Up must be preceded by X87,
3744     // which is passed in memory.
3745   case Memory:
3746   case X87:
3747   case ComplexX87:
3748     llvm_unreachable("Invalid classification for hi word.");
3749 
3750   case NoClass: break;
3751 
3752   case Integer:
3753     ++neededInt;
3754     // Pick an 8-byte type based on the preferred type.
3755     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3756 
3757     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3758       return ABIArgInfo::getDirect(HighPart, 8);
3759     break;
3760 
3761     // X87Up generally doesn't occur here (long double is passed in
3762     // memory), except in situations involving unions.
3763   case X87Up:
3764   case SSE:
3765     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3766 
3767     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3768       return ABIArgInfo::getDirect(HighPart, 8);
3769 
3770     ++neededSSE;
3771     break;
3772 
3773     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3774     // eightbyte is passed in the upper half of the last used SSE
3775     // register.  This only happens when 128-bit vectors are passed.
3776   case SSEUp:
3777     assert(Lo == SSE && "Unexpected SSEUp classification");
3778     ResType = GetByteVectorType(Ty);
3779     break;
3780   }
3781 
3782   // If a high part was specified, merge it together with the low part.  It is
3783   // known to pass in the high eightbyte of the result.  We do this by forming a
3784   // first class struct aggregate with the high and low part: {low, high}
3785   if (HighPart)
3786     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3787 
3788   return ABIArgInfo::getDirect(ResType);
3789 }
3790 
3791 ABIArgInfo
3792 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3793                                              unsigned &NeededSSE) const {
3794   auto RT = Ty->getAs<RecordType>();
3795   assert(RT && "classifyRegCallStructType only valid with struct types");
3796 
3797   if (RT->getDecl()->hasFlexibleArrayMember())
3798     return getIndirectReturnResult(Ty);
3799 
3800   // Sum up bases
3801   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3802     if (CXXRD->isDynamicClass()) {
3803       NeededInt = NeededSSE = 0;
3804       return getIndirectReturnResult(Ty);
3805     }
3806 
3807     for (const auto &I : CXXRD->bases())
3808       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3809               .isIndirect()) {
3810         NeededInt = NeededSSE = 0;
3811         return getIndirectReturnResult(Ty);
3812       }
3813   }
3814 
3815   // Sum up members
3816   for (const auto *FD : RT->getDecl()->fields()) {
3817     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3818       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3819               .isIndirect()) {
3820         NeededInt = NeededSSE = 0;
3821         return getIndirectReturnResult(Ty);
3822       }
3823     } else {
3824       unsigned LocalNeededInt, LocalNeededSSE;
3825       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3826                                LocalNeededSSE, true)
3827               .isIndirect()) {
3828         NeededInt = NeededSSE = 0;
3829         return getIndirectReturnResult(Ty);
3830       }
3831       NeededInt += LocalNeededInt;
3832       NeededSSE += LocalNeededSSE;
3833     }
3834   }
3835 
3836   return ABIArgInfo::getDirect();
3837 }
3838 
3839 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3840                                                     unsigned &NeededInt,
3841                                                     unsigned &NeededSSE) const {
3842 
3843   NeededInt = 0;
3844   NeededSSE = 0;
3845 
3846   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3847 }
3848 
3849 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3850 
3851   const unsigned CallingConv = FI.getCallingConvention();
3852   // It is possible to force Win64 calling convention on any x86_64 target by
3853   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3854   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3855   if (CallingConv == llvm::CallingConv::Win64) {
3856     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3857     Win64ABIInfo.computeInfo(FI);
3858     return;
3859   }
3860 
3861   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3862 
3863   // Keep track of the number of assigned registers.
3864   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3865   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3866   unsigned NeededInt, NeededSSE;
3867 
3868   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3869     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3870         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3871       FI.getReturnInfo() =
3872           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3873       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3874         FreeIntRegs -= NeededInt;
3875         FreeSSERegs -= NeededSSE;
3876       } else {
3877         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3878       }
3879     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3880                getContext().getCanonicalType(FI.getReturnType()
3881                                                  ->getAs<ComplexType>()
3882                                                  ->getElementType()) ==
3883                    getContext().LongDoubleTy)
3884       // Complex Long Double Type is passed in Memory when Regcall
3885       // calling convention is used.
3886       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3887     else
3888       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3889   }
3890 
3891   // If the return value is indirect, then the hidden argument is consuming one
3892   // integer register.
3893   if (FI.getReturnInfo().isIndirect())
3894     --FreeIntRegs;
3895 
3896   // The chain argument effectively gives us another free register.
3897   if (FI.isChainCall())
3898     ++FreeIntRegs;
3899 
3900   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3901   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3902   // get assigned (in left-to-right order) for passing as follows...
3903   unsigned ArgNo = 0;
3904   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3905        it != ie; ++it, ++ArgNo) {
3906     bool IsNamedArg = ArgNo < NumRequiredArgs;
3907 
3908     if (IsRegCall && it->type->isStructureOrClassType())
3909       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3910     else
3911       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3912                                       NeededSSE, IsNamedArg);
3913 
3914     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3915     // eightbyte of an argument, the whole argument is passed on the
3916     // stack. If registers have already been assigned for some
3917     // eightbytes of such an argument, the assignments get reverted.
3918     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3919       FreeIntRegs -= NeededInt;
3920       FreeSSERegs -= NeededSSE;
3921     } else {
3922       it->info = getIndirectResult(it->type, FreeIntRegs);
3923     }
3924   }
3925 }
3926 
3927 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3928                                          Address VAListAddr, QualType Ty) {
3929   Address overflow_arg_area_p =
3930       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3931   llvm::Value *overflow_arg_area =
3932     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3933 
3934   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3935   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3936   // It isn't stated explicitly in the standard, but in practice we use
3937   // alignment greater than 16 where necessary.
3938   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3939   if (Align > CharUnits::fromQuantity(8)) {
3940     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3941                                                       Align);
3942   }
3943 
3944   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3945   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3946   llvm::Value *Res =
3947     CGF.Builder.CreateBitCast(overflow_arg_area,
3948                               llvm::PointerType::getUnqual(LTy));
3949 
3950   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3951   // l->overflow_arg_area + sizeof(type).
3952   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3953   // an 8 byte boundary.
3954 
3955   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3956   llvm::Value *Offset =
3957       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3958   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3959                                             "overflow_arg_area.next");
3960   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3961 
3962   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3963   return Address(Res, Align);
3964 }
3965 
3966 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3967                                  QualType Ty) const {
3968   // Assume that va_list type is correct; should be pointer to LLVM type:
3969   // struct {
3970   //   i32 gp_offset;
3971   //   i32 fp_offset;
3972   //   i8* overflow_arg_area;
3973   //   i8* reg_save_area;
3974   // };
3975   unsigned neededInt, neededSSE;
3976 
3977   Ty = getContext().getCanonicalType(Ty);
3978   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3979                                        /*isNamedArg*/false);
3980 
3981   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3982   // in the registers. If not go to step 7.
3983   if (!neededInt && !neededSSE)
3984     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3985 
3986   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3987   // general purpose registers needed to pass type and num_fp to hold
3988   // the number of floating point registers needed.
3989 
3990   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3991   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3992   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3993   //
3994   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3995   // register save space).
3996 
3997   llvm::Value *InRegs = nullptr;
3998   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3999   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4000   if (neededInt) {
4001     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4002     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4003     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4004     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4005   }
4006 
4007   if (neededSSE) {
4008     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4009     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4010     llvm::Value *FitsInFP =
4011       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4012     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4013     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4014   }
4015 
4016   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4017   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4018   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4019   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4020 
4021   // Emit code to load the value if it was passed in registers.
4022 
4023   CGF.EmitBlock(InRegBlock);
4024 
4025   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4026   // an offset of l->gp_offset and/or l->fp_offset. This may require
4027   // copying to a temporary location in case the parameter is passed
4028   // in different register classes or requires an alignment greater
4029   // than 8 for general purpose registers and 16 for XMM registers.
4030   //
4031   // FIXME: This really results in shameful code when we end up needing to
4032   // collect arguments from different places; often what should result in a
4033   // simple assembling of a structure from scattered addresses has many more
4034   // loads than necessary. Can we clean this up?
4035   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4036   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4037       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4038 
4039   Address RegAddr = Address::invalid();
4040   if (neededInt && neededSSE) {
4041     // FIXME: Cleanup.
4042     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4043     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4044     Address Tmp = CGF.CreateMemTemp(Ty);
4045     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4046     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4047     llvm::Type *TyLo = ST->getElementType(0);
4048     llvm::Type *TyHi = ST->getElementType(1);
4049     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4050            "Unexpected ABI info for mixed regs");
4051     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4052     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4053     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4054     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4055     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4056     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4057 
4058     // Copy the first element.
4059     // FIXME: Our choice of alignment here and below is probably pessimistic.
4060     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4061         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4062         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4063     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4064 
4065     // Copy the second element.
4066     V = CGF.Builder.CreateAlignedLoad(
4067         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4068         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4069     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4070 
4071     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4072   } else if (neededInt) {
4073     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4074                       CharUnits::fromQuantity(8));
4075     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4076 
4077     // Copy to a temporary if necessary to ensure the appropriate alignment.
4078     auto TInfo = getContext().getTypeInfoInChars(Ty);
4079     uint64_t TySize = TInfo.Width.getQuantity();
4080     CharUnits TyAlign = TInfo.Align;
4081 
4082     // Copy into a temporary if the type is more aligned than the
4083     // register save area.
4084     if (TyAlign.getQuantity() > 8) {
4085       Address Tmp = CGF.CreateMemTemp(Ty);
4086       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4087       RegAddr = Tmp;
4088     }
4089 
4090   } else if (neededSSE == 1) {
4091     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4092                       CharUnits::fromQuantity(16));
4093     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4094   } else {
4095     assert(neededSSE == 2 && "Invalid number of needed registers!");
4096     // SSE registers are spaced 16 bytes apart in the register save
4097     // area, we need to collect the two eightbytes together.
4098     // The ABI isn't explicit about this, but it seems reasonable
4099     // to assume that the slots are 16-byte aligned, since the stack is
4100     // naturally 16-byte aligned and the prologue is expected to store
4101     // all the SSE registers to the RSA.
4102     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4103                                 CharUnits::fromQuantity(16));
4104     Address RegAddrHi =
4105       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4106                                              CharUnits::fromQuantity(16));
4107     llvm::Type *ST = AI.canHaveCoerceToType()
4108                          ? AI.getCoerceToType()
4109                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4110     llvm::Value *V;
4111     Address Tmp = CGF.CreateMemTemp(Ty);
4112     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4113     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4114         RegAddrLo, ST->getStructElementType(0)));
4115     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4116     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4117         RegAddrHi, ST->getStructElementType(1)));
4118     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4119 
4120     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4121   }
4122 
4123   // AMD64-ABI 3.5.7p5: Step 5. Set:
4124   // l->gp_offset = l->gp_offset + num_gp * 8
4125   // l->fp_offset = l->fp_offset + num_fp * 16.
4126   if (neededInt) {
4127     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4128     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4129                             gp_offset_p);
4130   }
4131   if (neededSSE) {
4132     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4133     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4134                             fp_offset_p);
4135   }
4136   CGF.EmitBranch(ContBlock);
4137 
4138   // Emit code to load the value if it was passed in memory.
4139 
4140   CGF.EmitBlock(InMemBlock);
4141   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4142 
4143   // Return the appropriate result.
4144 
4145   CGF.EmitBlock(ContBlock);
4146   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4147                                  "vaarg.addr");
4148   return ResAddr;
4149 }
4150 
4151 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4152                                    QualType Ty) const {
4153   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4154                           CGF.getContext().getTypeInfoInChars(Ty),
4155                           CharUnits::fromQuantity(8),
4156                           /*allowHigherAlign*/ false);
4157 }
4158 
4159 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4160     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4161   const Type *Base = nullptr;
4162   uint64_t NumElts = 0;
4163 
4164   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4165       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4166     FreeSSERegs -= NumElts;
4167     return getDirectX86Hva();
4168   }
4169   return current;
4170 }
4171 
4172 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4173                                       bool IsReturnType, bool IsVectorCall,
4174                                       bool IsRegCall) const {
4175 
4176   if (Ty->isVoidType())
4177     return ABIArgInfo::getIgnore();
4178 
4179   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4180     Ty = EnumTy->getDecl()->getIntegerType();
4181 
4182   TypeInfo Info = getContext().getTypeInfo(Ty);
4183   uint64_t Width = Info.Width;
4184   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4185 
4186   const RecordType *RT = Ty->getAs<RecordType>();
4187   if (RT) {
4188     if (!IsReturnType) {
4189       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4190         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4191     }
4192 
4193     if (RT->getDecl()->hasFlexibleArrayMember())
4194       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4195 
4196   }
4197 
4198   const Type *Base = nullptr;
4199   uint64_t NumElts = 0;
4200   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4201   // other targets.
4202   if ((IsVectorCall || IsRegCall) &&
4203       isHomogeneousAggregate(Ty, Base, NumElts)) {
4204     if (IsRegCall) {
4205       if (FreeSSERegs >= NumElts) {
4206         FreeSSERegs -= NumElts;
4207         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4208           return ABIArgInfo::getDirect();
4209         return ABIArgInfo::getExpand();
4210       }
4211       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4212     } else if (IsVectorCall) {
4213       if (FreeSSERegs >= NumElts &&
4214           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4215         FreeSSERegs -= NumElts;
4216         return ABIArgInfo::getDirect();
4217       } else if (IsReturnType) {
4218         return ABIArgInfo::getExpand();
4219       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4220         // HVAs are delayed and reclassified in the 2nd step.
4221         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4222       }
4223     }
4224   }
4225 
4226   if (Ty->isMemberPointerType()) {
4227     // If the member pointer is represented by an LLVM int or ptr, pass it
4228     // directly.
4229     llvm::Type *LLTy = CGT.ConvertType(Ty);
4230     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4231       return ABIArgInfo::getDirect();
4232   }
4233 
4234   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4235     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4236     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4237     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4238       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4239 
4240     // Otherwise, coerce it to a small integer.
4241     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4242   }
4243 
4244   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4245     switch (BT->getKind()) {
4246     case BuiltinType::Bool:
4247       // Bool type is always extended to the ABI, other builtin types are not
4248       // extended.
4249       return ABIArgInfo::getExtend(Ty);
4250 
4251     case BuiltinType::LongDouble:
4252       // Mingw64 GCC uses the old 80 bit extended precision floating point
4253       // unit. It passes them indirectly through memory.
4254       if (IsMingw64) {
4255         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4256         if (LDF == &llvm::APFloat::x87DoubleExtended())
4257           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4258       }
4259       break;
4260 
4261     case BuiltinType::Int128:
4262     case BuiltinType::UInt128:
4263       // If it's a parameter type, the normal ABI rule is that arguments larger
4264       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4265       // even though it isn't particularly efficient.
4266       if (!IsReturnType)
4267         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4268 
4269       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4270       // Clang matches them for compatibility.
4271       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4272           llvm::Type::getInt64Ty(getVMContext()), 2));
4273 
4274     default:
4275       break;
4276     }
4277   }
4278 
4279   if (Ty->isExtIntType()) {
4280     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4281     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4282     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4283     // anyway as long is it fits in them, so we don't have to check the power of
4284     // 2.
4285     if (Width <= 64)
4286       return ABIArgInfo::getDirect();
4287     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4288   }
4289 
4290   return ABIArgInfo::getDirect();
4291 }
4292 
4293 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4294   const unsigned CC = FI.getCallingConvention();
4295   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4296   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4297 
4298   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4299   // classification rules.
4300   if (CC == llvm::CallingConv::X86_64_SysV) {
4301     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4302     SysVABIInfo.computeInfo(FI);
4303     return;
4304   }
4305 
4306   unsigned FreeSSERegs = 0;
4307   if (IsVectorCall) {
4308     // We can use up to 4 SSE return registers with vectorcall.
4309     FreeSSERegs = 4;
4310   } else if (IsRegCall) {
4311     // RegCall gives us 16 SSE registers.
4312     FreeSSERegs = 16;
4313   }
4314 
4315   if (!getCXXABI().classifyReturnType(FI))
4316     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4317                                   IsVectorCall, IsRegCall);
4318 
4319   if (IsVectorCall) {
4320     // We can use up to 6 SSE register parameters with vectorcall.
4321     FreeSSERegs = 6;
4322   } else if (IsRegCall) {
4323     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4324     FreeSSERegs = 16;
4325   }
4326 
4327   unsigned ArgNum = 0;
4328   unsigned ZeroSSERegs = 0;
4329   for (auto &I : FI.arguments()) {
4330     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4331     // XMM/YMM registers. After the sixth argument, pretend no vector
4332     // registers are left.
4333     unsigned *MaybeFreeSSERegs =
4334         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4335     I.info =
4336         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4337     ++ArgNum;
4338   }
4339 
4340   if (IsVectorCall) {
4341     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4342     // second pass.
4343     for (auto &I : FI.arguments())
4344       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4345   }
4346 }
4347 
4348 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4349                                     QualType Ty) const {
4350 
4351   bool IsIndirect = false;
4352 
4353   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4354   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4355   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4356     uint64_t Width = getContext().getTypeSize(Ty);
4357     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4358   }
4359 
4360   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4361                           CGF.getContext().getTypeInfoInChars(Ty),
4362                           CharUnits::fromQuantity(8),
4363                           /*allowHigherAlign*/ false);
4364 }
4365 
4366 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4367                                         llvm::Value *Address, bool Is64Bit,
4368                                         bool IsAIX) {
4369   // This is calculated from the LLVM and GCC tables and verified
4370   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4371 
4372   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4373 
4374   llvm::IntegerType *i8 = CGF.Int8Ty;
4375   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4376   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4377   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4378 
4379   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4380   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4381 
4382   // 32-63: fp0-31, the 8-byte floating-point registers
4383   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4384 
4385   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4386   // 64: mq
4387   // 65: lr
4388   // 66: ctr
4389   // 67: ap
4390   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4391 
4392   // 68-76 are various 4-byte special-purpose registers:
4393   // 68-75 cr0-7
4394   // 76: xer
4395   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4396 
4397   // 77-108: v0-31, the 16-byte vector registers
4398   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4399 
4400   // 109: vrsave
4401   // 110: vscr
4402   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4403 
4404   // AIX does not utilize the rest of the registers.
4405   if (IsAIX)
4406     return false;
4407 
4408   // 111: spe_acc
4409   // 112: spefscr
4410   // 113: sfp
4411   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4412 
4413   if (!Is64Bit)
4414     return false;
4415 
4416   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4417   // or above CPU.
4418   // 64-bit only registers:
4419   // 114: tfhar
4420   // 115: tfiar
4421   // 116: texasr
4422   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4423 
4424   return false;
4425 }
4426 
4427 // AIX
4428 namespace {
4429 /// AIXABIInfo - The AIX XCOFF ABI information.
4430 class AIXABIInfo : public ABIInfo {
4431   const bool Is64Bit;
4432   const unsigned PtrByteSize;
4433   CharUnits getParamTypeAlignment(QualType Ty) const;
4434 
4435 public:
4436   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4437       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4438 
4439   bool isPromotableTypeForABI(QualType Ty) const;
4440 
4441   ABIArgInfo classifyReturnType(QualType RetTy) const;
4442   ABIArgInfo classifyArgumentType(QualType Ty) const;
4443 
4444   void computeInfo(CGFunctionInfo &FI) const override {
4445     if (!getCXXABI().classifyReturnType(FI))
4446       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4447 
4448     for (auto &I : FI.arguments())
4449       I.info = classifyArgumentType(I.type);
4450   }
4451 
4452   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4453                     QualType Ty) const override;
4454 };
4455 
4456 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4457   const bool Is64Bit;
4458 
4459 public:
4460   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4461       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4462         Is64Bit(Is64Bit) {}
4463   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4464     return 1; // r1 is the dedicated stack pointer
4465   }
4466 
4467   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4468                                llvm::Value *Address) const override;
4469 };
4470 } // namespace
4471 
4472 // Return true if the ABI requires Ty to be passed sign- or zero-
4473 // extended to 32/64 bits.
4474 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4475   // Treat an enum type as its underlying type.
4476   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4477     Ty = EnumTy->getDecl()->getIntegerType();
4478 
4479   // Promotable integer types are required to be promoted by the ABI.
4480   if (Ty->isPromotableIntegerType())
4481     return true;
4482 
4483   if (!Is64Bit)
4484     return false;
4485 
4486   // For 64 bit mode, in addition to the usual promotable integer types, we also
4487   // need to extend all 32-bit types, since the ABI requires promotion to 64
4488   // bits.
4489   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4490     switch (BT->getKind()) {
4491     case BuiltinType::Int:
4492     case BuiltinType::UInt:
4493       return true;
4494     default:
4495       break;
4496     }
4497 
4498   return false;
4499 }
4500 
4501 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4502   if (RetTy->isAnyComplexType())
4503     return ABIArgInfo::getDirect();
4504 
4505   if (RetTy->isVectorType())
4506     return ABIArgInfo::getDirect();
4507 
4508   if (RetTy->isVoidType())
4509     return ABIArgInfo::getIgnore();
4510 
4511   if (isAggregateTypeForABI(RetTy))
4512     return getNaturalAlignIndirect(RetTy);
4513 
4514   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4515                                         : ABIArgInfo::getDirect());
4516 }
4517 
4518 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4519   Ty = useFirstFieldIfTransparentUnion(Ty);
4520 
4521   if (Ty->isAnyComplexType())
4522     return ABIArgInfo::getDirect();
4523 
4524   if (Ty->isVectorType())
4525     return ABIArgInfo::getDirect();
4526 
4527   if (isAggregateTypeForABI(Ty)) {
4528     // Records with non-trivial destructors/copy-constructors should not be
4529     // passed by value.
4530     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4531       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4532 
4533     CharUnits CCAlign = getParamTypeAlignment(Ty);
4534     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4535 
4536     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4537                                    /*Realign*/ TyAlign > CCAlign);
4538   }
4539 
4540   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4541                                      : ABIArgInfo::getDirect());
4542 }
4543 
4544 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4545   // Complex types are passed just like their elements.
4546   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4547     Ty = CTy->getElementType();
4548 
4549   if (Ty->isVectorType())
4550     return CharUnits::fromQuantity(16);
4551 
4552   // If the structure contains a vector type, the alignment is 16.
4553   if (isRecordWithSIMDVectorType(getContext(), Ty))
4554     return CharUnits::fromQuantity(16);
4555 
4556   return CharUnits::fromQuantity(PtrByteSize);
4557 }
4558 
4559 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4560                               QualType Ty) const {
4561   if (Ty->isAnyComplexType())
4562     llvm::report_fatal_error("complex type is not supported on AIX yet");
4563 
4564   if (Ty->isVectorType())
4565     llvm::report_fatal_error(
4566         "vector types are not yet supported for variadic functions on AIX");
4567 
4568   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4569   TypeInfo.Align = getParamTypeAlignment(Ty);
4570 
4571   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4572 
4573   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4574                           SlotSize, /*AllowHigher*/ true);
4575 }
4576 
4577 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4578     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4579   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4580 }
4581 
4582 // PowerPC-32
4583 namespace {
4584 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4585 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4586   bool IsSoftFloatABI;
4587   bool IsRetSmallStructInRegABI;
4588 
4589   CharUnits getParamTypeAlignment(QualType Ty) const;
4590 
4591 public:
4592   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4593                      bool RetSmallStructInRegABI)
4594       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4595         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4596 
4597   ABIArgInfo classifyReturnType(QualType RetTy) const;
4598 
4599   void computeInfo(CGFunctionInfo &FI) const override {
4600     if (!getCXXABI().classifyReturnType(FI))
4601       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4602     for (auto &I : FI.arguments())
4603       I.info = classifyArgumentType(I.type);
4604   }
4605 
4606   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4607                     QualType Ty) const override;
4608 };
4609 
4610 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4611 public:
4612   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4613                          bool RetSmallStructInRegABI)
4614       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4615             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4616 
4617   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4618                                      const CodeGenOptions &Opts);
4619 
4620   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4621     // This is recovered from gcc output.
4622     return 1; // r1 is the dedicated stack pointer
4623   }
4624 
4625   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4626                                llvm::Value *Address) const override;
4627 };
4628 }
4629 
4630 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4631   // Complex types are passed just like their elements.
4632   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4633     Ty = CTy->getElementType();
4634 
4635   if (Ty->isVectorType())
4636     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4637                                                                        : 4);
4638 
4639   // For single-element float/vector structs, we consider the whole type
4640   // to have the same alignment requirements as its single element.
4641   const Type *AlignTy = nullptr;
4642   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4643     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4644     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4645         (BT && BT->isFloatingPoint()))
4646       AlignTy = EltType;
4647   }
4648 
4649   if (AlignTy)
4650     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4651   return CharUnits::fromQuantity(4);
4652 }
4653 
4654 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4655   uint64_t Size;
4656 
4657   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4658   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4659       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4660     // System V ABI (1995), page 3-22, specified:
4661     // > A structure or union whose size is less than or equal to 8 bytes
4662     // > shall be returned in r3 and r4, as if it were first stored in the
4663     // > 8-byte aligned memory area and then the low addressed word were
4664     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4665     // > the last member of the structure or union are not defined.
4666     //
4667     // GCC for big-endian PPC32 inserts the pad before the first member,
4668     // not "beyond the last member" of the struct.  To stay compatible
4669     // with GCC, we coerce the struct to an integer of the same size.
4670     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4671     if (Size == 0)
4672       return ABIArgInfo::getIgnore();
4673     else {
4674       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4675       return ABIArgInfo::getDirect(CoerceTy);
4676     }
4677   }
4678 
4679   return DefaultABIInfo::classifyReturnType(RetTy);
4680 }
4681 
4682 // TODO: this implementation is now likely redundant with
4683 // DefaultABIInfo::EmitVAArg.
4684 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4685                                       QualType Ty) const {
4686   if (getTarget().getTriple().isOSDarwin()) {
4687     auto TI = getContext().getTypeInfoInChars(Ty);
4688     TI.Align = getParamTypeAlignment(Ty);
4689 
4690     CharUnits SlotSize = CharUnits::fromQuantity(4);
4691     return emitVoidPtrVAArg(CGF, VAList, Ty,
4692                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4693                             /*AllowHigherAlign=*/true);
4694   }
4695 
4696   const unsigned OverflowLimit = 8;
4697   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4698     // TODO: Implement this. For now ignore.
4699     (void)CTy;
4700     return Address::invalid(); // FIXME?
4701   }
4702 
4703   // struct __va_list_tag {
4704   //   unsigned char gpr;
4705   //   unsigned char fpr;
4706   //   unsigned short reserved;
4707   //   void *overflow_arg_area;
4708   //   void *reg_save_area;
4709   // };
4710 
4711   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4712   bool isInt =
4713       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4714   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4715 
4716   // All aggregates are passed indirectly?  That doesn't seem consistent
4717   // with the argument-lowering code.
4718   bool isIndirect = Ty->isAggregateType();
4719 
4720   CGBuilderTy &Builder = CGF.Builder;
4721 
4722   // The calling convention either uses 1-2 GPRs or 1 FPR.
4723   Address NumRegsAddr = Address::invalid();
4724   if (isInt || IsSoftFloatABI) {
4725     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4726   } else {
4727     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4728   }
4729 
4730   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4731 
4732   // "Align" the register count when TY is i64.
4733   if (isI64 || (isF64 && IsSoftFloatABI)) {
4734     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4735     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4736   }
4737 
4738   llvm::Value *CC =
4739       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4740 
4741   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4742   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4743   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4744 
4745   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4746 
4747   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4748   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4749 
4750   // Case 1: consume registers.
4751   Address RegAddr = Address::invalid();
4752   {
4753     CGF.EmitBlock(UsingRegs);
4754 
4755     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4756     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4757                       CharUnits::fromQuantity(8));
4758     assert(RegAddr.getElementType() == CGF.Int8Ty);
4759 
4760     // Floating-point registers start after the general-purpose registers.
4761     if (!(isInt || IsSoftFloatABI)) {
4762       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4763                                                    CharUnits::fromQuantity(32));
4764     }
4765 
4766     // Get the address of the saved value by scaling the number of
4767     // registers we've used by the number of
4768     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4769     llvm::Value *RegOffset =
4770       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4771     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4772                                             RegAddr.getPointer(), RegOffset),
4773                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4774     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4775 
4776     // Increase the used-register count.
4777     NumRegs =
4778       Builder.CreateAdd(NumRegs,
4779                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4780     Builder.CreateStore(NumRegs, NumRegsAddr);
4781 
4782     CGF.EmitBranch(Cont);
4783   }
4784 
4785   // Case 2: consume space in the overflow area.
4786   Address MemAddr = Address::invalid();
4787   {
4788     CGF.EmitBlock(UsingOverflow);
4789 
4790     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4791 
4792     // Everything in the overflow area is rounded up to a size of at least 4.
4793     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4794 
4795     CharUnits Size;
4796     if (!isIndirect) {
4797       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4798       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4799     } else {
4800       Size = CGF.getPointerSize();
4801     }
4802 
4803     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4804     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4805                          OverflowAreaAlign);
4806     // Round up address of argument to alignment
4807     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4808     if (Align > OverflowAreaAlign) {
4809       llvm::Value *Ptr = OverflowArea.getPointer();
4810       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4811                                                            Align);
4812     }
4813 
4814     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4815 
4816     // Increase the overflow area.
4817     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4818     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4819     CGF.EmitBranch(Cont);
4820   }
4821 
4822   CGF.EmitBlock(Cont);
4823 
4824   // Merge the cases with a phi.
4825   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4826                                 "vaarg.addr");
4827 
4828   // Load the pointer if the argument was passed indirectly.
4829   if (isIndirect) {
4830     Result = Address(Builder.CreateLoad(Result, "aggr"),
4831                      getContext().getTypeAlignInChars(Ty));
4832   }
4833 
4834   return Result;
4835 }
4836 
4837 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4838     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4839   assert(Triple.isPPC32());
4840 
4841   switch (Opts.getStructReturnConvention()) {
4842   case CodeGenOptions::SRCK_Default:
4843     break;
4844   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4845     return false;
4846   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4847     return true;
4848   }
4849 
4850   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4851     return true;
4852 
4853   return false;
4854 }
4855 
4856 bool
4857 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4858                                                 llvm::Value *Address) const {
4859   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4860                                      /*IsAIX*/ false);
4861 }
4862 
4863 // PowerPC-64
4864 
4865 namespace {
4866 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4867 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4868 public:
4869   enum ABIKind {
4870     ELFv1 = 0,
4871     ELFv2
4872   };
4873 
4874 private:
4875   static const unsigned GPRBits = 64;
4876   ABIKind Kind;
4877   bool IsSoftFloatABI;
4878 
4879 public:
4880   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4881                      bool SoftFloatABI)
4882       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4883 
4884   bool isPromotableTypeForABI(QualType Ty) const;
4885   CharUnits getParamTypeAlignment(QualType Ty) const;
4886 
4887   ABIArgInfo classifyReturnType(QualType RetTy) const;
4888   ABIArgInfo classifyArgumentType(QualType Ty) const;
4889 
4890   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4891   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4892                                          uint64_t Members) const override;
4893 
4894   // TODO: We can add more logic to computeInfo to improve performance.
4895   // Example: For aggregate arguments that fit in a register, we could
4896   // use getDirectInReg (as is done below for structs containing a single
4897   // floating-point value) to avoid pushing them to memory on function
4898   // entry.  This would require changing the logic in PPCISelLowering
4899   // when lowering the parameters in the caller and args in the callee.
4900   void computeInfo(CGFunctionInfo &FI) const override {
4901     if (!getCXXABI().classifyReturnType(FI))
4902       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4903     for (auto &I : FI.arguments()) {
4904       // We rely on the default argument classification for the most part.
4905       // One exception:  An aggregate containing a single floating-point
4906       // or vector item must be passed in a register if one is available.
4907       const Type *T = isSingleElementStruct(I.type, getContext());
4908       if (T) {
4909         const BuiltinType *BT = T->getAs<BuiltinType>();
4910         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4911             (BT && BT->isFloatingPoint())) {
4912           QualType QT(T, 0);
4913           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4914           continue;
4915         }
4916       }
4917       I.info = classifyArgumentType(I.type);
4918     }
4919   }
4920 
4921   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4922                     QualType Ty) const override;
4923 
4924   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4925                                     bool asReturnValue) const override {
4926     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4927   }
4928 
4929   bool isSwiftErrorInRegister() const override {
4930     return false;
4931   }
4932 };
4933 
4934 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4935 
4936 public:
4937   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4938                                PPC64_SVR4_ABIInfo::ABIKind Kind,
4939                                bool SoftFloatABI)
4940       : TargetCodeGenInfo(
4941             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
4942 
4943   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4944     // This is recovered from gcc output.
4945     return 1; // r1 is the dedicated stack pointer
4946   }
4947 
4948   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4949                                llvm::Value *Address) const override;
4950 };
4951 
4952 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4953 public:
4954   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4955 
4956   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4957     // This is recovered from gcc output.
4958     return 1; // r1 is the dedicated stack pointer
4959   }
4960 
4961   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4962                                llvm::Value *Address) const override;
4963 };
4964 
4965 }
4966 
4967 // Return true if the ABI requires Ty to be passed sign- or zero-
4968 // extended to 64 bits.
4969 bool
4970 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4971   // Treat an enum type as its underlying type.
4972   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4973     Ty = EnumTy->getDecl()->getIntegerType();
4974 
4975   // Promotable integer types are required to be promoted by the ABI.
4976   if (isPromotableIntegerTypeForABI(Ty))
4977     return true;
4978 
4979   // In addition to the usual promotable integer types, we also need to
4980   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4981   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4982     switch (BT->getKind()) {
4983     case BuiltinType::Int:
4984     case BuiltinType::UInt:
4985       return true;
4986     default:
4987       break;
4988     }
4989 
4990   if (const auto *EIT = Ty->getAs<ExtIntType>())
4991     if (EIT->getNumBits() < 64)
4992       return true;
4993 
4994   return false;
4995 }
4996 
4997 /// isAlignedParamType - Determine whether a type requires 16-byte or
4998 /// higher alignment in the parameter area.  Always returns at least 8.
4999 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5000   // Complex types are passed just like their elements.
5001   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5002     Ty = CTy->getElementType();
5003 
5004   // Only vector types of size 16 bytes need alignment (larger types are
5005   // passed via reference, smaller types are not aligned).
5006   if (Ty->isVectorType()) {
5007     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5008   } else if (Ty->isRealFloatingType() &&
5009              &getContext().getFloatTypeSemantics(Ty) ==
5010                  &llvm::APFloat::IEEEquad()) {
5011     // According to ABI document section 'Optional Save Areas': If extended
5012     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5013     // format are supported, map them to a single quadword, quadword aligned.
5014     return CharUnits::fromQuantity(16);
5015   }
5016 
5017   // For single-element float/vector structs, we consider the whole type
5018   // to have the same alignment requirements as its single element.
5019   const Type *AlignAsType = nullptr;
5020   const Type *EltType = isSingleElementStruct(Ty, getContext());
5021   if (EltType) {
5022     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5023     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5024         (BT && BT->isFloatingPoint()))
5025       AlignAsType = EltType;
5026   }
5027 
5028   // Likewise for ELFv2 homogeneous aggregates.
5029   const Type *Base = nullptr;
5030   uint64_t Members = 0;
5031   if (!AlignAsType && Kind == ELFv2 &&
5032       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5033     AlignAsType = Base;
5034 
5035   // With special case aggregates, only vector base types need alignment.
5036   if (AlignAsType) {
5037     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5038   }
5039 
5040   // Otherwise, we only need alignment for any aggregate type that
5041   // has an alignment requirement of >= 16 bytes.
5042   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5043     return CharUnits::fromQuantity(16);
5044   }
5045 
5046   return CharUnits::fromQuantity(8);
5047 }
5048 
5049 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5050 /// aggregate.  Base is set to the base element type, and Members is set
5051 /// to the number of base elements.
5052 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5053                                      uint64_t &Members) const {
5054   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5055     uint64_t NElements = AT->getSize().getZExtValue();
5056     if (NElements == 0)
5057       return false;
5058     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5059       return false;
5060     Members *= NElements;
5061   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5062     const RecordDecl *RD = RT->getDecl();
5063     if (RD->hasFlexibleArrayMember())
5064       return false;
5065 
5066     Members = 0;
5067 
5068     // If this is a C++ record, check the properties of the record such as
5069     // bases and ABI specific restrictions
5070     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5071       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5072         return false;
5073 
5074       for (const auto &I : CXXRD->bases()) {
5075         // Ignore empty records.
5076         if (isEmptyRecord(getContext(), I.getType(), true))
5077           continue;
5078 
5079         uint64_t FldMembers;
5080         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5081           return false;
5082 
5083         Members += FldMembers;
5084       }
5085     }
5086 
5087     for (const auto *FD : RD->fields()) {
5088       // Ignore (non-zero arrays of) empty records.
5089       QualType FT = FD->getType();
5090       while (const ConstantArrayType *AT =
5091              getContext().getAsConstantArrayType(FT)) {
5092         if (AT->getSize().getZExtValue() == 0)
5093           return false;
5094         FT = AT->getElementType();
5095       }
5096       if (isEmptyRecord(getContext(), FT, true))
5097         continue;
5098 
5099       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5100       if (getContext().getLangOpts().CPlusPlus &&
5101           FD->isZeroLengthBitField(getContext()))
5102         continue;
5103 
5104       uint64_t FldMembers;
5105       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5106         return false;
5107 
5108       Members = (RD->isUnion() ?
5109                  std::max(Members, FldMembers) : Members + FldMembers);
5110     }
5111 
5112     if (!Base)
5113       return false;
5114 
5115     // Ensure there is no padding.
5116     if (getContext().getTypeSize(Base) * Members !=
5117         getContext().getTypeSize(Ty))
5118       return false;
5119   } else {
5120     Members = 1;
5121     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5122       Members = 2;
5123       Ty = CT->getElementType();
5124     }
5125 
5126     // Most ABIs only support float, double, and some vector type widths.
5127     if (!isHomogeneousAggregateBaseType(Ty))
5128       return false;
5129 
5130     // The base type must be the same for all members.  Types that
5131     // agree in both total size and mode (float vs. vector) are
5132     // treated as being equivalent here.
5133     const Type *TyPtr = Ty.getTypePtr();
5134     if (!Base) {
5135       Base = TyPtr;
5136       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5137       // so make sure to widen it explicitly.
5138       if (const VectorType *VT = Base->getAs<VectorType>()) {
5139         QualType EltTy = VT->getElementType();
5140         unsigned NumElements =
5141             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5142         Base = getContext()
5143                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5144                    .getTypePtr();
5145       }
5146     }
5147 
5148     if (Base->isVectorType() != TyPtr->isVectorType() ||
5149         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5150       return false;
5151   }
5152   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5153 }
5154 
5155 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5156   // Homogeneous aggregates for ELFv2 must have base types of float,
5157   // double, long double, or 128-bit vectors.
5158   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5159     if (BT->getKind() == BuiltinType::Float ||
5160         BT->getKind() == BuiltinType::Double ||
5161         BT->getKind() == BuiltinType::LongDouble ||
5162         (getContext().getTargetInfo().hasFloat128Type() &&
5163           (BT->getKind() == BuiltinType::Float128))) {
5164       if (IsSoftFloatABI)
5165         return false;
5166       return true;
5167     }
5168   }
5169   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5170     if (getContext().getTypeSize(VT) == 128)
5171       return true;
5172   }
5173   return false;
5174 }
5175 
5176 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5177     const Type *Base, uint64_t Members) const {
5178   // Vector and fp128 types require one register, other floating point types
5179   // require one or two registers depending on their size.
5180   uint32_t NumRegs =
5181       ((getContext().getTargetInfo().hasFloat128Type() &&
5182           Base->isFloat128Type()) ||
5183         Base->isVectorType()) ? 1
5184                               : (getContext().getTypeSize(Base) + 63) / 64;
5185 
5186   // Homogeneous Aggregates may occupy at most 8 registers.
5187   return Members * NumRegs <= 8;
5188 }
5189 
5190 ABIArgInfo
5191 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5192   Ty = useFirstFieldIfTransparentUnion(Ty);
5193 
5194   if (Ty->isAnyComplexType())
5195     return ABIArgInfo::getDirect();
5196 
5197   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5198   // or via reference (larger than 16 bytes).
5199   if (Ty->isVectorType()) {
5200     uint64_t Size = getContext().getTypeSize(Ty);
5201     if (Size > 128)
5202       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5203     else if (Size < 128) {
5204       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5205       return ABIArgInfo::getDirect(CoerceTy);
5206     }
5207   }
5208 
5209   if (const auto *EIT = Ty->getAs<ExtIntType>())
5210     if (EIT->getNumBits() > 128)
5211       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5212 
5213   if (isAggregateTypeForABI(Ty)) {
5214     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5215       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5216 
5217     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5218     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5219 
5220     // ELFv2 homogeneous aggregates are passed as array types.
5221     const Type *Base = nullptr;
5222     uint64_t Members = 0;
5223     if (Kind == ELFv2 &&
5224         isHomogeneousAggregate(Ty, Base, Members)) {
5225       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5226       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5227       return ABIArgInfo::getDirect(CoerceTy);
5228     }
5229 
5230     // If an aggregate may end up fully in registers, we do not
5231     // use the ByVal method, but pass the aggregate as array.
5232     // This is usually beneficial since we avoid forcing the
5233     // back-end to store the argument to memory.
5234     uint64_t Bits = getContext().getTypeSize(Ty);
5235     if (Bits > 0 && Bits <= 8 * GPRBits) {
5236       llvm::Type *CoerceTy;
5237 
5238       // Types up to 8 bytes are passed as integer type (which will be
5239       // properly aligned in the argument save area doubleword).
5240       if (Bits <= GPRBits)
5241         CoerceTy =
5242             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5243       // Larger types are passed as arrays, with the base type selected
5244       // according to the required alignment in the save area.
5245       else {
5246         uint64_t RegBits = ABIAlign * 8;
5247         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5248         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5249         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5250       }
5251 
5252       return ABIArgInfo::getDirect(CoerceTy);
5253     }
5254 
5255     // All other aggregates are passed ByVal.
5256     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5257                                    /*ByVal=*/true,
5258                                    /*Realign=*/TyAlign > ABIAlign);
5259   }
5260 
5261   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5262                                      : ABIArgInfo::getDirect());
5263 }
5264 
5265 ABIArgInfo
5266 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5267   if (RetTy->isVoidType())
5268     return ABIArgInfo::getIgnore();
5269 
5270   if (RetTy->isAnyComplexType())
5271     return ABIArgInfo::getDirect();
5272 
5273   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5274   // or via reference (larger than 16 bytes).
5275   if (RetTy->isVectorType()) {
5276     uint64_t Size = getContext().getTypeSize(RetTy);
5277     if (Size > 128)
5278       return getNaturalAlignIndirect(RetTy);
5279     else if (Size < 128) {
5280       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5281       return ABIArgInfo::getDirect(CoerceTy);
5282     }
5283   }
5284 
5285   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5286     if (EIT->getNumBits() > 128)
5287       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5288 
5289   if (isAggregateTypeForABI(RetTy)) {
5290     // ELFv2 homogeneous aggregates are returned as array types.
5291     const Type *Base = nullptr;
5292     uint64_t Members = 0;
5293     if (Kind == ELFv2 &&
5294         isHomogeneousAggregate(RetTy, Base, Members)) {
5295       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5296       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5297       return ABIArgInfo::getDirect(CoerceTy);
5298     }
5299 
5300     // ELFv2 small aggregates are returned in up to two registers.
5301     uint64_t Bits = getContext().getTypeSize(RetTy);
5302     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5303       if (Bits == 0)
5304         return ABIArgInfo::getIgnore();
5305 
5306       llvm::Type *CoerceTy;
5307       if (Bits > GPRBits) {
5308         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5309         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5310       } else
5311         CoerceTy =
5312             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5313       return ABIArgInfo::getDirect(CoerceTy);
5314     }
5315 
5316     // All other aggregates are returned indirectly.
5317     return getNaturalAlignIndirect(RetTy);
5318   }
5319 
5320   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5321                                         : ABIArgInfo::getDirect());
5322 }
5323 
5324 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5325 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5326                                       QualType Ty) const {
5327   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5328   TypeInfo.Align = getParamTypeAlignment(Ty);
5329 
5330   CharUnits SlotSize = CharUnits::fromQuantity(8);
5331 
5332   // If we have a complex type and the base type is smaller than 8 bytes,
5333   // the ABI calls for the real and imaginary parts to be right-adjusted
5334   // in separate doublewords.  However, Clang expects us to produce a
5335   // pointer to a structure with the two parts packed tightly.  So generate
5336   // loads of the real and imaginary parts relative to the va_list pointer,
5337   // and store them to a temporary structure.
5338   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5339     CharUnits EltSize = TypeInfo.Width / 2;
5340     if (EltSize < SlotSize) {
5341       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5342                                             SlotSize * 2, SlotSize,
5343                                             SlotSize, /*AllowHigher*/ true);
5344 
5345       Address RealAddr = Addr;
5346       Address ImagAddr = RealAddr;
5347       if (CGF.CGM.getDataLayout().isBigEndian()) {
5348         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5349                                                           SlotSize - EltSize);
5350         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5351                                                       2 * SlotSize - EltSize);
5352       } else {
5353         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5354       }
5355 
5356       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5357       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5358       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5359       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5360       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5361 
5362       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5363       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5364                              /*init*/ true);
5365       return Temp;
5366     }
5367   }
5368 
5369   // Otherwise, just use the general rule.
5370   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5371                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5372 }
5373 
5374 bool
5375 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5376   CodeGen::CodeGenFunction &CGF,
5377   llvm::Value *Address) const {
5378   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5379                                      /*IsAIX*/ false);
5380 }
5381 
5382 bool
5383 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5384                                                 llvm::Value *Address) const {
5385   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5386                                      /*IsAIX*/ false);
5387 }
5388 
5389 //===----------------------------------------------------------------------===//
5390 // AArch64 ABI Implementation
5391 //===----------------------------------------------------------------------===//
5392 
5393 namespace {
5394 
5395 class AArch64ABIInfo : public SwiftABIInfo {
5396 public:
5397   enum ABIKind {
5398     AAPCS = 0,
5399     DarwinPCS,
5400     Win64
5401   };
5402 
5403 private:
5404   ABIKind Kind;
5405 
5406 public:
5407   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5408     : SwiftABIInfo(CGT), Kind(Kind) {}
5409 
5410 private:
5411   ABIKind getABIKind() const { return Kind; }
5412   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5413 
5414   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5415   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5416   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5417   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5418   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5419                                          uint64_t Members) const override;
5420 
5421   bool isIllegalVectorType(QualType Ty) const;
5422 
5423   void computeInfo(CGFunctionInfo &FI) const override {
5424     if (!::classifyReturnType(getCXXABI(), FI, *this))
5425       FI.getReturnInfo() =
5426           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5427 
5428     for (auto &it : FI.arguments())
5429       it.info = classifyArgumentType(it.type);
5430   }
5431 
5432   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5433                           CodeGenFunction &CGF) const;
5434 
5435   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5436                          CodeGenFunction &CGF) const;
5437 
5438   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5439                     QualType Ty) const override {
5440     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5441     if (isa<llvm::ScalableVectorType>(BaseTy))
5442       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5443                                "currently not supported");
5444 
5445     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5446                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5447                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5448   }
5449 
5450   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5451                       QualType Ty) const override;
5452 
5453   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5454                                     bool asReturnValue) const override {
5455     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5456   }
5457   bool isSwiftErrorInRegister() const override {
5458     return true;
5459   }
5460 
5461   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5462                                  unsigned elts) const override;
5463 
5464   bool allowBFloatArgsAndRet() const override {
5465     return getTarget().hasBFloat16Type();
5466   }
5467 };
5468 
5469 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5470 public:
5471   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5472       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5473 
5474   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5475     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5476   }
5477 
5478   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5479     return 31;
5480   }
5481 
5482   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5483 
5484   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5485                            CodeGen::CodeGenModule &CGM) const override {
5486     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5487     if (!FD)
5488       return;
5489 
5490     const auto *TA = FD->getAttr<TargetAttr>();
5491     if (TA == nullptr)
5492       return;
5493 
5494     ParsedTargetAttr Attr = TA->parse();
5495     if (Attr.BranchProtection.empty())
5496       return;
5497 
5498     TargetInfo::BranchProtectionInfo BPI;
5499     StringRef Error;
5500     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5501                                                    BPI, Error);
5502     assert(Error.empty());
5503 
5504     auto *Fn = cast<llvm::Function>(GV);
5505     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5506     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5507 
5508     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5509       Fn->addFnAttr("sign-return-address-key",
5510                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5511                         ? "a_key"
5512                         : "b_key");
5513     }
5514 
5515     Fn->addFnAttr("branch-target-enforcement",
5516                   BPI.BranchTargetEnforcement ? "true" : "false");
5517   }
5518 };
5519 
5520 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5521 public:
5522   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5523       : AArch64TargetCodeGenInfo(CGT, K) {}
5524 
5525   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5526                            CodeGen::CodeGenModule &CGM) const override;
5527 
5528   void getDependentLibraryOption(llvm::StringRef Lib,
5529                                  llvm::SmallString<24> &Opt) const override {
5530     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5531   }
5532 
5533   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5534                                llvm::SmallString<32> &Opt) const override {
5535     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5536   }
5537 };
5538 
5539 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5540     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5541   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5542   if (GV->isDeclaration())
5543     return;
5544   addStackProbeTargetAttributes(D, GV, CGM);
5545 }
5546 }
5547 
5548 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5549   assert(Ty->isVectorType() && "expected vector type!");
5550 
5551   const auto *VT = Ty->castAs<VectorType>();
5552   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5553     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5554     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5555                BuiltinType::UChar &&
5556            "unexpected builtin type for SVE predicate!");
5557     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5558         llvm::Type::getInt1Ty(getVMContext()), 16));
5559   }
5560 
5561   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5562     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5563 
5564     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5565     llvm::ScalableVectorType *ResType = nullptr;
5566     switch (BT->getKind()) {
5567     default:
5568       llvm_unreachable("unexpected builtin type for SVE vector!");
5569     case BuiltinType::SChar:
5570     case BuiltinType::UChar:
5571       ResType = llvm::ScalableVectorType::get(
5572           llvm::Type::getInt8Ty(getVMContext()), 16);
5573       break;
5574     case BuiltinType::Short:
5575     case BuiltinType::UShort:
5576       ResType = llvm::ScalableVectorType::get(
5577           llvm::Type::getInt16Ty(getVMContext()), 8);
5578       break;
5579     case BuiltinType::Int:
5580     case BuiltinType::UInt:
5581       ResType = llvm::ScalableVectorType::get(
5582           llvm::Type::getInt32Ty(getVMContext()), 4);
5583       break;
5584     case BuiltinType::Long:
5585     case BuiltinType::ULong:
5586       ResType = llvm::ScalableVectorType::get(
5587           llvm::Type::getInt64Ty(getVMContext()), 2);
5588       break;
5589     case BuiltinType::Half:
5590       ResType = llvm::ScalableVectorType::get(
5591           llvm::Type::getHalfTy(getVMContext()), 8);
5592       break;
5593     case BuiltinType::Float:
5594       ResType = llvm::ScalableVectorType::get(
5595           llvm::Type::getFloatTy(getVMContext()), 4);
5596       break;
5597     case BuiltinType::Double:
5598       ResType = llvm::ScalableVectorType::get(
5599           llvm::Type::getDoubleTy(getVMContext()), 2);
5600       break;
5601     case BuiltinType::BFloat16:
5602       ResType = llvm::ScalableVectorType::get(
5603           llvm::Type::getBFloatTy(getVMContext()), 8);
5604       break;
5605     }
5606     return ABIArgInfo::getDirect(ResType);
5607   }
5608 
5609   uint64_t Size = getContext().getTypeSize(Ty);
5610   // Android promotes <2 x i8> to i16, not i32
5611   if (isAndroid() && (Size <= 16)) {
5612     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5613     return ABIArgInfo::getDirect(ResType);
5614   }
5615   if (Size <= 32) {
5616     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5617     return ABIArgInfo::getDirect(ResType);
5618   }
5619   if (Size == 64) {
5620     auto *ResType =
5621         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5622     return ABIArgInfo::getDirect(ResType);
5623   }
5624   if (Size == 128) {
5625     auto *ResType =
5626         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5627     return ABIArgInfo::getDirect(ResType);
5628   }
5629   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5630 }
5631 
5632 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5633   Ty = useFirstFieldIfTransparentUnion(Ty);
5634 
5635   // Handle illegal vector types here.
5636   if (isIllegalVectorType(Ty))
5637     return coerceIllegalVector(Ty);
5638 
5639   if (!isAggregateTypeForABI(Ty)) {
5640     // Treat an enum type as its underlying type.
5641     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5642       Ty = EnumTy->getDecl()->getIntegerType();
5643 
5644     if (const auto *EIT = Ty->getAs<ExtIntType>())
5645       if (EIT->getNumBits() > 128)
5646         return getNaturalAlignIndirect(Ty);
5647 
5648     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5649                 ? ABIArgInfo::getExtend(Ty)
5650                 : ABIArgInfo::getDirect());
5651   }
5652 
5653   // Structures with either a non-trivial destructor or a non-trivial
5654   // copy constructor are always indirect.
5655   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5656     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5657                                      CGCXXABI::RAA_DirectInMemory);
5658   }
5659 
5660   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5661   // elsewhere for GNU compatibility.
5662   uint64_t Size = getContext().getTypeSize(Ty);
5663   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5664   if (IsEmpty || Size == 0) {
5665     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5666       return ABIArgInfo::getIgnore();
5667 
5668     // GNU C mode. The only argument that gets ignored is an empty one with size
5669     // 0.
5670     if (IsEmpty && Size == 0)
5671       return ABIArgInfo::getIgnore();
5672     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5673   }
5674 
5675   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5676   const Type *Base = nullptr;
5677   uint64_t Members = 0;
5678   if (isHomogeneousAggregate(Ty, Base, Members)) {
5679     return ABIArgInfo::getDirect(
5680         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5681   }
5682 
5683   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5684   if (Size <= 128) {
5685     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5686     // same size and alignment.
5687     if (getTarget().isRenderScriptTarget()) {
5688       return coerceToIntArray(Ty, getContext(), getVMContext());
5689     }
5690     unsigned Alignment;
5691     if (Kind == AArch64ABIInfo::AAPCS) {
5692       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5693       Alignment = Alignment < 128 ? 64 : 128;
5694     } else {
5695       Alignment = std::max(getContext().getTypeAlign(Ty),
5696                            (unsigned)getTarget().getPointerWidth(0));
5697     }
5698     Size = llvm::alignTo(Size, Alignment);
5699 
5700     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5701     // For aggregates with 16-byte alignment, we use i128.
5702     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5703     return ABIArgInfo::getDirect(
5704         Size == Alignment ? BaseTy
5705                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5706   }
5707 
5708   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5709 }
5710 
5711 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5712                                               bool IsVariadic) const {
5713   if (RetTy->isVoidType())
5714     return ABIArgInfo::getIgnore();
5715 
5716   if (const auto *VT = RetTy->getAs<VectorType>()) {
5717     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5718         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5719       return coerceIllegalVector(RetTy);
5720   }
5721 
5722   // Large vector types should be returned via memory.
5723   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5724     return getNaturalAlignIndirect(RetTy);
5725 
5726   if (!isAggregateTypeForABI(RetTy)) {
5727     // Treat an enum type as its underlying type.
5728     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5729       RetTy = EnumTy->getDecl()->getIntegerType();
5730 
5731     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5732       if (EIT->getNumBits() > 128)
5733         return getNaturalAlignIndirect(RetTy);
5734 
5735     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5736                 ? ABIArgInfo::getExtend(RetTy)
5737                 : ABIArgInfo::getDirect());
5738   }
5739 
5740   uint64_t Size = getContext().getTypeSize(RetTy);
5741   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5742     return ABIArgInfo::getIgnore();
5743 
5744   const Type *Base = nullptr;
5745   uint64_t Members = 0;
5746   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5747       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5748         IsVariadic))
5749     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5750     return ABIArgInfo::getDirect();
5751 
5752   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5753   if (Size <= 128) {
5754     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5755     // same size and alignment.
5756     if (getTarget().isRenderScriptTarget()) {
5757       return coerceToIntArray(RetTy, getContext(), getVMContext());
5758     }
5759     unsigned Alignment = getContext().getTypeAlign(RetTy);
5760     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5761 
5762     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5763     // For aggregates with 16-byte alignment, we use i128.
5764     if (Alignment < 128 && Size == 128) {
5765       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5766       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5767     }
5768     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5769   }
5770 
5771   return getNaturalAlignIndirect(RetTy);
5772 }
5773 
5774 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5775 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5776   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5777     // Check whether VT is a fixed-length SVE vector. These types are
5778     // represented as scalable vectors in function args/return and must be
5779     // coerced from fixed vectors.
5780     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5781         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5782       return true;
5783 
5784     // Check whether VT is legal.
5785     unsigned NumElements = VT->getNumElements();
5786     uint64_t Size = getContext().getTypeSize(VT);
5787     // NumElements should be power of 2.
5788     if (!llvm::isPowerOf2_32(NumElements))
5789       return true;
5790 
5791     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5792     // vectors for some reason.
5793     llvm::Triple Triple = getTarget().getTriple();
5794     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5795         Triple.isOSBinFormatMachO())
5796       return Size <= 32;
5797 
5798     return Size != 64 && (Size != 128 || NumElements == 1);
5799   }
5800   return false;
5801 }
5802 
5803 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5804                                                llvm::Type *eltTy,
5805                                                unsigned elts) const {
5806   if (!llvm::isPowerOf2_32(elts))
5807     return false;
5808   if (totalSize.getQuantity() != 8 &&
5809       (totalSize.getQuantity() != 16 || elts == 1))
5810     return false;
5811   return true;
5812 }
5813 
5814 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5815   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5816   // point type or a short-vector type. This is the same as the 32-bit ABI,
5817   // but with the difference that any floating-point type is allowed,
5818   // including __fp16.
5819   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5820     if (BT->isFloatingPoint())
5821       return true;
5822   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5823     unsigned VecSize = getContext().getTypeSize(VT);
5824     if (VecSize == 64 || VecSize == 128)
5825       return true;
5826   }
5827   return false;
5828 }
5829 
5830 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5831                                                        uint64_t Members) const {
5832   return Members <= 4;
5833 }
5834 
5835 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5836                                             QualType Ty,
5837                                             CodeGenFunction &CGF) const {
5838   ABIArgInfo AI = classifyArgumentType(Ty);
5839   bool IsIndirect = AI.isIndirect();
5840 
5841   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5842   if (IsIndirect)
5843     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5844   else if (AI.getCoerceToType())
5845     BaseTy = AI.getCoerceToType();
5846 
5847   unsigned NumRegs = 1;
5848   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5849     BaseTy = ArrTy->getElementType();
5850     NumRegs = ArrTy->getNumElements();
5851   }
5852   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5853 
5854   // The AArch64 va_list type and handling is specified in the Procedure Call
5855   // Standard, section B.4:
5856   //
5857   // struct {
5858   //   void *__stack;
5859   //   void *__gr_top;
5860   //   void *__vr_top;
5861   //   int __gr_offs;
5862   //   int __vr_offs;
5863   // };
5864 
5865   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5866   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5867   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5868   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5869 
5870   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5871   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5872 
5873   Address reg_offs_p = Address::invalid();
5874   llvm::Value *reg_offs = nullptr;
5875   int reg_top_index;
5876   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5877   if (!IsFPR) {
5878     // 3 is the field number of __gr_offs
5879     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5880     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5881     reg_top_index = 1; // field number for __gr_top
5882     RegSize = llvm::alignTo(RegSize, 8);
5883   } else {
5884     // 4 is the field number of __vr_offs.
5885     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5886     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5887     reg_top_index = 2; // field number for __vr_top
5888     RegSize = 16 * NumRegs;
5889   }
5890 
5891   //=======================================
5892   // Find out where argument was passed
5893   //=======================================
5894 
5895   // If reg_offs >= 0 we're already using the stack for this type of
5896   // argument. We don't want to keep updating reg_offs (in case it overflows,
5897   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5898   // whatever they get).
5899   llvm::Value *UsingStack = nullptr;
5900   UsingStack = CGF.Builder.CreateICmpSGE(
5901       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5902 
5903   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5904 
5905   // Otherwise, at least some kind of argument could go in these registers, the
5906   // question is whether this particular type is too big.
5907   CGF.EmitBlock(MaybeRegBlock);
5908 
5909   // Integer arguments may need to correct register alignment (for example a
5910   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5911   // align __gr_offs to calculate the potential address.
5912   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5913     int Align = TyAlign.getQuantity();
5914 
5915     reg_offs = CGF.Builder.CreateAdd(
5916         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5917         "align_regoffs");
5918     reg_offs = CGF.Builder.CreateAnd(
5919         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5920         "aligned_regoffs");
5921   }
5922 
5923   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5924   // The fact that this is done unconditionally reflects the fact that
5925   // allocating an argument to the stack also uses up all the remaining
5926   // registers of the appropriate kind.
5927   llvm::Value *NewOffset = nullptr;
5928   NewOffset = CGF.Builder.CreateAdd(
5929       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5930   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5931 
5932   // Now we're in a position to decide whether this argument really was in
5933   // registers or not.
5934   llvm::Value *InRegs = nullptr;
5935   InRegs = CGF.Builder.CreateICmpSLE(
5936       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5937 
5938   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5939 
5940   //=======================================
5941   // Argument was in registers
5942   //=======================================
5943 
5944   // Now we emit the code for if the argument was originally passed in
5945   // registers. First start the appropriate block:
5946   CGF.EmitBlock(InRegBlock);
5947 
5948   llvm::Value *reg_top = nullptr;
5949   Address reg_top_p =
5950       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5951   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5952   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5953                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5954   Address RegAddr = Address::invalid();
5955   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5956 
5957   if (IsIndirect) {
5958     // If it's been passed indirectly (actually a struct), whatever we find from
5959     // stored registers or on the stack will actually be a struct **.
5960     MemTy = llvm::PointerType::getUnqual(MemTy);
5961   }
5962 
5963   const Type *Base = nullptr;
5964   uint64_t NumMembers = 0;
5965   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5966   if (IsHFA && NumMembers > 1) {
5967     // Homogeneous aggregates passed in registers will have their elements split
5968     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5969     // qN+1, ...). We reload and store into a temporary local variable
5970     // contiguously.
5971     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5972     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5973     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5974     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5975     Address Tmp = CGF.CreateTempAlloca(HFATy,
5976                                        std::max(TyAlign, BaseTyInfo.Align));
5977 
5978     // On big-endian platforms, the value will be right-aligned in its slot.
5979     int Offset = 0;
5980     if (CGF.CGM.getDataLayout().isBigEndian() &&
5981         BaseTyInfo.Width.getQuantity() < 16)
5982       Offset = 16 - BaseTyInfo.Width.getQuantity();
5983 
5984     for (unsigned i = 0; i < NumMembers; ++i) {
5985       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5986       Address LoadAddr =
5987         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5988       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5989 
5990       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5991 
5992       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5993       CGF.Builder.CreateStore(Elem, StoreAddr);
5994     }
5995 
5996     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5997   } else {
5998     // Otherwise the object is contiguous in memory.
5999 
6000     // It might be right-aligned in its slot.
6001     CharUnits SlotSize = BaseAddr.getAlignment();
6002     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6003         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6004         TySize < SlotSize) {
6005       CharUnits Offset = SlotSize - TySize;
6006       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6007     }
6008 
6009     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6010   }
6011 
6012   CGF.EmitBranch(ContBlock);
6013 
6014   //=======================================
6015   // Argument was on the stack
6016   //=======================================
6017   CGF.EmitBlock(OnStackBlock);
6018 
6019   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6020   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6021 
6022   // Again, stack arguments may need realignment. In this case both integer and
6023   // floating-point ones might be affected.
6024   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6025     int Align = TyAlign.getQuantity();
6026 
6027     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6028 
6029     OnStackPtr = CGF.Builder.CreateAdd(
6030         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6031         "align_stack");
6032     OnStackPtr = CGF.Builder.CreateAnd(
6033         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6034         "align_stack");
6035 
6036     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6037   }
6038   Address OnStackAddr(OnStackPtr,
6039                       std::max(CharUnits::fromQuantity(8), TyAlign));
6040 
6041   // All stack slots are multiples of 8 bytes.
6042   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6043   CharUnits StackSize;
6044   if (IsIndirect)
6045     StackSize = StackSlotSize;
6046   else
6047     StackSize = TySize.alignTo(StackSlotSize);
6048 
6049   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6050   llvm::Value *NewStack =
6051       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6052 
6053   // Write the new value of __stack for the next call to va_arg
6054   CGF.Builder.CreateStore(NewStack, stack_p);
6055 
6056   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6057       TySize < StackSlotSize) {
6058     CharUnits Offset = StackSlotSize - TySize;
6059     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6060   }
6061 
6062   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6063 
6064   CGF.EmitBranch(ContBlock);
6065 
6066   //=======================================
6067   // Tidy up
6068   //=======================================
6069   CGF.EmitBlock(ContBlock);
6070 
6071   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6072                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6073 
6074   if (IsIndirect)
6075     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6076                    TyAlign);
6077 
6078   return ResAddr;
6079 }
6080 
6081 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6082                                         CodeGenFunction &CGF) const {
6083   // The backend's lowering doesn't support va_arg for aggregates or
6084   // illegal vector types.  Lower VAArg here for these cases and use
6085   // the LLVM va_arg instruction for everything else.
6086   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6087     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6088 
6089   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6090   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6091 
6092   // Empty records are ignored for parameter passing purposes.
6093   if (isEmptyRecord(getContext(), Ty, true)) {
6094     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6095     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6096     return Addr;
6097   }
6098 
6099   // The size of the actual thing passed, which might end up just
6100   // being a pointer for indirect types.
6101   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6102 
6103   // Arguments bigger than 16 bytes which aren't homogeneous
6104   // aggregates should be passed indirectly.
6105   bool IsIndirect = false;
6106   if (TyInfo.Width.getQuantity() > 16) {
6107     const Type *Base = nullptr;
6108     uint64_t Members = 0;
6109     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6110   }
6111 
6112   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6113                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6114 }
6115 
6116 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6117                                     QualType Ty) const {
6118   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6119                           CGF.getContext().getTypeInfoInChars(Ty),
6120                           CharUnits::fromQuantity(8),
6121                           /*allowHigherAlign*/ false);
6122 }
6123 
6124 //===----------------------------------------------------------------------===//
6125 // ARM ABI Implementation
6126 //===----------------------------------------------------------------------===//
6127 
6128 namespace {
6129 
6130 class ARMABIInfo : public SwiftABIInfo {
6131 public:
6132   enum ABIKind {
6133     APCS = 0,
6134     AAPCS = 1,
6135     AAPCS_VFP = 2,
6136     AAPCS16_VFP = 3,
6137   };
6138 
6139 private:
6140   ABIKind Kind;
6141   bool IsFloatABISoftFP;
6142 
6143 public:
6144   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6145       : SwiftABIInfo(CGT), Kind(_Kind) {
6146     setCCs();
6147     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6148         CGT.getCodeGenOpts().FloatABI == ""; // default
6149   }
6150 
6151   bool isEABI() const {
6152     switch (getTarget().getTriple().getEnvironment()) {
6153     case llvm::Triple::Android:
6154     case llvm::Triple::EABI:
6155     case llvm::Triple::EABIHF:
6156     case llvm::Triple::GNUEABI:
6157     case llvm::Triple::GNUEABIHF:
6158     case llvm::Triple::MuslEABI:
6159     case llvm::Triple::MuslEABIHF:
6160       return true;
6161     default:
6162       return false;
6163     }
6164   }
6165 
6166   bool isEABIHF() const {
6167     switch (getTarget().getTriple().getEnvironment()) {
6168     case llvm::Triple::EABIHF:
6169     case llvm::Triple::GNUEABIHF:
6170     case llvm::Triple::MuslEABIHF:
6171       return true;
6172     default:
6173       return false;
6174     }
6175   }
6176 
6177   ABIKind getABIKind() const { return Kind; }
6178 
6179   bool allowBFloatArgsAndRet() const override {
6180     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6181   }
6182 
6183 private:
6184   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6185                                 unsigned functionCallConv) const;
6186   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6187                                   unsigned functionCallConv) const;
6188   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6189                                           uint64_t Members) const;
6190   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6191   bool isIllegalVectorType(QualType Ty) const;
6192   bool containsAnyFP16Vectors(QualType Ty) const;
6193 
6194   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6195   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6196                                          uint64_t Members) const override;
6197 
6198   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6199 
6200   void computeInfo(CGFunctionInfo &FI) const override;
6201 
6202   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6203                     QualType Ty) const override;
6204 
6205   llvm::CallingConv::ID getLLVMDefaultCC() const;
6206   llvm::CallingConv::ID getABIDefaultCC() const;
6207   void setCCs();
6208 
6209   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6210                                     bool asReturnValue) const override {
6211     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6212   }
6213   bool isSwiftErrorInRegister() const override {
6214     return true;
6215   }
6216   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6217                                  unsigned elts) const override;
6218 };
6219 
6220 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6221 public:
6222   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6223       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6224 
6225   const ARMABIInfo &getABIInfo() const {
6226     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6227   }
6228 
6229   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6230     return 13;
6231   }
6232 
6233   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6234     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6235   }
6236 
6237   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6238                                llvm::Value *Address) const override {
6239     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6240 
6241     // 0-15 are the 16 integer registers.
6242     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6243     return false;
6244   }
6245 
6246   unsigned getSizeOfUnwindException() const override {
6247     if (getABIInfo().isEABI()) return 88;
6248     return TargetCodeGenInfo::getSizeOfUnwindException();
6249   }
6250 
6251   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6252                            CodeGen::CodeGenModule &CGM) const override {
6253     if (GV->isDeclaration())
6254       return;
6255     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6256     if (!FD)
6257       return;
6258 
6259     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6260     if (!Attr)
6261       return;
6262 
6263     const char *Kind;
6264     switch (Attr->getInterrupt()) {
6265     case ARMInterruptAttr::Generic: Kind = ""; break;
6266     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6267     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6268     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6269     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6270     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6271     }
6272 
6273     llvm::Function *Fn = cast<llvm::Function>(GV);
6274 
6275     Fn->addFnAttr("interrupt", Kind);
6276 
6277     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6278     if (ABI == ARMABIInfo::APCS)
6279       return;
6280 
6281     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6282     // however this is not necessarily true on taking any interrupt. Instruct
6283     // the backend to perform a realignment as part of the function prologue.
6284     llvm::AttrBuilder B;
6285     B.addStackAlignmentAttr(8);
6286     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6287   }
6288 };
6289 
6290 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6291 public:
6292   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6293       : ARMTargetCodeGenInfo(CGT, K) {}
6294 
6295   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6296                            CodeGen::CodeGenModule &CGM) const override;
6297 
6298   void getDependentLibraryOption(llvm::StringRef Lib,
6299                                  llvm::SmallString<24> &Opt) const override {
6300     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6301   }
6302 
6303   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6304                                llvm::SmallString<32> &Opt) const override {
6305     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6306   }
6307 };
6308 
6309 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6310     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6311   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6312   if (GV->isDeclaration())
6313     return;
6314   addStackProbeTargetAttributes(D, GV, CGM);
6315 }
6316 }
6317 
6318 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6319   if (!::classifyReturnType(getCXXABI(), FI, *this))
6320     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6321                                             FI.getCallingConvention());
6322 
6323   for (auto &I : FI.arguments())
6324     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6325                                   FI.getCallingConvention());
6326 
6327 
6328   // Always honor user-specified calling convention.
6329   if (FI.getCallingConvention() != llvm::CallingConv::C)
6330     return;
6331 
6332   llvm::CallingConv::ID cc = getRuntimeCC();
6333   if (cc != llvm::CallingConv::C)
6334     FI.setEffectiveCallingConvention(cc);
6335 }
6336 
6337 /// Return the default calling convention that LLVM will use.
6338 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6339   // The default calling convention that LLVM will infer.
6340   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6341     return llvm::CallingConv::ARM_AAPCS_VFP;
6342   else if (isEABI())
6343     return llvm::CallingConv::ARM_AAPCS;
6344   else
6345     return llvm::CallingConv::ARM_APCS;
6346 }
6347 
6348 /// Return the calling convention that our ABI would like us to use
6349 /// as the C calling convention.
6350 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6351   switch (getABIKind()) {
6352   case APCS: return llvm::CallingConv::ARM_APCS;
6353   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6354   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6355   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6356   }
6357   llvm_unreachable("bad ABI kind");
6358 }
6359 
6360 void ARMABIInfo::setCCs() {
6361   assert(getRuntimeCC() == llvm::CallingConv::C);
6362 
6363   // Don't muddy up the IR with a ton of explicit annotations if
6364   // they'd just match what LLVM will infer from the triple.
6365   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6366   if (abiCC != getLLVMDefaultCC())
6367     RuntimeCC = abiCC;
6368 }
6369 
6370 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6371   uint64_t Size = getContext().getTypeSize(Ty);
6372   if (Size <= 32) {
6373     llvm::Type *ResType =
6374         llvm::Type::getInt32Ty(getVMContext());
6375     return ABIArgInfo::getDirect(ResType);
6376   }
6377   if (Size == 64 || Size == 128) {
6378     auto *ResType = llvm::FixedVectorType::get(
6379         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6380     return ABIArgInfo::getDirect(ResType);
6381   }
6382   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6383 }
6384 
6385 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6386                                                     const Type *Base,
6387                                                     uint64_t Members) const {
6388   assert(Base && "Base class should be set for homogeneous aggregate");
6389   // Base can be a floating-point or a vector.
6390   if (const VectorType *VT = Base->getAs<VectorType>()) {
6391     // FP16 vectors should be converted to integer vectors
6392     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6393       uint64_t Size = getContext().getTypeSize(VT);
6394       auto *NewVecTy = llvm::FixedVectorType::get(
6395           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6396       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6397       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6398     }
6399   }
6400   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6401 }
6402 
6403 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6404                                             unsigned functionCallConv) const {
6405   // 6.1.2.1 The following argument types are VFP CPRCs:
6406   //   A single-precision floating-point type (including promoted
6407   //   half-precision types); A double-precision floating-point type;
6408   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6409   //   with a Base Type of a single- or double-precision floating-point type,
6410   //   64-bit containerized vectors or 128-bit containerized vectors with one
6411   //   to four Elements.
6412   // Variadic functions should always marshal to the base standard.
6413   bool IsAAPCS_VFP =
6414       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6415 
6416   Ty = useFirstFieldIfTransparentUnion(Ty);
6417 
6418   // Handle illegal vector types here.
6419   if (isIllegalVectorType(Ty))
6420     return coerceIllegalVector(Ty);
6421 
6422   if (!isAggregateTypeForABI(Ty)) {
6423     // Treat an enum type as its underlying type.
6424     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6425       Ty = EnumTy->getDecl()->getIntegerType();
6426     }
6427 
6428     if (const auto *EIT = Ty->getAs<ExtIntType>())
6429       if (EIT->getNumBits() > 64)
6430         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6431 
6432     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6433                                               : ABIArgInfo::getDirect());
6434   }
6435 
6436   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6437     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6438   }
6439 
6440   // Ignore empty records.
6441   if (isEmptyRecord(getContext(), Ty, true))
6442     return ABIArgInfo::getIgnore();
6443 
6444   if (IsAAPCS_VFP) {
6445     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6446     // into VFP registers.
6447     const Type *Base = nullptr;
6448     uint64_t Members = 0;
6449     if (isHomogeneousAggregate(Ty, Base, Members))
6450       return classifyHomogeneousAggregate(Ty, Base, Members);
6451   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6452     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6453     // this convention even for a variadic function: the backend will use GPRs
6454     // if needed.
6455     const Type *Base = nullptr;
6456     uint64_t Members = 0;
6457     if (isHomogeneousAggregate(Ty, Base, Members)) {
6458       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6459       llvm::Type *Ty =
6460         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6461       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6462     }
6463   }
6464 
6465   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6466       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6467     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6468     // bigger than 128-bits, they get placed in space allocated by the caller,
6469     // and a pointer is passed.
6470     return ABIArgInfo::getIndirect(
6471         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6472   }
6473 
6474   // Support byval for ARM.
6475   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6476   // most 8-byte. We realign the indirect argument if type alignment is bigger
6477   // than ABI alignment.
6478   uint64_t ABIAlign = 4;
6479   uint64_t TyAlign;
6480   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6481       getABIKind() == ARMABIInfo::AAPCS) {
6482     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6483     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6484   } else {
6485     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6486   }
6487   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6488     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6489     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6490                                    /*ByVal=*/true,
6491                                    /*Realign=*/TyAlign > ABIAlign);
6492   }
6493 
6494   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6495   // same size and alignment.
6496   if (getTarget().isRenderScriptTarget()) {
6497     return coerceToIntArray(Ty, getContext(), getVMContext());
6498   }
6499 
6500   // Otherwise, pass by coercing to a structure of the appropriate size.
6501   llvm::Type* ElemTy;
6502   unsigned SizeRegs;
6503   // FIXME: Try to match the types of the arguments more accurately where
6504   // we can.
6505   if (TyAlign <= 4) {
6506     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6507     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6508   } else {
6509     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6510     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6511   }
6512 
6513   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6514 }
6515 
6516 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6517                               llvm::LLVMContext &VMContext) {
6518   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6519   // is called integer-like if its size is less than or equal to one word, and
6520   // the offset of each of its addressable sub-fields is zero.
6521 
6522   uint64_t Size = Context.getTypeSize(Ty);
6523 
6524   // Check that the type fits in a word.
6525   if (Size > 32)
6526     return false;
6527 
6528   // FIXME: Handle vector types!
6529   if (Ty->isVectorType())
6530     return false;
6531 
6532   // Float types are never treated as "integer like".
6533   if (Ty->isRealFloatingType())
6534     return false;
6535 
6536   // If this is a builtin or pointer type then it is ok.
6537   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6538     return true;
6539 
6540   // Small complex integer types are "integer like".
6541   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6542     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6543 
6544   // Single element and zero sized arrays should be allowed, by the definition
6545   // above, but they are not.
6546 
6547   // Otherwise, it must be a record type.
6548   const RecordType *RT = Ty->getAs<RecordType>();
6549   if (!RT) return false;
6550 
6551   // Ignore records with flexible arrays.
6552   const RecordDecl *RD = RT->getDecl();
6553   if (RD->hasFlexibleArrayMember())
6554     return false;
6555 
6556   // Check that all sub-fields are at offset 0, and are themselves "integer
6557   // like".
6558   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6559 
6560   bool HadField = false;
6561   unsigned idx = 0;
6562   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6563        i != e; ++i, ++idx) {
6564     const FieldDecl *FD = *i;
6565 
6566     // Bit-fields are not addressable, we only need to verify they are "integer
6567     // like". We still have to disallow a subsequent non-bitfield, for example:
6568     //   struct { int : 0; int x }
6569     // is non-integer like according to gcc.
6570     if (FD->isBitField()) {
6571       if (!RD->isUnion())
6572         HadField = true;
6573 
6574       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6575         return false;
6576 
6577       continue;
6578     }
6579 
6580     // Check if this field is at offset 0.
6581     if (Layout.getFieldOffset(idx) != 0)
6582       return false;
6583 
6584     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6585       return false;
6586 
6587     // Only allow at most one field in a structure. This doesn't match the
6588     // wording above, but follows gcc in situations with a field following an
6589     // empty structure.
6590     if (!RD->isUnion()) {
6591       if (HadField)
6592         return false;
6593 
6594       HadField = true;
6595     }
6596   }
6597 
6598   return true;
6599 }
6600 
6601 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6602                                           unsigned functionCallConv) const {
6603 
6604   // Variadic functions should always marshal to the base standard.
6605   bool IsAAPCS_VFP =
6606       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6607 
6608   if (RetTy->isVoidType())
6609     return ABIArgInfo::getIgnore();
6610 
6611   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6612     // Large vector types should be returned via memory.
6613     if (getContext().getTypeSize(RetTy) > 128)
6614       return getNaturalAlignIndirect(RetTy);
6615     // TODO: FP16/BF16 vectors should be converted to integer vectors
6616     // This check is similar  to isIllegalVectorType - refactor?
6617     if ((!getTarget().hasLegalHalfType() &&
6618         (VT->getElementType()->isFloat16Type() ||
6619          VT->getElementType()->isHalfType())) ||
6620         (IsFloatABISoftFP &&
6621          VT->getElementType()->isBFloat16Type()))
6622       return coerceIllegalVector(RetTy);
6623   }
6624 
6625   if (!isAggregateTypeForABI(RetTy)) {
6626     // Treat an enum type as its underlying type.
6627     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6628       RetTy = EnumTy->getDecl()->getIntegerType();
6629 
6630     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6631       if (EIT->getNumBits() > 64)
6632         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6633 
6634     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6635                                                 : ABIArgInfo::getDirect();
6636   }
6637 
6638   // Are we following APCS?
6639   if (getABIKind() == APCS) {
6640     if (isEmptyRecord(getContext(), RetTy, false))
6641       return ABIArgInfo::getIgnore();
6642 
6643     // Complex types are all returned as packed integers.
6644     //
6645     // FIXME: Consider using 2 x vector types if the back end handles them
6646     // correctly.
6647     if (RetTy->isAnyComplexType())
6648       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6649           getVMContext(), getContext().getTypeSize(RetTy)));
6650 
6651     // Integer like structures are returned in r0.
6652     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6653       // Return in the smallest viable integer type.
6654       uint64_t Size = getContext().getTypeSize(RetTy);
6655       if (Size <= 8)
6656         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6657       if (Size <= 16)
6658         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6659       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6660     }
6661 
6662     // Otherwise return in memory.
6663     return getNaturalAlignIndirect(RetTy);
6664   }
6665 
6666   // Otherwise this is an AAPCS variant.
6667 
6668   if (isEmptyRecord(getContext(), RetTy, true))
6669     return ABIArgInfo::getIgnore();
6670 
6671   // Check for homogeneous aggregates with AAPCS-VFP.
6672   if (IsAAPCS_VFP) {
6673     const Type *Base = nullptr;
6674     uint64_t Members = 0;
6675     if (isHomogeneousAggregate(RetTy, Base, Members))
6676       return classifyHomogeneousAggregate(RetTy, Base, Members);
6677   }
6678 
6679   // Aggregates <= 4 bytes are returned in r0; other aggregates
6680   // are returned indirectly.
6681   uint64_t Size = getContext().getTypeSize(RetTy);
6682   if (Size <= 32) {
6683     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6684     // same size and alignment.
6685     if (getTarget().isRenderScriptTarget()) {
6686       return coerceToIntArray(RetTy, getContext(), getVMContext());
6687     }
6688     if (getDataLayout().isBigEndian())
6689       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6690       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6691 
6692     // Return in the smallest viable integer type.
6693     if (Size <= 8)
6694       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6695     if (Size <= 16)
6696       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6697     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6698   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6699     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6700     llvm::Type *CoerceTy =
6701         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6702     return ABIArgInfo::getDirect(CoerceTy);
6703   }
6704 
6705   return getNaturalAlignIndirect(RetTy);
6706 }
6707 
6708 /// isIllegalVector - check whether Ty is an illegal vector type.
6709 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6710   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6711     // On targets that don't support half, fp16 or bfloat, they are expanded
6712     // into float, and we don't want the ABI to depend on whether or not they
6713     // are supported in hardware. Thus return false to coerce vectors of these
6714     // types into integer vectors.
6715     // We do not depend on hasLegalHalfType for bfloat as it is a
6716     // separate IR type.
6717     if ((!getTarget().hasLegalHalfType() &&
6718         (VT->getElementType()->isFloat16Type() ||
6719          VT->getElementType()->isHalfType())) ||
6720         (IsFloatABISoftFP &&
6721          VT->getElementType()->isBFloat16Type()))
6722       return true;
6723     if (isAndroid()) {
6724       // Android shipped using Clang 3.1, which supported a slightly different
6725       // vector ABI. The primary differences were that 3-element vector types
6726       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6727       // accepts that legacy behavior for Android only.
6728       // Check whether VT is legal.
6729       unsigned NumElements = VT->getNumElements();
6730       // NumElements should be power of 2 or equal to 3.
6731       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6732         return true;
6733     } else {
6734       // Check whether VT is legal.
6735       unsigned NumElements = VT->getNumElements();
6736       uint64_t Size = getContext().getTypeSize(VT);
6737       // NumElements should be power of 2.
6738       if (!llvm::isPowerOf2_32(NumElements))
6739         return true;
6740       // Size should be greater than 32 bits.
6741       return Size <= 32;
6742     }
6743   }
6744   return false;
6745 }
6746 
6747 /// Return true if a type contains any 16-bit floating point vectors
6748 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6749   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6750     uint64_t NElements = AT->getSize().getZExtValue();
6751     if (NElements == 0)
6752       return false;
6753     return containsAnyFP16Vectors(AT->getElementType());
6754   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6755     const RecordDecl *RD = RT->getDecl();
6756 
6757     // If this is a C++ record, check the bases first.
6758     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6759       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6760             return containsAnyFP16Vectors(B.getType());
6761           }))
6762         return true;
6763 
6764     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6765           return FD && containsAnyFP16Vectors(FD->getType());
6766         }))
6767       return true;
6768 
6769     return false;
6770   } else {
6771     if (const VectorType *VT = Ty->getAs<VectorType>())
6772       return (VT->getElementType()->isFloat16Type() ||
6773               VT->getElementType()->isBFloat16Type() ||
6774               VT->getElementType()->isHalfType());
6775     return false;
6776   }
6777 }
6778 
6779 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6780                                            llvm::Type *eltTy,
6781                                            unsigned numElts) const {
6782   if (!llvm::isPowerOf2_32(numElts))
6783     return false;
6784   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6785   if (size > 64)
6786     return false;
6787   if (vectorSize.getQuantity() != 8 &&
6788       (vectorSize.getQuantity() != 16 || numElts == 1))
6789     return false;
6790   return true;
6791 }
6792 
6793 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6794   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6795   // double, or 64-bit or 128-bit vectors.
6796   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6797     if (BT->getKind() == BuiltinType::Float ||
6798         BT->getKind() == BuiltinType::Double ||
6799         BT->getKind() == BuiltinType::LongDouble)
6800       return true;
6801   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6802     unsigned VecSize = getContext().getTypeSize(VT);
6803     if (VecSize == 64 || VecSize == 128)
6804       return true;
6805   }
6806   return false;
6807 }
6808 
6809 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6810                                                    uint64_t Members) const {
6811   return Members <= 4;
6812 }
6813 
6814 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6815                                         bool acceptHalf) const {
6816   // Give precedence to user-specified calling conventions.
6817   if (callConvention != llvm::CallingConv::C)
6818     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6819   else
6820     return (getABIKind() == AAPCS_VFP) ||
6821            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6822 }
6823 
6824 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6825                               QualType Ty) const {
6826   CharUnits SlotSize = CharUnits::fromQuantity(4);
6827 
6828   // Empty records are ignored for parameter passing purposes.
6829   if (isEmptyRecord(getContext(), Ty, true)) {
6830     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6831     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6832     return Addr;
6833   }
6834 
6835   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6836   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6837 
6838   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6839   bool IsIndirect = false;
6840   const Type *Base = nullptr;
6841   uint64_t Members = 0;
6842   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6843     IsIndirect = true;
6844 
6845   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6846   // allocated by the caller.
6847   } else if (TySize > CharUnits::fromQuantity(16) &&
6848              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6849              !isHomogeneousAggregate(Ty, Base, Members)) {
6850     IsIndirect = true;
6851 
6852   // Otherwise, bound the type's ABI alignment.
6853   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6854   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6855   // Our callers should be prepared to handle an under-aligned address.
6856   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6857              getABIKind() == ARMABIInfo::AAPCS) {
6858     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6859     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6860   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6861     // ARMv7k allows type alignment up to 16 bytes.
6862     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6863     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6864   } else {
6865     TyAlignForABI = CharUnits::fromQuantity(4);
6866   }
6867 
6868   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6869   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6870                           SlotSize, /*AllowHigherAlign*/ true);
6871 }
6872 
6873 //===----------------------------------------------------------------------===//
6874 // NVPTX ABI Implementation
6875 //===----------------------------------------------------------------------===//
6876 
6877 namespace {
6878 
6879 class NVPTXTargetCodeGenInfo;
6880 
6881 class NVPTXABIInfo : public ABIInfo {
6882   NVPTXTargetCodeGenInfo &CGInfo;
6883 
6884 public:
6885   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6886       : ABIInfo(CGT), CGInfo(Info) {}
6887 
6888   ABIArgInfo classifyReturnType(QualType RetTy) const;
6889   ABIArgInfo classifyArgumentType(QualType Ty) const;
6890 
6891   void computeInfo(CGFunctionInfo &FI) const override;
6892   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6893                     QualType Ty) const override;
6894   bool isUnsupportedType(QualType T) const;
6895   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6896 };
6897 
6898 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6899 public:
6900   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6901       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6902 
6903   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6904                            CodeGen::CodeGenModule &M) const override;
6905   bool shouldEmitStaticExternCAliases() const override;
6906 
6907   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6908     // On the device side, surface reference is represented as an object handle
6909     // in 64-bit integer.
6910     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6911   }
6912 
6913   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6914     // On the device side, texture reference is represented as an object handle
6915     // in 64-bit integer.
6916     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6917   }
6918 
6919   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6920                                               LValue Src) const override {
6921     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6922     return true;
6923   }
6924 
6925   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6926                                               LValue Src) const override {
6927     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6928     return true;
6929   }
6930 
6931 private:
6932   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6933   // resulting MDNode to the nvvm.annotations MDNode.
6934   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6935                               int Operand);
6936 
6937   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6938                                            LValue Src) {
6939     llvm::Value *Handle = nullptr;
6940     llvm::Constant *C =
6941         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6942     // Lookup `addrspacecast` through the constant pointer if any.
6943     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6944       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6945     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6946       // Load the handle from the specific global variable using
6947       // `nvvm.texsurf.handle.internal` intrinsic.
6948       Handle = CGF.EmitRuntimeCall(
6949           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6950                                {GV->getType()}),
6951           {GV}, "texsurf_handle");
6952     } else
6953       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6954     CGF.EmitStoreOfScalar(Handle, Dst);
6955   }
6956 };
6957 
6958 /// Checks if the type is unsupported directly by the current target.
6959 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6960   ASTContext &Context = getContext();
6961   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6962     return true;
6963   if (!Context.getTargetInfo().hasFloat128Type() &&
6964       (T->isFloat128Type() ||
6965        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6966     return true;
6967   if (const auto *EIT = T->getAs<ExtIntType>())
6968     return EIT->getNumBits() >
6969            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6970   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6971       Context.getTypeSize(T) > 64U)
6972     return true;
6973   if (const auto *AT = T->getAsArrayTypeUnsafe())
6974     return isUnsupportedType(AT->getElementType());
6975   const auto *RT = T->getAs<RecordType>();
6976   if (!RT)
6977     return false;
6978   const RecordDecl *RD = RT->getDecl();
6979 
6980   // If this is a C++ record, check the bases first.
6981   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6982     for (const CXXBaseSpecifier &I : CXXRD->bases())
6983       if (isUnsupportedType(I.getType()))
6984         return true;
6985 
6986   for (const FieldDecl *I : RD->fields())
6987     if (isUnsupportedType(I->getType()))
6988       return true;
6989   return false;
6990 }
6991 
6992 /// Coerce the given type into an array with maximum allowed size of elements.
6993 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6994                                                    unsigned MaxSize) const {
6995   // Alignment and Size are measured in bits.
6996   const uint64_t Size = getContext().getTypeSize(Ty);
6997   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6998   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6999   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7000   const uint64_t NumElements = (Size + Div - 1) / Div;
7001   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7002 }
7003 
7004 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7005   if (RetTy->isVoidType())
7006     return ABIArgInfo::getIgnore();
7007 
7008   if (getContext().getLangOpts().OpenMP &&
7009       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7010     return coerceToIntArrayWithLimit(RetTy, 64);
7011 
7012   // note: this is different from default ABI
7013   if (!RetTy->isScalarType())
7014     return ABIArgInfo::getDirect();
7015 
7016   // Treat an enum type as its underlying type.
7017   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7018     RetTy = EnumTy->getDecl()->getIntegerType();
7019 
7020   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7021                                                : ABIArgInfo::getDirect());
7022 }
7023 
7024 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7025   // Treat an enum type as its underlying type.
7026   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7027     Ty = EnumTy->getDecl()->getIntegerType();
7028 
7029   // Return aggregates type as indirect by value
7030   if (isAggregateTypeForABI(Ty)) {
7031     // Under CUDA device compilation, tex/surf builtin types are replaced with
7032     // object types and passed directly.
7033     if (getContext().getLangOpts().CUDAIsDevice) {
7034       if (Ty->isCUDADeviceBuiltinSurfaceType())
7035         return ABIArgInfo::getDirect(
7036             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7037       if (Ty->isCUDADeviceBuiltinTextureType())
7038         return ABIArgInfo::getDirect(
7039             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7040     }
7041     return getNaturalAlignIndirect(Ty, /* byval */ true);
7042   }
7043 
7044   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7045     if ((EIT->getNumBits() > 128) ||
7046         (!getContext().getTargetInfo().hasInt128Type() &&
7047          EIT->getNumBits() > 64))
7048       return getNaturalAlignIndirect(Ty, /* byval */ true);
7049   }
7050 
7051   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7052                                             : ABIArgInfo::getDirect());
7053 }
7054 
7055 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7056   if (!getCXXABI().classifyReturnType(FI))
7057     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7058   for (auto &I : FI.arguments())
7059     I.info = classifyArgumentType(I.type);
7060 
7061   // Always honor user-specified calling convention.
7062   if (FI.getCallingConvention() != llvm::CallingConv::C)
7063     return;
7064 
7065   FI.setEffectiveCallingConvention(getRuntimeCC());
7066 }
7067 
7068 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7069                                 QualType Ty) const {
7070   llvm_unreachable("NVPTX does not support varargs");
7071 }
7072 
7073 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7074     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7075   if (GV->isDeclaration())
7076     return;
7077   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7078   if (VD) {
7079     if (M.getLangOpts().CUDA) {
7080       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7081         addNVVMMetadata(GV, "surface", 1);
7082       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7083         addNVVMMetadata(GV, "texture", 1);
7084       return;
7085     }
7086   }
7087 
7088   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7089   if (!FD) return;
7090 
7091   llvm::Function *F = cast<llvm::Function>(GV);
7092 
7093   // Perform special handling in OpenCL mode
7094   if (M.getLangOpts().OpenCL) {
7095     // Use OpenCL function attributes to check for kernel functions
7096     // By default, all functions are device functions
7097     if (FD->hasAttr<OpenCLKernelAttr>()) {
7098       // OpenCL __kernel functions get kernel metadata
7099       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7100       addNVVMMetadata(F, "kernel", 1);
7101       // And kernel functions are not subject to inlining
7102       F->addFnAttr(llvm::Attribute::NoInline);
7103     }
7104   }
7105 
7106   // Perform special handling in CUDA mode.
7107   if (M.getLangOpts().CUDA) {
7108     // CUDA __global__ functions get a kernel metadata entry.  Since
7109     // __global__ functions cannot be called from the device, we do not
7110     // need to set the noinline attribute.
7111     if (FD->hasAttr<CUDAGlobalAttr>()) {
7112       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7113       addNVVMMetadata(F, "kernel", 1);
7114     }
7115     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7116       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7117       llvm::APSInt MaxThreads(32);
7118       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7119       if (MaxThreads > 0)
7120         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7121 
7122       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7123       // not specified in __launch_bounds__ or if the user specified a 0 value,
7124       // we don't have to add a PTX directive.
7125       if (Attr->getMinBlocks()) {
7126         llvm::APSInt MinBlocks(32);
7127         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7128         if (MinBlocks > 0)
7129           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7130           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7131       }
7132     }
7133   }
7134 }
7135 
7136 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7137                                              StringRef Name, int Operand) {
7138   llvm::Module *M = GV->getParent();
7139   llvm::LLVMContext &Ctx = M->getContext();
7140 
7141   // Get "nvvm.annotations" metadata node
7142   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7143 
7144   llvm::Metadata *MDVals[] = {
7145       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7146       llvm::ConstantAsMetadata::get(
7147           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7148   // Append metadata to nvvm.annotations
7149   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7150 }
7151 
7152 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7153   return false;
7154 }
7155 }
7156 
7157 //===----------------------------------------------------------------------===//
7158 // SystemZ ABI Implementation
7159 //===----------------------------------------------------------------------===//
7160 
7161 namespace {
7162 
7163 class SystemZABIInfo : public SwiftABIInfo {
7164   bool HasVector;
7165   bool IsSoftFloatABI;
7166 
7167 public:
7168   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7169     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7170 
7171   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7172   bool isCompoundType(QualType Ty) const;
7173   bool isVectorArgumentType(QualType Ty) const;
7174   bool isFPArgumentType(QualType Ty) const;
7175   QualType GetSingleElementType(QualType Ty) const;
7176 
7177   ABIArgInfo classifyReturnType(QualType RetTy) const;
7178   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7179 
7180   void computeInfo(CGFunctionInfo &FI) const override {
7181     if (!getCXXABI().classifyReturnType(FI))
7182       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7183     for (auto &I : FI.arguments())
7184       I.info = classifyArgumentType(I.type);
7185   }
7186 
7187   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7188                     QualType Ty) const override;
7189 
7190   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7191                                     bool asReturnValue) const override {
7192     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7193   }
7194   bool isSwiftErrorInRegister() const override {
7195     return false;
7196   }
7197 };
7198 
7199 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7200 public:
7201   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7202       : TargetCodeGenInfo(
7203             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7204 };
7205 
7206 }
7207 
7208 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7209   // Treat an enum type as its underlying type.
7210   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7211     Ty = EnumTy->getDecl()->getIntegerType();
7212 
7213   // Promotable integer types are required to be promoted by the ABI.
7214   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7215     return true;
7216 
7217   if (const auto *EIT = Ty->getAs<ExtIntType>())
7218     if (EIT->getNumBits() < 64)
7219       return true;
7220 
7221   // 32-bit values must also be promoted.
7222   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7223     switch (BT->getKind()) {
7224     case BuiltinType::Int:
7225     case BuiltinType::UInt:
7226       return true;
7227     default:
7228       return false;
7229     }
7230   return false;
7231 }
7232 
7233 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7234   return (Ty->isAnyComplexType() ||
7235           Ty->isVectorType() ||
7236           isAggregateTypeForABI(Ty));
7237 }
7238 
7239 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7240   return (HasVector &&
7241           Ty->isVectorType() &&
7242           getContext().getTypeSize(Ty) <= 128);
7243 }
7244 
7245 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7246   if (IsSoftFloatABI)
7247     return false;
7248 
7249   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7250     switch (BT->getKind()) {
7251     case BuiltinType::Float:
7252     case BuiltinType::Double:
7253       return true;
7254     default:
7255       return false;
7256     }
7257 
7258   return false;
7259 }
7260 
7261 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7262   const RecordType *RT = Ty->getAs<RecordType>();
7263 
7264   if (RT && RT->isStructureOrClassType()) {
7265     const RecordDecl *RD = RT->getDecl();
7266     QualType Found;
7267 
7268     // If this is a C++ record, check the bases first.
7269     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7270       for (const auto &I : CXXRD->bases()) {
7271         QualType Base = I.getType();
7272 
7273         // Empty bases don't affect things either way.
7274         if (isEmptyRecord(getContext(), Base, true))
7275           continue;
7276 
7277         if (!Found.isNull())
7278           return Ty;
7279         Found = GetSingleElementType(Base);
7280       }
7281 
7282     // Check the fields.
7283     for (const auto *FD : RD->fields()) {
7284       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7285       // Unlike isSingleElementStruct(), empty structure and array fields
7286       // do count.  So do anonymous bitfields that aren't zero-sized.
7287       if (getContext().getLangOpts().CPlusPlus &&
7288           FD->isZeroLengthBitField(getContext()))
7289         continue;
7290       // Like isSingleElementStruct(), ignore C++20 empty data members.
7291       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7292           isEmptyRecord(getContext(), FD->getType(), true))
7293         continue;
7294 
7295       // Unlike isSingleElementStruct(), arrays do not count.
7296       // Nested structures still do though.
7297       if (!Found.isNull())
7298         return Ty;
7299       Found = GetSingleElementType(FD->getType());
7300     }
7301 
7302     // Unlike isSingleElementStruct(), trailing padding is allowed.
7303     // An 8-byte aligned struct s { float f; } is passed as a double.
7304     if (!Found.isNull())
7305       return Found;
7306   }
7307 
7308   return Ty;
7309 }
7310 
7311 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7312                                   QualType Ty) const {
7313   // Assume that va_list type is correct; should be pointer to LLVM type:
7314   // struct {
7315   //   i64 __gpr;
7316   //   i64 __fpr;
7317   //   i8 *__overflow_arg_area;
7318   //   i8 *__reg_save_area;
7319   // };
7320 
7321   // Every non-vector argument occupies 8 bytes and is passed by preference
7322   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7323   // always passed on the stack.
7324   Ty = getContext().getCanonicalType(Ty);
7325   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7326   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7327   llvm::Type *DirectTy = ArgTy;
7328   ABIArgInfo AI = classifyArgumentType(Ty);
7329   bool IsIndirect = AI.isIndirect();
7330   bool InFPRs = false;
7331   bool IsVector = false;
7332   CharUnits UnpaddedSize;
7333   CharUnits DirectAlign;
7334   if (IsIndirect) {
7335     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7336     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7337   } else {
7338     if (AI.getCoerceToType())
7339       ArgTy = AI.getCoerceToType();
7340     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7341     IsVector = ArgTy->isVectorTy();
7342     UnpaddedSize = TyInfo.Width;
7343     DirectAlign = TyInfo.Align;
7344   }
7345   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7346   if (IsVector && UnpaddedSize > PaddedSize)
7347     PaddedSize = CharUnits::fromQuantity(16);
7348   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7349 
7350   CharUnits Padding = (PaddedSize - UnpaddedSize);
7351 
7352   llvm::Type *IndexTy = CGF.Int64Ty;
7353   llvm::Value *PaddedSizeV =
7354     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7355 
7356   if (IsVector) {
7357     // Work out the address of a vector argument on the stack.
7358     // Vector arguments are always passed in the high bits of a
7359     // single (8 byte) or double (16 byte) stack slot.
7360     Address OverflowArgAreaPtr =
7361         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7362     Address OverflowArgArea =
7363       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7364               TyInfo.Align);
7365     Address MemAddr =
7366       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7367 
7368     // Update overflow_arg_area_ptr pointer
7369     llvm::Value *NewOverflowArgArea =
7370       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7371                             "overflow_arg_area");
7372     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7373 
7374     return MemAddr;
7375   }
7376 
7377   assert(PaddedSize.getQuantity() == 8);
7378 
7379   unsigned MaxRegs, RegCountField, RegSaveIndex;
7380   CharUnits RegPadding;
7381   if (InFPRs) {
7382     MaxRegs = 4; // Maximum of 4 FPR arguments
7383     RegCountField = 1; // __fpr
7384     RegSaveIndex = 16; // save offset for f0
7385     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7386   } else {
7387     MaxRegs = 5; // Maximum of 5 GPR arguments
7388     RegCountField = 0; // __gpr
7389     RegSaveIndex = 2; // save offset for r2
7390     RegPadding = Padding; // values are passed in the low bits of a GPR
7391   }
7392 
7393   Address RegCountPtr =
7394       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7395   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7396   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7397   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7398                                                  "fits_in_regs");
7399 
7400   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7401   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7402   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7403   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7404 
7405   // Emit code to load the value if it was passed in registers.
7406   CGF.EmitBlock(InRegBlock);
7407 
7408   // Work out the address of an argument register.
7409   llvm::Value *ScaledRegCount =
7410     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7411   llvm::Value *RegBase =
7412     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7413                                       + RegPadding.getQuantity());
7414   llvm::Value *RegOffset =
7415     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7416   Address RegSaveAreaPtr =
7417       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7418   llvm::Value *RegSaveArea =
7419     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7420   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7421                                            "raw_reg_addr"),
7422                      PaddedSize);
7423   Address RegAddr =
7424     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7425 
7426   // Update the register count
7427   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7428   llvm::Value *NewRegCount =
7429     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7430   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7431   CGF.EmitBranch(ContBlock);
7432 
7433   // Emit code to load the value if it was passed in memory.
7434   CGF.EmitBlock(InMemBlock);
7435 
7436   // Work out the address of a stack argument.
7437   Address OverflowArgAreaPtr =
7438       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7439   Address OverflowArgArea =
7440     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7441             PaddedSize);
7442   Address RawMemAddr =
7443     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7444   Address MemAddr =
7445     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7446 
7447   // Update overflow_arg_area_ptr pointer
7448   llvm::Value *NewOverflowArgArea =
7449     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7450                           "overflow_arg_area");
7451   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7452   CGF.EmitBranch(ContBlock);
7453 
7454   // Return the appropriate result.
7455   CGF.EmitBlock(ContBlock);
7456   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7457                                  MemAddr, InMemBlock, "va_arg.addr");
7458 
7459   if (IsIndirect)
7460     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7461                       TyInfo.Align);
7462 
7463   return ResAddr;
7464 }
7465 
7466 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7467   if (RetTy->isVoidType())
7468     return ABIArgInfo::getIgnore();
7469   if (isVectorArgumentType(RetTy))
7470     return ABIArgInfo::getDirect();
7471   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7472     return getNaturalAlignIndirect(RetTy);
7473   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7474                                                : ABIArgInfo::getDirect());
7475 }
7476 
7477 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7478   // Handle the generic C++ ABI.
7479   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7480     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7481 
7482   // Integers and enums are extended to full register width.
7483   if (isPromotableIntegerTypeForABI(Ty))
7484     return ABIArgInfo::getExtend(Ty);
7485 
7486   // Handle vector types and vector-like structure types.  Note that
7487   // as opposed to float-like structure types, we do not allow any
7488   // padding for vector-like structures, so verify the sizes match.
7489   uint64_t Size = getContext().getTypeSize(Ty);
7490   QualType SingleElementTy = GetSingleElementType(Ty);
7491   if (isVectorArgumentType(SingleElementTy) &&
7492       getContext().getTypeSize(SingleElementTy) == Size)
7493     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7494 
7495   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7496   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7497     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7498 
7499   // Handle small structures.
7500   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7501     // Structures with flexible arrays have variable length, so really
7502     // fail the size test above.
7503     const RecordDecl *RD = RT->getDecl();
7504     if (RD->hasFlexibleArrayMember())
7505       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7506 
7507     // The structure is passed as an unextended integer, a float, or a double.
7508     llvm::Type *PassTy;
7509     if (isFPArgumentType(SingleElementTy)) {
7510       assert(Size == 32 || Size == 64);
7511       if (Size == 32)
7512         PassTy = llvm::Type::getFloatTy(getVMContext());
7513       else
7514         PassTy = llvm::Type::getDoubleTy(getVMContext());
7515     } else
7516       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7517     return ABIArgInfo::getDirect(PassTy);
7518   }
7519 
7520   // Non-structure compounds are passed indirectly.
7521   if (isCompoundType(Ty))
7522     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7523 
7524   return ABIArgInfo::getDirect(nullptr);
7525 }
7526 
7527 //===----------------------------------------------------------------------===//
7528 // MSP430 ABI Implementation
7529 //===----------------------------------------------------------------------===//
7530 
7531 namespace {
7532 
7533 class MSP430ABIInfo : public DefaultABIInfo {
7534   static ABIArgInfo complexArgInfo() {
7535     ABIArgInfo Info = ABIArgInfo::getDirect();
7536     Info.setCanBeFlattened(false);
7537     return Info;
7538   }
7539 
7540 public:
7541   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7542 
7543   ABIArgInfo classifyReturnType(QualType RetTy) const {
7544     if (RetTy->isAnyComplexType())
7545       return complexArgInfo();
7546 
7547     return DefaultABIInfo::classifyReturnType(RetTy);
7548   }
7549 
7550   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7551     if (RetTy->isAnyComplexType())
7552       return complexArgInfo();
7553 
7554     return DefaultABIInfo::classifyArgumentType(RetTy);
7555   }
7556 
7557   // Just copy the original implementations because
7558   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7559   void computeInfo(CGFunctionInfo &FI) const override {
7560     if (!getCXXABI().classifyReturnType(FI))
7561       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7562     for (auto &I : FI.arguments())
7563       I.info = classifyArgumentType(I.type);
7564   }
7565 
7566   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7567                     QualType Ty) const override {
7568     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7569   }
7570 };
7571 
7572 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7573 public:
7574   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7575       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7576   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7577                            CodeGen::CodeGenModule &M) const override;
7578 };
7579 
7580 }
7581 
7582 void MSP430TargetCodeGenInfo::setTargetAttributes(
7583     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7584   if (GV->isDeclaration())
7585     return;
7586   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7587     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7588     if (!InterruptAttr)
7589       return;
7590 
7591     // Handle 'interrupt' attribute:
7592     llvm::Function *F = cast<llvm::Function>(GV);
7593 
7594     // Step 1: Set ISR calling convention.
7595     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7596 
7597     // Step 2: Add attributes goodness.
7598     F->addFnAttr(llvm::Attribute::NoInline);
7599     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7600   }
7601 }
7602 
7603 //===----------------------------------------------------------------------===//
7604 // MIPS ABI Implementation.  This works for both little-endian and
7605 // big-endian variants.
7606 //===----------------------------------------------------------------------===//
7607 
7608 namespace {
7609 class MipsABIInfo : public ABIInfo {
7610   bool IsO32;
7611   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7612   void CoerceToIntArgs(uint64_t TySize,
7613                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7614   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7615   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7616   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7617 public:
7618   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7619     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7620     StackAlignInBytes(IsO32 ? 8 : 16) {}
7621 
7622   ABIArgInfo classifyReturnType(QualType RetTy) const;
7623   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7624   void computeInfo(CGFunctionInfo &FI) const override;
7625   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7626                     QualType Ty) const override;
7627   ABIArgInfo extendType(QualType Ty) const;
7628 };
7629 
7630 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7631   unsigned SizeOfUnwindException;
7632 public:
7633   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7634       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7635         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7636 
7637   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7638     return 29;
7639   }
7640 
7641   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7642                            CodeGen::CodeGenModule &CGM) const override {
7643     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7644     if (!FD) return;
7645     llvm::Function *Fn = cast<llvm::Function>(GV);
7646 
7647     if (FD->hasAttr<MipsLongCallAttr>())
7648       Fn->addFnAttr("long-call");
7649     else if (FD->hasAttr<MipsShortCallAttr>())
7650       Fn->addFnAttr("short-call");
7651 
7652     // Other attributes do not have a meaning for declarations.
7653     if (GV->isDeclaration())
7654       return;
7655 
7656     if (FD->hasAttr<Mips16Attr>()) {
7657       Fn->addFnAttr("mips16");
7658     }
7659     else if (FD->hasAttr<NoMips16Attr>()) {
7660       Fn->addFnAttr("nomips16");
7661     }
7662 
7663     if (FD->hasAttr<MicroMipsAttr>())
7664       Fn->addFnAttr("micromips");
7665     else if (FD->hasAttr<NoMicroMipsAttr>())
7666       Fn->addFnAttr("nomicromips");
7667 
7668     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7669     if (!Attr)
7670       return;
7671 
7672     const char *Kind;
7673     switch (Attr->getInterrupt()) {
7674     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7675     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7676     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7677     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7678     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7679     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7680     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7681     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7682     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7683     }
7684 
7685     Fn->addFnAttr("interrupt", Kind);
7686 
7687   }
7688 
7689   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7690                                llvm::Value *Address) const override;
7691 
7692   unsigned getSizeOfUnwindException() const override {
7693     return SizeOfUnwindException;
7694   }
7695 };
7696 }
7697 
7698 void MipsABIInfo::CoerceToIntArgs(
7699     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7700   llvm::IntegerType *IntTy =
7701     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7702 
7703   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7704   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7705     ArgList.push_back(IntTy);
7706 
7707   // If necessary, add one more integer type to ArgList.
7708   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7709 
7710   if (R)
7711     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7712 }
7713 
7714 // In N32/64, an aligned double precision floating point field is passed in
7715 // a register.
7716 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7717   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7718 
7719   if (IsO32) {
7720     CoerceToIntArgs(TySize, ArgList);
7721     return llvm::StructType::get(getVMContext(), ArgList);
7722   }
7723 
7724   if (Ty->isComplexType())
7725     return CGT.ConvertType(Ty);
7726 
7727   const RecordType *RT = Ty->getAs<RecordType>();
7728 
7729   // Unions/vectors are passed in integer registers.
7730   if (!RT || !RT->isStructureOrClassType()) {
7731     CoerceToIntArgs(TySize, ArgList);
7732     return llvm::StructType::get(getVMContext(), ArgList);
7733   }
7734 
7735   const RecordDecl *RD = RT->getDecl();
7736   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7737   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7738 
7739   uint64_t LastOffset = 0;
7740   unsigned idx = 0;
7741   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7742 
7743   // Iterate over fields in the struct/class and check if there are any aligned
7744   // double fields.
7745   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7746        i != e; ++i, ++idx) {
7747     const QualType Ty = i->getType();
7748     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7749 
7750     if (!BT || BT->getKind() != BuiltinType::Double)
7751       continue;
7752 
7753     uint64_t Offset = Layout.getFieldOffset(idx);
7754     if (Offset % 64) // Ignore doubles that are not aligned.
7755       continue;
7756 
7757     // Add ((Offset - LastOffset) / 64) args of type i64.
7758     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7759       ArgList.push_back(I64);
7760 
7761     // Add double type.
7762     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7763     LastOffset = Offset + 64;
7764   }
7765 
7766   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7767   ArgList.append(IntArgList.begin(), IntArgList.end());
7768 
7769   return llvm::StructType::get(getVMContext(), ArgList);
7770 }
7771 
7772 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7773                                         uint64_t Offset) const {
7774   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7775     return nullptr;
7776 
7777   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7778 }
7779 
7780 ABIArgInfo
7781 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7782   Ty = useFirstFieldIfTransparentUnion(Ty);
7783 
7784   uint64_t OrigOffset = Offset;
7785   uint64_t TySize = getContext().getTypeSize(Ty);
7786   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7787 
7788   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7789                    (uint64_t)StackAlignInBytes);
7790   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7791   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7792 
7793   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7794     // Ignore empty aggregates.
7795     if (TySize == 0)
7796       return ABIArgInfo::getIgnore();
7797 
7798     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7799       Offset = OrigOffset + MinABIStackAlignInBytes;
7800       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7801     }
7802 
7803     // If we have reached here, aggregates are passed directly by coercing to
7804     // another structure type. Padding is inserted if the offset of the
7805     // aggregate is unaligned.
7806     ABIArgInfo ArgInfo =
7807         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7808                               getPaddingType(OrigOffset, CurrOffset));
7809     ArgInfo.setInReg(true);
7810     return ArgInfo;
7811   }
7812 
7813   // Treat an enum type as its underlying type.
7814   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7815     Ty = EnumTy->getDecl()->getIntegerType();
7816 
7817   // Make sure we pass indirectly things that are too large.
7818   if (const auto *EIT = Ty->getAs<ExtIntType>())
7819     if (EIT->getNumBits() > 128 ||
7820         (EIT->getNumBits() > 64 &&
7821          !getContext().getTargetInfo().hasInt128Type()))
7822       return getNaturalAlignIndirect(Ty);
7823 
7824   // All integral types are promoted to the GPR width.
7825   if (Ty->isIntegralOrEnumerationType())
7826     return extendType(Ty);
7827 
7828   return ABIArgInfo::getDirect(
7829       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7830 }
7831 
7832 llvm::Type*
7833 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7834   const RecordType *RT = RetTy->getAs<RecordType>();
7835   SmallVector<llvm::Type*, 8> RTList;
7836 
7837   if (RT && RT->isStructureOrClassType()) {
7838     const RecordDecl *RD = RT->getDecl();
7839     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7840     unsigned FieldCnt = Layout.getFieldCount();
7841 
7842     // N32/64 returns struct/classes in floating point registers if the
7843     // following conditions are met:
7844     // 1. The size of the struct/class is no larger than 128-bit.
7845     // 2. The struct/class has one or two fields all of which are floating
7846     //    point types.
7847     // 3. The offset of the first field is zero (this follows what gcc does).
7848     //
7849     // Any other composite results are returned in integer registers.
7850     //
7851     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7852       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7853       for (; b != e; ++b) {
7854         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7855 
7856         if (!BT || !BT->isFloatingPoint())
7857           break;
7858 
7859         RTList.push_back(CGT.ConvertType(b->getType()));
7860       }
7861 
7862       if (b == e)
7863         return llvm::StructType::get(getVMContext(), RTList,
7864                                      RD->hasAttr<PackedAttr>());
7865 
7866       RTList.clear();
7867     }
7868   }
7869 
7870   CoerceToIntArgs(Size, RTList);
7871   return llvm::StructType::get(getVMContext(), RTList);
7872 }
7873 
7874 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7875   uint64_t Size = getContext().getTypeSize(RetTy);
7876 
7877   if (RetTy->isVoidType())
7878     return ABIArgInfo::getIgnore();
7879 
7880   // O32 doesn't treat zero-sized structs differently from other structs.
7881   // However, N32/N64 ignores zero sized return values.
7882   if (!IsO32 && Size == 0)
7883     return ABIArgInfo::getIgnore();
7884 
7885   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7886     if (Size <= 128) {
7887       if (RetTy->isAnyComplexType())
7888         return ABIArgInfo::getDirect();
7889 
7890       // O32 returns integer vectors in registers and N32/N64 returns all small
7891       // aggregates in registers.
7892       if (!IsO32 ||
7893           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7894         ABIArgInfo ArgInfo =
7895             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7896         ArgInfo.setInReg(true);
7897         return ArgInfo;
7898       }
7899     }
7900 
7901     return getNaturalAlignIndirect(RetTy);
7902   }
7903 
7904   // Treat an enum type as its underlying type.
7905   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7906     RetTy = EnumTy->getDecl()->getIntegerType();
7907 
7908   // Make sure we pass indirectly things that are too large.
7909   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7910     if (EIT->getNumBits() > 128 ||
7911         (EIT->getNumBits() > 64 &&
7912          !getContext().getTargetInfo().hasInt128Type()))
7913       return getNaturalAlignIndirect(RetTy);
7914 
7915   if (isPromotableIntegerTypeForABI(RetTy))
7916     return ABIArgInfo::getExtend(RetTy);
7917 
7918   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7919       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7920     return ABIArgInfo::getSignExtend(RetTy);
7921 
7922   return ABIArgInfo::getDirect();
7923 }
7924 
7925 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7926   ABIArgInfo &RetInfo = FI.getReturnInfo();
7927   if (!getCXXABI().classifyReturnType(FI))
7928     RetInfo = classifyReturnType(FI.getReturnType());
7929 
7930   // Check if a pointer to an aggregate is passed as a hidden argument.
7931   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7932 
7933   for (auto &I : FI.arguments())
7934     I.info = classifyArgumentType(I.type, Offset);
7935 }
7936 
7937 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7938                                QualType OrigTy) const {
7939   QualType Ty = OrigTy;
7940 
7941   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7942   // Pointers are also promoted in the same way but this only matters for N32.
7943   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7944   unsigned PtrWidth = getTarget().getPointerWidth(0);
7945   bool DidPromote = false;
7946   if ((Ty->isIntegerType() &&
7947           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7948       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7949     DidPromote = true;
7950     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7951                                             Ty->isSignedIntegerType());
7952   }
7953 
7954   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7955 
7956   // The alignment of things in the argument area is never larger than
7957   // StackAlignInBytes.
7958   TyInfo.Align =
7959     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7960 
7961   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7962   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7963 
7964   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7965                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7966 
7967 
7968   // If there was a promotion, "unpromote" into a temporary.
7969   // TODO: can we just use a pointer into a subset of the original slot?
7970   if (DidPromote) {
7971     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7972     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7973 
7974     // Truncate down to the right width.
7975     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7976                                                  : CGF.IntPtrTy);
7977     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7978     if (OrigTy->isPointerType())
7979       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7980 
7981     CGF.Builder.CreateStore(V, Temp);
7982     Addr = Temp;
7983   }
7984 
7985   return Addr;
7986 }
7987 
7988 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7989   int TySize = getContext().getTypeSize(Ty);
7990 
7991   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7992   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7993     return ABIArgInfo::getSignExtend(Ty);
7994 
7995   return ABIArgInfo::getExtend(Ty);
7996 }
7997 
7998 bool
7999 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8000                                                llvm::Value *Address) const {
8001   // This information comes from gcc's implementation, which seems to
8002   // as canonical as it gets.
8003 
8004   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8005   // are aliased to pairs of single-precision FP registers.
8006   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8007 
8008   // 0-31 are the general purpose registers, $0 - $31.
8009   // 32-63 are the floating-point registers, $f0 - $f31.
8010   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8011   // 66 is the (notional, I think) register for signal-handler return.
8012   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8013 
8014   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8015   // They are one bit wide and ignored here.
8016 
8017   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8018   // (coprocessor 1 is the FP unit)
8019   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8020   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8021   // 176-181 are the DSP accumulator registers.
8022   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8023   return false;
8024 }
8025 
8026 //===----------------------------------------------------------------------===//
8027 // AVR ABI Implementation.
8028 //===----------------------------------------------------------------------===//
8029 
8030 namespace {
8031 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8032 public:
8033   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8034       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8035 
8036   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8037                            CodeGen::CodeGenModule &CGM) const override {
8038     if (GV->isDeclaration())
8039       return;
8040     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8041     if (!FD) return;
8042     auto *Fn = cast<llvm::Function>(GV);
8043 
8044     if (FD->getAttr<AVRInterruptAttr>())
8045       Fn->addFnAttr("interrupt");
8046 
8047     if (FD->getAttr<AVRSignalAttr>())
8048       Fn->addFnAttr("signal");
8049   }
8050 };
8051 }
8052 
8053 //===----------------------------------------------------------------------===//
8054 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8055 // Currently subclassed only to implement custom OpenCL C function attribute
8056 // handling.
8057 //===----------------------------------------------------------------------===//
8058 
8059 namespace {
8060 
8061 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8062 public:
8063   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8064     : DefaultTargetCodeGenInfo(CGT) {}
8065 
8066   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8067                            CodeGen::CodeGenModule &M) const override;
8068 };
8069 
8070 void TCETargetCodeGenInfo::setTargetAttributes(
8071     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8072   if (GV->isDeclaration())
8073     return;
8074   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8075   if (!FD) return;
8076 
8077   llvm::Function *F = cast<llvm::Function>(GV);
8078 
8079   if (M.getLangOpts().OpenCL) {
8080     if (FD->hasAttr<OpenCLKernelAttr>()) {
8081       // OpenCL C Kernel functions are not subject to inlining
8082       F->addFnAttr(llvm::Attribute::NoInline);
8083       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8084       if (Attr) {
8085         // Convert the reqd_work_group_size() attributes to metadata.
8086         llvm::LLVMContext &Context = F->getContext();
8087         llvm::NamedMDNode *OpenCLMetadata =
8088             M.getModule().getOrInsertNamedMetadata(
8089                 "opencl.kernel_wg_size_info");
8090 
8091         SmallVector<llvm::Metadata *, 5> Operands;
8092         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8093 
8094         Operands.push_back(
8095             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8096                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8097         Operands.push_back(
8098             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8099                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8100         Operands.push_back(
8101             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8102                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8103 
8104         // Add a boolean constant operand for "required" (true) or "hint"
8105         // (false) for implementing the work_group_size_hint attr later.
8106         // Currently always true as the hint is not yet implemented.
8107         Operands.push_back(
8108             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8109         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8110       }
8111     }
8112   }
8113 }
8114 
8115 }
8116 
8117 //===----------------------------------------------------------------------===//
8118 // Hexagon ABI Implementation
8119 //===----------------------------------------------------------------------===//
8120 
8121 namespace {
8122 
8123 class HexagonABIInfo : public DefaultABIInfo {
8124 public:
8125   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8126 
8127 private:
8128   ABIArgInfo classifyReturnType(QualType RetTy) const;
8129   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8130   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8131 
8132   void computeInfo(CGFunctionInfo &FI) const override;
8133 
8134   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8135                     QualType Ty) const override;
8136   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8137                               QualType Ty) const;
8138   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8139                               QualType Ty) const;
8140   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8141                                    QualType Ty) const;
8142 };
8143 
8144 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8145 public:
8146   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8147       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8148 
8149   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8150     return 29;
8151   }
8152 
8153   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8154                            CodeGen::CodeGenModule &GCM) const override {
8155     if (GV->isDeclaration())
8156       return;
8157     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8158     if (!FD)
8159       return;
8160   }
8161 };
8162 
8163 } // namespace
8164 
8165 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8166   unsigned RegsLeft = 6;
8167   if (!getCXXABI().classifyReturnType(FI))
8168     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8169   for (auto &I : FI.arguments())
8170     I.info = classifyArgumentType(I.type, &RegsLeft);
8171 }
8172 
8173 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8174   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8175                        " through registers");
8176 
8177   if (*RegsLeft == 0)
8178     return false;
8179 
8180   if (Size <= 32) {
8181     (*RegsLeft)--;
8182     return true;
8183   }
8184 
8185   if (2 <= (*RegsLeft & (~1U))) {
8186     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8187     return true;
8188   }
8189 
8190   // Next available register was r5 but candidate was greater than 32-bits so it
8191   // has to go on the stack. However we still consume r5
8192   if (*RegsLeft == 1)
8193     *RegsLeft = 0;
8194 
8195   return false;
8196 }
8197 
8198 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8199                                                 unsigned *RegsLeft) const {
8200   if (!isAggregateTypeForABI(Ty)) {
8201     // Treat an enum type as its underlying type.
8202     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8203       Ty = EnumTy->getDecl()->getIntegerType();
8204 
8205     uint64_t Size = getContext().getTypeSize(Ty);
8206     if (Size <= 64)
8207       HexagonAdjustRegsLeft(Size, RegsLeft);
8208 
8209     if (Size > 64 && Ty->isExtIntType())
8210       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8211 
8212     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8213                                              : ABIArgInfo::getDirect();
8214   }
8215 
8216   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8217     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8218 
8219   // Ignore empty records.
8220   if (isEmptyRecord(getContext(), Ty, true))
8221     return ABIArgInfo::getIgnore();
8222 
8223   uint64_t Size = getContext().getTypeSize(Ty);
8224   unsigned Align = getContext().getTypeAlign(Ty);
8225 
8226   if (Size > 64)
8227     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8228 
8229   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8230     Align = Size <= 32 ? 32 : 64;
8231   if (Size <= Align) {
8232     // Pass in the smallest viable integer type.
8233     if (!llvm::isPowerOf2_64(Size))
8234       Size = llvm::NextPowerOf2(Size);
8235     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8236   }
8237   return DefaultABIInfo::classifyArgumentType(Ty);
8238 }
8239 
8240 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8241   if (RetTy->isVoidType())
8242     return ABIArgInfo::getIgnore();
8243 
8244   const TargetInfo &T = CGT.getTarget();
8245   uint64_t Size = getContext().getTypeSize(RetTy);
8246 
8247   if (RetTy->getAs<VectorType>()) {
8248     // HVX vectors are returned in vector registers or register pairs.
8249     if (T.hasFeature("hvx")) {
8250       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8251       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8252       if (Size == VecSize || Size == 2*VecSize)
8253         return ABIArgInfo::getDirectInReg();
8254     }
8255     // Large vector types should be returned via memory.
8256     if (Size > 64)
8257       return getNaturalAlignIndirect(RetTy);
8258   }
8259 
8260   if (!isAggregateTypeForABI(RetTy)) {
8261     // Treat an enum type as its underlying type.
8262     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8263       RetTy = EnumTy->getDecl()->getIntegerType();
8264 
8265     if (Size > 64 && RetTy->isExtIntType())
8266       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8267 
8268     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8269                                                 : ABIArgInfo::getDirect();
8270   }
8271 
8272   if (isEmptyRecord(getContext(), RetTy, true))
8273     return ABIArgInfo::getIgnore();
8274 
8275   // Aggregates <= 8 bytes are returned in registers, other aggregates
8276   // are returned indirectly.
8277   if (Size <= 64) {
8278     // Return in the smallest viable integer type.
8279     if (!llvm::isPowerOf2_64(Size))
8280       Size = llvm::NextPowerOf2(Size);
8281     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8282   }
8283   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8284 }
8285 
8286 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8287                                             Address VAListAddr,
8288                                             QualType Ty) const {
8289   // Load the overflow area pointer.
8290   Address __overflow_area_pointer_p =
8291       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8292   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8293       __overflow_area_pointer_p, "__overflow_area_pointer");
8294 
8295   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8296   if (Align > 4) {
8297     // Alignment should be a power of 2.
8298     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8299 
8300     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8301     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8302 
8303     // Add offset to the current pointer to access the argument.
8304     __overflow_area_pointer =
8305         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8306     llvm::Value *AsInt =
8307         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8308 
8309     // Create a mask which should be "AND"ed
8310     // with (overflow_arg_area + align - 1)
8311     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8312     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8313         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8314         "__overflow_area_pointer.align");
8315   }
8316 
8317   // Get the type of the argument from memory and bitcast
8318   // overflow area pointer to the argument type.
8319   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8320   Address AddrTyped = CGF.Builder.CreateBitCast(
8321       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8322       llvm::PointerType::getUnqual(PTy));
8323 
8324   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8325   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8326 
8327   __overflow_area_pointer = CGF.Builder.CreateGEP(
8328       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8329       "__overflow_area_pointer.next");
8330   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8331 
8332   return AddrTyped;
8333 }
8334 
8335 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8336                                             Address VAListAddr,
8337                                             QualType Ty) const {
8338   // FIXME: Need to handle alignment
8339   llvm::Type *BP = CGF.Int8PtrTy;
8340   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8341   CGBuilderTy &Builder = CGF.Builder;
8342   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8343   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8344   // Handle address alignment for type alignment > 32 bits
8345   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8346   if (TyAlign > 4) {
8347     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8348     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8349     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8350     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8351     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8352   }
8353   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8354   Address AddrTyped = Builder.CreateBitCast(
8355       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8356 
8357   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8358   llvm::Value *NextAddr = Builder.CreateGEP(
8359       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8360   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8361 
8362   return AddrTyped;
8363 }
8364 
8365 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8366                                                  Address VAListAddr,
8367                                                  QualType Ty) const {
8368   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8369 
8370   if (ArgSize > 8)
8371     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8372 
8373   // Here we have check if the argument is in register area or
8374   // in overflow area.
8375   // If the saved register area pointer + argsize rounded up to alignment >
8376   // saved register area end pointer, argument is in overflow area.
8377   unsigned RegsLeft = 6;
8378   Ty = CGF.getContext().getCanonicalType(Ty);
8379   (void)classifyArgumentType(Ty, &RegsLeft);
8380 
8381   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8382   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8383   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8384   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8385 
8386   // Get rounded size of the argument.GCC does not allow vararg of
8387   // size < 4 bytes. We follow the same logic here.
8388   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8389   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8390 
8391   // Argument may be in saved register area
8392   CGF.EmitBlock(MaybeRegBlock);
8393 
8394   // Load the current saved register area pointer.
8395   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8396       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8397   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8398       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8399 
8400   // Load the saved register area end pointer.
8401   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8402       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8403   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8404       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8405 
8406   // If the size of argument is > 4 bytes, check if the stack
8407   // location is aligned to 8 bytes
8408   if (ArgAlign > 4) {
8409 
8410     llvm::Value *__current_saved_reg_area_pointer_int =
8411         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8412                                    CGF.Int32Ty);
8413 
8414     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8415         __current_saved_reg_area_pointer_int,
8416         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8417         "align_current_saved_reg_area_pointer");
8418 
8419     __current_saved_reg_area_pointer_int =
8420         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8421                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8422                               "align_current_saved_reg_area_pointer");
8423 
8424     __current_saved_reg_area_pointer =
8425         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8426                                    __current_saved_reg_area_pointer->getType(),
8427                                    "align_current_saved_reg_area_pointer");
8428   }
8429 
8430   llvm::Value *__new_saved_reg_area_pointer =
8431       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8432                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8433                             "__new_saved_reg_area_pointer");
8434 
8435   llvm::Value *UsingStack = 0;
8436   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8437                                          __saved_reg_area_end_pointer);
8438 
8439   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8440 
8441   // Argument in saved register area
8442   // Implement the block where argument is in register saved area
8443   CGF.EmitBlock(InRegBlock);
8444 
8445   llvm::Type *PTy = CGF.ConvertType(Ty);
8446   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8447       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8448 
8449   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8450                           __current_saved_reg_area_pointer_p);
8451 
8452   CGF.EmitBranch(ContBlock);
8453 
8454   // Argument in overflow area
8455   // Implement the block where the argument is in overflow area.
8456   CGF.EmitBlock(OnStackBlock);
8457 
8458   // Load the overflow area pointer
8459   Address __overflow_area_pointer_p =
8460       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8461   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8462       __overflow_area_pointer_p, "__overflow_area_pointer");
8463 
8464   // Align the overflow area pointer according to the alignment of the argument
8465   if (ArgAlign > 4) {
8466     llvm::Value *__overflow_area_pointer_int =
8467         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8468 
8469     __overflow_area_pointer_int =
8470         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8471                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8472                               "align_overflow_area_pointer");
8473 
8474     __overflow_area_pointer_int =
8475         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8476                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8477                               "align_overflow_area_pointer");
8478 
8479     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8480         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8481         "align_overflow_area_pointer");
8482   }
8483 
8484   // Get the pointer for next argument in overflow area and store it
8485   // to overflow area pointer.
8486   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8487       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8488       "__overflow_area_pointer.next");
8489 
8490   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8491                           __overflow_area_pointer_p);
8492 
8493   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8494                           __current_saved_reg_area_pointer_p);
8495 
8496   // Bitcast the overflow area pointer to the type of argument.
8497   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8498   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8499       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8500 
8501   CGF.EmitBranch(ContBlock);
8502 
8503   // Get the correct pointer to load the variable argument
8504   // Implement the ContBlock
8505   CGF.EmitBlock(ContBlock);
8506 
8507   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8508   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8509   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8510   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8511 
8512   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8513 }
8514 
8515 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8516                                   QualType Ty) const {
8517 
8518   if (getTarget().getTriple().isMusl())
8519     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8520 
8521   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8522 }
8523 
8524 //===----------------------------------------------------------------------===//
8525 // Lanai ABI Implementation
8526 //===----------------------------------------------------------------------===//
8527 
8528 namespace {
8529 class LanaiABIInfo : public DefaultABIInfo {
8530 public:
8531   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8532 
8533   bool shouldUseInReg(QualType Ty, CCState &State) const;
8534 
8535   void computeInfo(CGFunctionInfo &FI) const override {
8536     CCState State(FI);
8537     // Lanai uses 4 registers to pass arguments unless the function has the
8538     // regparm attribute set.
8539     if (FI.getHasRegParm()) {
8540       State.FreeRegs = FI.getRegParm();
8541     } else {
8542       State.FreeRegs = 4;
8543     }
8544 
8545     if (!getCXXABI().classifyReturnType(FI))
8546       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8547     for (auto &I : FI.arguments())
8548       I.info = classifyArgumentType(I.type, State);
8549   }
8550 
8551   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8552   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8553 };
8554 } // end anonymous namespace
8555 
8556 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8557   unsigned Size = getContext().getTypeSize(Ty);
8558   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8559 
8560   if (SizeInRegs == 0)
8561     return false;
8562 
8563   if (SizeInRegs > State.FreeRegs) {
8564     State.FreeRegs = 0;
8565     return false;
8566   }
8567 
8568   State.FreeRegs -= SizeInRegs;
8569 
8570   return true;
8571 }
8572 
8573 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8574                                            CCState &State) const {
8575   if (!ByVal) {
8576     if (State.FreeRegs) {
8577       --State.FreeRegs; // Non-byval indirects just use one pointer.
8578       return getNaturalAlignIndirectInReg(Ty);
8579     }
8580     return getNaturalAlignIndirect(Ty, false);
8581   }
8582 
8583   // Compute the byval alignment.
8584   const unsigned MinABIStackAlignInBytes = 4;
8585   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8586   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8587                                  /*Realign=*/TypeAlign >
8588                                      MinABIStackAlignInBytes);
8589 }
8590 
8591 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8592                                               CCState &State) const {
8593   // Check with the C++ ABI first.
8594   const RecordType *RT = Ty->getAs<RecordType>();
8595   if (RT) {
8596     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8597     if (RAA == CGCXXABI::RAA_Indirect) {
8598       return getIndirectResult(Ty, /*ByVal=*/false, State);
8599     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8600       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8601     }
8602   }
8603 
8604   if (isAggregateTypeForABI(Ty)) {
8605     // Structures with flexible arrays are always indirect.
8606     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8607       return getIndirectResult(Ty, /*ByVal=*/true, State);
8608 
8609     // Ignore empty structs/unions.
8610     if (isEmptyRecord(getContext(), Ty, true))
8611       return ABIArgInfo::getIgnore();
8612 
8613     llvm::LLVMContext &LLVMContext = getVMContext();
8614     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8615     if (SizeInRegs <= State.FreeRegs) {
8616       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8617       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8618       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8619       State.FreeRegs -= SizeInRegs;
8620       return ABIArgInfo::getDirectInReg(Result);
8621     } else {
8622       State.FreeRegs = 0;
8623     }
8624     return getIndirectResult(Ty, true, State);
8625   }
8626 
8627   // Treat an enum type as its underlying type.
8628   if (const auto *EnumTy = Ty->getAs<EnumType>())
8629     Ty = EnumTy->getDecl()->getIntegerType();
8630 
8631   bool InReg = shouldUseInReg(Ty, State);
8632 
8633   // Don't pass >64 bit integers in registers.
8634   if (const auto *EIT = Ty->getAs<ExtIntType>())
8635     if (EIT->getNumBits() > 64)
8636       return getIndirectResult(Ty, /*ByVal=*/true, State);
8637 
8638   if (isPromotableIntegerTypeForABI(Ty)) {
8639     if (InReg)
8640       return ABIArgInfo::getDirectInReg();
8641     return ABIArgInfo::getExtend(Ty);
8642   }
8643   if (InReg)
8644     return ABIArgInfo::getDirectInReg();
8645   return ABIArgInfo::getDirect();
8646 }
8647 
8648 namespace {
8649 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8650 public:
8651   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8652       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8653 };
8654 }
8655 
8656 //===----------------------------------------------------------------------===//
8657 // AMDGPU ABI Implementation
8658 //===----------------------------------------------------------------------===//
8659 
8660 namespace {
8661 
8662 class AMDGPUABIInfo final : public DefaultABIInfo {
8663 private:
8664   static const unsigned MaxNumRegsForArgsRet = 16;
8665 
8666   unsigned numRegsForType(QualType Ty) const;
8667 
8668   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8669   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8670                                          uint64_t Members) const override;
8671 
8672   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8673   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8674                                        unsigned ToAS) const {
8675     // Single value types.
8676     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8677       return llvm::PointerType::get(
8678           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8679     return Ty;
8680   }
8681 
8682 public:
8683   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8684     DefaultABIInfo(CGT) {}
8685 
8686   ABIArgInfo classifyReturnType(QualType RetTy) const;
8687   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8688   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8689 
8690   void computeInfo(CGFunctionInfo &FI) const override;
8691   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8692                     QualType Ty) const override;
8693 };
8694 
8695 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8696   return true;
8697 }
8698 
8699 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8700   const Type *Base, uint64_t Members) const {
8701   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8702 
8703   // Homogeneous Aggregates may occupy at most 16 registers.
8704   return Members * NumRegs <= MaxNumRegsForArgsRet;
8705 }
8706 
8707 /// Estimate number of registers the type will use when passed in registers.
8708 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8709   unsigned NumRegs = 0;
8710 
8711   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8712     // Compute from the number of elements. The reported size is based on the
8713     // in-memory size, which includes the padding 4th element for 3-vectors.
8714     QualType EltTy = VT->getElementType();
8715     unsigned EltSize = getContext().getTypeSize(EltTy);
8716 
8717     // 16-bit element vectors should be passed as packed.
8718     if (EltSize == 16)
8719       return (VT->getNumElements() + 1) / 2;
8720 
8721     unsigned EltNumRegs = (EltSize + 31) / 32;
8722     return EltNumRegs * VT->getNumElements();
8723   }
8724 
8725   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8726     const RecordDecl *RD = RT->getDecl();
8727     assert(!RD->hasFlexibleArrayMember());
8728 
8729     for (const FieldDecl *Field : RD->fields()) {
8730       QualType FieldTy = Field->getType();
8731       NumRegs += numRegsForType(FieldTy);
8732     }
8733 
8734     return NumRegs;
8735   }
8736 
8737   return (getContext().getTypeSize(Ty) + 31) / 32;
8738 }
8739 
8740 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8741   llvm::CallingConv::ID CC = FI.getCallingConvention();
8742 
8743   if (!getCXXABI().classifyReturnType(FI))
8744     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8745 
8746   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8747   for (auto &Arg : FI.arguments()) {
8748     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8749       Arg.info = classifyKernelArgumentType(Arg.type);
8750     } else {
8751       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8752     }
8753   }
8754 }
8755 
8756 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8757                                  QualType Ty) const {
8758   llvm_unreachable("AMDGPU does not support varargs");
8759 }
8760 
8761 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8762   if (isAggregateTypeForABI(RetTy)) {
8763     // Records with non-trivial destructors/copy-constructors should not be
8764     // returned by value.
8765     if (!getRecordArgABI(RetTy, getCXXABI())) {
8766       // Ignore empty structs/unions.
8767       if (isEmptyRecord(getContext(), RetTy, true))
8768         return ABIArgInfo::getIgnore();
8769 
8770       // Lower single-element structs to just return a regular value.
8771       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8772         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8773 
8774       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8775         const RecordDecl *RD = RT->getDecl();
8776         if (RD->hasFlexibleArrayMember())
8777           return DefaultABIInfo::classifyReturnType(RetTy);
8778       }
8779 
8780       // Pack aggregates <= 4 bytes into single VGPR or pair.
8781       uint64_t Size = getContext().getTypeSize(RetTy);
8782       if (Size <= 16)
8783         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8784 
8785       if (Size <= 32)
8786         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8787 
8788       if (Size <= 64) {
8789         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8790         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8791       }
8792 
8793       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8794         return ABIArgInfo::getDirect();
8795     }
8796   }
8797 
8798   // Otherwise just do the default thing.
8799   return DefaultABIInfo::classifyReturnType(RetTy);
8800 }
8801 
8802 /// For kernels all parameters are really passed in a special buffer. It doesn't
8803 /// make sense to pass anything byval, so everything must be direct.
8804 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8805   Ty = useFirstFieldIfTransparentUnion(Ty);
8806 
8807   // TODO: Can we omit empty structs?
8808 
8809   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8810     Ty = QualType(SeltTy, 0);
8811 
8812   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8813   llvm::Type *LTy = OrigLTy;
8814   if (getContext().getLangOpts().HIP) {
8815     LTy = coerceKernelArgumentType(
8816         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8817         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8818   }
8819 
8820   // FIXME: Should also use this for OpenCL, but it requires addressing the
8821   // problem of kernels being called.
8822   //
8823   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8824   // to global address space when using byref. This would require implementing a
8825   // new kind of coercion of the in-memory type when for indirect arguments.
8826   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8827       isAggregateTypeForABI(Ty)) {
8828     return ABIArgInfo::getIndirectAliased(
8829         getContext().getTypeAlignInChars(Ty),
8830         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8831         false /*Realign*/, nullptr /*Padding*/);
8832   }
8833 
8834   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8835   // individual elements, which confuses the Clover OpenCL backend; therefore we
8836   // have to set it to false here. Other args of getDirect() are just defaults.
8837   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8838 }
8839 
8840 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8841                                                unsigned &NumRegsLeft) const {
8842   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8843 
8844   Ty = useFirstFieldIfTransparentUnion(Ty);
8845 
8846   if (isAggregateTypeForABI(Ty)) {
8847     // Records with non-trivial destructors/copy-constructors should not be
8848     // passed by value.
8849     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8850       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8851 
8852     // Ignore empty structs/unions.
8853     if (isEmptyRecord(getContext(), Ty, true))
8854       return ABIArgInfo::getIgnore();
8855 
8856     // Lower single-element structs to just pass a regular value. TODO: We
8857     // could do reasonable-size multiple-element structs too, using getExpand(),
8858     // though watch out for things like bitfields.
8859     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8860       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8861 
8862     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8863       const RecordDecl *RD = RT->getDecl();
8864       if (RD->hasFlexibleArrayMember())
8865         return DefaultABIInfo::classifyArgumentType(Ty);
8866     }
8867 
8868     // Pack aggregates <= 8 bytes into single VGPR or pair.
8869     uint64_t Size = getContext().getTypeSize(Ty);
8870     if (Size <= 64) {
8871       unsigned NumRegs = (Size + 31) / 32;
8872       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8873 
8874       if (Size <= 16)
8875         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8876 
8877       if (Size <= 32)
8878         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8879 
8880       // XXX: Should this be i64 instead, and should the limit increase?
8881       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8882       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8883     }
8884 
8885     if (NumRegsLeft > 0) {
8886       unsigned NumRegs = numRegsForType(Ty);
8887       if (NumRegsLeft >= NumRegs) {
8888         NumRegsLeft -= NumRegs;
8889         return ABIArgInfo::getDirect();
8890       }
8891     }
8892   }
8893 
8894   // Otherwise just do the default thing.
8895   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8896   if (!ArgInfo.isIndirect()) {
8897     unsigned NumRegs = numRegsForType(Ty);
8898     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8899   }
8900 
8901   return ArgInfo;
8902 }
8903 
8904 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8905 public:
8906   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8907       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8908   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8909                            CodeGen::CodeGenModule &M) const override;
8910   unsigned getOpenCLKernelCallingConv() const override;
8911 
8912   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8913       llvm::PointerType *T, QualType QT) const override;
8914 
8915   LangAS getASTAllocaAddressSpace() const override {
8916     return getLangASFromTargetAS(
8917         getABIInfo().getDataLayout().getAllocaAddrSpace());
8918   }
8919   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8920                                   const VarDecl *D) const override;
8921   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8922                                          SyncScope Scope,
8923                                          llvm::AtomicOrdering Ordering,
8924                                          llvm::LLVMContext &Ctx) const override;
8925   llvm::Function *
8926   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8927                             llvm::Function *BlockInvokeFunc,
8928                             llvm::Value *BlockLiteral) const override;
8929   bool shouldEmitStaticExternCAliases() const override;
8930   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8931 };
8932 }
8933 
8934 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8935                                               llvm::GlobalValue *GV) {
8936   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8937     return false;
8938 
8939   return D->hasAttr<OpenCLKernelAttr>() ||
8940          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8941          (isa<VarDecl>(D) &&
8942           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8943            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8944            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8945 }
8946 
8947 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8948     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8949   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8950     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8951     GV->setDSOLocal(true);
8952   }
8953 
8954   if (GV->isDeclaration())
8955     return;
8956   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8957   if (!FD)
8958     return;
8959 
8960   llvm::Function *F = cast<llvm::Function>(GV);
8961 
8962   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8963     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8964 
8965 
8966   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8967                               FD->hasAttr<OpenCLKernelAttr>();
8968   const bool IsHIPKernel = M.getLangOpts().HIP &&
8969                            FD->hasAttr<CUDAGlobalAttr>();
8970   if ((IsOpenCLKernel || IsHIPKernel) &&
8971       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8972     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8973 
8974   if (IsHIPKernel)
8975     F->addFnAttr("uniform-work-group-size", "true");
8976 
8977 
8978   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8979   if (ReqdWGS || FlatWGS) {
8980     unsigned Min = 0;
8981     unsigned Max = 0;
8982     if (FlatWGS) {
8983       Min = FlatWGS->getMin()
8984                 ->EvaluateKnownConstInt(M.getContext())
8985                 .getExtValue();
8986       Max = FlatWGS->getMax()
8987                 ->EvaluateKnownConstInt(M.getContext())
8988                 .getExtValue();
8989     }
8990     if (ReqdWGS && Min == 0 && Max == 0)
8991       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8992 
8993     if (Min != 0) {
8994       assert(Min <= Max && "Min must be less than or equal Max");
8995 
8996       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8997       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8998     } else
8999       assert(Max == 0 && "Max must be zero");
9000   } else if (IsOpenCLKernel || IsHIPKernel) {
9001     // By default, restrict the maximum size to a value specified by
9002     // --gpu-max-threads-per-block=n or its default value.
9003     std::string AttrVal =
9004         std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
9005     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9006   }
9007 
9008   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9009     unsigned Min =
9010         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9011     unsigned Max = Attr->getMax() ? Attr->getMax()
9012                                         ->EvaluateKnownConstInt(M.getContext())
9013                                         .getExtValue()
9014                                   : 0;
9015 
9016     if (Min != 0) {
9017       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9018 
9019       std::string AttrVal = llvm::utostr(Min);
9020       if (Max != 0)
9021         AttrVal = AttrVal + "," + llvm::utostr(Max);
9022       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9023     } else
9024       assert(Max == 0 && "Max must be zero");
9025   }
9026 
9027   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9028     unsigned NumSGPR = Attr->getNumSGPR();
9029 
9030     if (NumSGPR != 0)
9031       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9032   }
9033 
9034   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9035     uint32_t NumVGPR = Attr->getNumVGPR();
9036 
9037     if (NumVGPR != 0)
9038       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9039   }
9040 
9041   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9042     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9043 }
9044 
9045 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9046   return llvm::CallingConv::AMDGPU_KERNEL;
9047 }
9048 
9049 // Currently LLVM assumes null pointers always have value 0,
9050 // which results in incorrectly transformed IR. Therefore, instead of
9051 // emitting null pointers in private and local address spaces, a null
9052 // pointer in generic address space is emitted which is casted to a
9053 // pointer in local or private address space.
9054 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9055     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9056     QualType QT) const {
9057   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9058     return llvm::ConstantPointerNull::get(PT);
9059 
9060   auto &Ctx = CGM.getContext();
9061   auto NPT = llvm::PointerType::get(PT->getElementType(),
9062       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9063   return llvm::ConstantExpr::getAddrSpaceCast(
9064       llvm::ConstantPointerNull::get(NPT), PT);
9065 }
9066 
9067 LangAS
9068 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9069                                                   const VarDecl *D) const {
9070   assert(!CGM.getLangOpts().OpenCL &&
9071          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9072          "Address space agnostic languages only");
9073   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9074       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9075   if (!D)
9076     return DefaultGlobalAS;
9077 
9078   LangAS AddrSpace = D->getType().getAddressSpace();
9079   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9080   if (AddrSpace != LangAS::Default)
9081     return AddrSpace;
9082 
9083   if (CGM.isTypeConstant(D->getType(), false)) {
9084     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9085       return ConstAS.getValue();
9086   }
9087   return DefaultGlobalAS;
9088 }
9089 
9090 llvm::SyncScope::ID
9091 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9092                                             SyncScope Scope,
9093                                             llvm::AtomicOrdering Ordering,
9094                                             llvm::LLVMContext &Ctx) const {
9095   std::string Name;
9096   switch (Scope) {
9097   case SyncScope::OpenCLWorkGroup:
9098     Name = "workgroup";
9099     break;
9100   case SyncScope::OpenCLDevice:
9101     Name = "agent";
9102     break;
9103   case SyncScope::OpenCLAllSVMDevices:
9104     Name = "";
9105     break;
9106   case SyncScope::OpenCLSubGroup:
9107     Name = "wavefront";
9108   }
9109 
9110   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9111     if (!Name.empty())
9112       Name = Twine(Twine(Name) + Twine("-")).str();
9113 
9114     Name = Twine(Twine(Name) + Twine("one-as")).str();
9115   }
9116 
9117   return Ctx.getOrInsertSyncScopeID(Name);
9118 }
9119 
9120 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9121   return false;
9122 }
9123 
9124 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9125     const FunctionType *&FT) const {
9126   FT = getABIInfo().getContext().adjustFunctionType(
9127       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9128 }
9129 
9130 //===----------------------------------------------------------------------===//
9131 // SPARC v8 ABI Implementation.
9132 // Based on the SPARC Compliance Definition version 2.4.1.
9133 //
9134 // Ensures that complex values are passed in registers.
9135 //
9136 namespace {
9137 class SparcV8ABIInfo : public DefaultABIInfo {
9138 public:
9139   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9140 
9141 private:
9142   ABIArgInfo classifyReturnType(QualType RetTy) const;
9143   void computeInfo(CGFunctionInfo &FI) const override;
9144 };
9145 } // end anonymous namespace
9146 
9147 
9148 ABIArgInfo
9149 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9150   if (Ty->isAnyComplexType()) {
9151     return ABIArgInfo::getDirect();
9152   }
9153   else {
9154     return DefaultABIInfo::classifyReturnType(Ty);
9155   }
9156 }
9157 
9158 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9159 
9160   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9161   for (auto &Arg : FI.arguments())
9162     Arg.info = classifyArgumentType(Arg.type);
9163 }
9164 
9165 namespace {
9166 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9167 public:
9168   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9169       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9170 };
9171 } // end anonymous namespace
9172 
9173 //===----------------------------------------------------------------------===//
9174 // SPARC v9 ABI Implementation.
9175 // Based on the SPARC Compliance Definition version 2.4.1.
9176 //
9177 // Function arguments a mapped to a nominal "parameter array" and promoted to
9178 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9179 // the array, structs larger than 16 bytes are passed indirectly.
9180 //
9181 // One case requires special care:
9182 //
9183 //   struct mixed {
9184 //     int i;
9185 //     float f;
9186 //   };
9187 //
9188 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9189 // parameter array, but the int is passed in an integer register, and the float
9190 // is passed in a floating point register. This is represented as two arguments
9191 // with the LLVM IR inreg attribute:
9192 //
9193 //   declare void f(i32 inreg %i, float inreg %f)
9194 //
9195 // The code generator will only allocate 4 bytes from the parameter array for
9196 // the inreg arguments. All other arguments are allocated a multiple of 8
9197 // bytes.
9198 //
9199 namespace {
9200 class SparcV9ABIInfo : public ABIInfo {
9201 public:
9202   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9203 
9204 private:
9205   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9206   void computeInfo(CGFunctionInfo &FI) const override;
9207   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9208                     QualType Ty) const override;
9209 
9210   // Coercion type builder for structs passed in registers. The coercion type
9211   // serves two purposes:
9212   //
9213   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9214   //    in registers.
9215   // 2. Expose aligned floating point elements as first-level elements, so the
9216   //    code generator knows to pass them in floating point registers.
9217   //
9218   // We also compute the InReg flag which indicates that the struct contains
9219   // aligned 32-bit floats.
9220   //
9221   struct CoerceBuilder {
9222     llvm::LLVMContext &Context;
9223     const llvm::DataLayout &DL;
9224     SmallVector<llvm::Type*, 8> Elems;
9225     uint64_t Size;
9226     bool InReg;
9227 
9228     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9229       : Context(c), DL(dl), Size(0), InReg(false) {}
9230 
9231     // Pad Elems with integers until Size is ToSize.
9232     void pad(uint64_t ToSize) {
9233       assert(ToSize >= Size && "Cannot remove elements");
9234       if (ToSize == Size)
9235         return;
9236 
9237       // Finish the current 64-bit word.
9238       uint64_t Aligned = llvm::alignTo(Size, 64);
9239       if (Aligned > Size && Aligned <= ToSize) {
9240         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9241         Size = Aligned;
9242       }
9243 
9244       // Add whole 64-bit words.
9245       while (Size + 64 <= ToSize) {
9246         Elems.push_back(llvm::Type::getInt64Ty(Context));
9247         Size += 64;
9248       }
9249 
9250       // Final in-word padding.
9251       if (Size < ToSize) {
9252         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9253         Size = ToSize;
9254       }
9255     }
9256 
9257     // Add a floating point element at Offset.
9258     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9259       // Unaligned floats are treated as integers.
9260       if (Offset % Bits)
9261         return;
9262       // The InReg flag is only required if there are any floats < 64 bits.
9263       if (Bits < 64)
9264         InReg = true;
9265       pad(Offset);
9266       Elems.push_back(Ty);
9267       Size = Offset + Bits;
9268     }
9269 
9270     // Add a struct type to the coercion type, starting at Offset (in bits).
9271     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9272       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9273       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9274         llvm::Type *ElemTy = StrTy->getElementType(i);
9275         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9276         switch (ElemTy->getTypeID()) {
9277         case llvm::Type::StructTyID:
9278           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9279           break;
9280         case llvm::Type::FloatTyID:
9281           addFloat(ElemOffset, ElemTy, 32);
9282           break;
9283         case llvm::Type::DoubleTyID:
9284           addFloat(ElemOffset, ElemTy, 64);
9285           break;
9286         case llvm::Type::FP128TyID:
9287           addFloat(ElemOffset, ElemTy, 128);
9288           break;
9289         case llvm::Type::PointerTyID:
9290           if (ElemOffset % 64 == 0) {
9291             pad(ElemOffset);
9292             Elems.push_back(ElemTy);
9293             Size += 64;
9294           }
9295           break;
9296         default:
9297           break;
9298         }
9299       }
9300     }
9301 
9302     // Check if Ty is a usable substitute for the coercion type.
9303     bool isUsableType(llvm::StructType *Ty) const {
9304       return llvm::makeArrayRef(Elems) == Ty->elements();
9305     }
9306 
9307     // Get the coercion type as a literal struct type.
9308     llvm::Type *getType() const {
9309       if (Elems.size() == 1)
9310         return Elems.front();
9311       else
9312         return llvm::StructType::get(Context, Elems);
9313     }
9314   };
9315 };
9316 } // end anonymous namespace
9317 
9318 ABIArgInfo
9319 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9320   if (Ty->isVoidType())
9321     return ABIArgInfo::getIgnore();
9322 
9323   uint64_t Size = getContext().getTypeSize(Ty);
9324 
9325   // Anything too big to fit in registers is passed with an explicit indirect
9326   // pointer / sret pointer.
9327   if (Size > SizeLimit)
9328     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9329 
9330   // Treat an enum type as its underlying type.
9331   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9332     Ty = EnumTy->getDecl()->getIntegerType();
9333 
9334   // Integer types smaller than a register are extended.
9335   if (Size < 64 && Ty->isIntegerType())
9336     return ABIArgInfo::getExtend(Ty);
9337 
9338   if (const auto *EIT = Ty->getAs<ExtIntType>())
9339     if (EIT->getNumBits() < 64)
9340       return ABIArgInfo::getExtend(Ty);
9341 
9342   // Other non-aggregates go in registers.
9343   if (!isAggregateTypeForABI(Ty))
9344     return ABIArgInfo::getDirect();
9345 
9346   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9347   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9348   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9349     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9350 
9351   // This is a small aggregate type that should be passed in registers.
9352   // Build a coercion type from the LLVM struct type.
9353   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9354   if (!StrTy)
9355     return ABIArgInfo::getDirect();
9356 
9357   CoerceBuilder CB(getVMContext(), getDataLayout());
9358   CB.addStruct(0, StrTy);
9359   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9360 
9361   // Try to use the original type for coercion.
9362   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9363 
9364   if (CB.InReg)
9365     return ABIArgInfo::getDirectInReg(CoerceTy);
9366   else
9367     return ABIArgInfo::getDirect(CoerceTy);
9368 }
9369 
9370 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9371                                   QualType Ty) const {
9372   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9373   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9374   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9375     AI.setCoerceToType(ArgTy);
9376 
9377   CharUnits SlotSize = CharUnits::fromQuantity(8);
9378 
9379   CGBuilderTy &Builder = CGF.Builder;
9380   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9381   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9382 
9383   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9384 
9385   Address ArgAddr = Address::invalid();
9386   CharUnits Stride;
9387   switch (AI.getKind()) {
9388   case ABIArgInfo::Expand:
9389   case ABIArgInfo::CoerceAndExpand:
9390   case ABIArgInfo::InAlloca:
9391     llvm_unreachable("Unsupported ABI kind for va_arg");
9392 
9393   case ABIArgInfo::Extend: {
9394     Stride = SlotSize;
9395     CharUnits Offset = SlotSize - TypeInfo.Width;
9396     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9397     break;
9398   }
9399 
9400   case ABIArgInfo::Direct: {
9401     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9402     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9403     ArgAddr = Addr;
9404     break;
9405   }
9406 
9407   case ABIArgInfo::Indirect:
9408   case ABIArgInfo::IndirectAliased:
9409     Stride = SlotSize;
9410     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9411     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9412                       TypeInfo.Align);
9413     break;
9414 
9415   case ABIArgInfo::Ignore:
9416     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9417   }
9418 
9419   // Update VAList.
9420   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9421   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9422 
9423   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9424 }
9425 
9426 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9427   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9428   for (auto &I : FI.arguments())
9429     I.info = classifyType(I.type, 16 * 8);
9430 }
9431 
9432 namespace {
9433 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9434 public:
9435   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9436       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9437 
9438   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9439     return 14;
9440   }
9441 
9442   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9443                                llvm::Value *Address) const override;
9444 };
9445 } // end anonymous namespace
9446 
9447 bool
9448 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9449                                                 llvm::Value *Address) const {
9450   // This is calculated from the LLVM and GCC tables and verified
9451   // against gcc output.  AFAIK all ABIs use the same encoding.
9452 
9453   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9454 
9455   llvm::IntegerType *i8 = CGF.Int8Ty;
9456   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9457   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9458 
9459   // 0-31: the 8-byte general-purpose registers
9460   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9461 
9462   // 32-63: f0-31, the 4-byte floating-point registers
9463   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9464 
9465   //   Y   = 64
9466   //   PSR = 65
9467   //   WIM = 66
9468   //   TBR = 67
9469   //   PC  = 68
9470   //   NPC = 69
9471   //   FSR = 70
9472   //   CSR = 71
9473   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9474 
9475   // 72-87: d0-15, the 8-byte floating-point registers
9476   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9477 
9478   return false;
9479 }
9480 
9481 // ARC ABI implementation.
9482 namespace {
9483 
9484 class ARCABIInfo : public DefaultABIInfo {
9485 public:
9486   using DefaultABIInfo::DefaultABIInfo;
9487 
9488 private:
9489   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9490                     QualType Ty) const override;
9491 
9492   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9493     if (!State.FreeRegs)
9494       return;
9495     if (Info.isIndirect() && Info.getInReg())
9496       State.FreeRegs--;
9497     else if (Info.isDirect() && Info.getInReg()) {
9498       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9499       if (sz < State.FreeRegs)
9500         State.FreeRegs -= sz;
9501       else
9502         State.FreeRegs = 0;
9503     }
9504   }
9505 
9506   void computeInfo(CGFunctionInfo &FI) const override {
9507     CCState State(FI);
9508     // ARC uses 8 registers to pass arguments.
9509     State.FreeRegs = 8;
9510 
9511     if (!getCXXABI().classifyReturnType(FI))
9512       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9513     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9514     for (auto &I : FI.arguments()) {
9515       I.info = classifyArgumentType(I.type, State.FreeRegs);
9516       updateState(I.info, I.type, State);
9517     }
9518   }
9519 
9520   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9521   ABIArgInfo getIndirectByValue(QualType Ty) const;
9522   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9523   ABIArgInfo classifyReturnType(QualType RetTy) const;
9524 };
9525 
9526 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9527 public:
9528   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9529       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9530 };
9531 
9532 
9533 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9534   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9535                        getNaturalAlignIndirect(Ty, false);
9536 }
9537 
9538 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9539   // Compute the byval alignment.
9540   const unsigned MinABIStackAlignInBytes = 4;
9541   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9542   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9543                                  TypeAlign > MinABIStackAlignInBytes);
9544 }
9545 
9546 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9547                               QualType Ty) const {
9548   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9549                           getContext().getTypeInfoInChars(Ty),
9550                           CharUnits::fromQuantity(4), true);
9551 }
9552 
9553 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9554                                             uint8_t FreeRegs) const {
9555   // Handle the generic C++ ABI.
9556   const RecordType *RT = Ty->getAs<RecordType>();
9557   if (RT) {
9558     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9559     if (RAA == CGCXXABI::RAA_Indirect)
9560       return getIndirectByRef(Ty, FreeRegs > 0);
9561 
9562     if (RAA == CGCXXABI::RAA_DirectInMemory)
9563       return getIndirectByValue(Ty);
9564   }
9565 
9566   // Treat an enum type as its underlying type.
9567   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9568     Ty = EnumTy->getDecl()->getIntegerType();
9569 
9570   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9571 
9572   if (isAggregateTypeForABI(Ty)) {
9573     // Structures with flexible arrays are always indirect.
9574     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9575       return getIndirectByValue(Ty);
9576 
9577     // Ignore empty structs/unions.
9578     if (isEmptyRecord(getContext(), Ty, true))
9579       return ABIArgInfo::getIgnore();
9580 
9581     llvm::LLVMContext &LLVMContext = getVMContext();
9582 
9583     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9584     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9585     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9586 
9587     return FreeRegs >= SizeInRegs ?
9588         ABIArgInfo::getDirectInReg(Result) :
9589         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9590   }
9591 
9592   if (const auto *EIT = Ty->getAs<ExtIntType>())
9593     if (EIT->getNumBits() > 64)
9594       return getIndirectByValue(Ty);
9595 
9596   return isPromotableIntegerTypeForABI(Ty)
9597              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9598                                        : ABIArgInfo::getExtend(Ty))
9599              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9600                                        : ABIArgInfo::getDirect());
9601 }
9602 
9603 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9604   if (RetTy->isAnyComplexType())
9605     return ABIArgInfo::getDirectInReg();
9606 
9607   // Arguments of size > 4 registers are indirect.
9608   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9609   if (RetSize > 4)
9610     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9611 
9612   return DefaultABIInfo::classifyReturnType(RetTy);
9613 }
9614 
9615 } // End anonymous namespace.
9616 
9617 //===----------------------------------------------------------------------===//
9618 // XCore ABI Implementation
9619 //===----------------------------------------------------------------------===//
9620 
9621 namespace {
9622 
9623 /// A SmallStringEnc instance is used to build up the TypeString by passing
9624 /// it by reference between functions that append to it.
9625 typedef llvm::SmallString<128> SmallStringEnc;
9626 
9627 /// TypeStringCache caches the meta encodings of Types.
9628 ///
9629 /// The reason for caching TypeStrings is two fold:
9630 ///   1. To cache a type's encoding for later uses;
9631 ///   2. As a means to break recursive member type inclusion.
9632 ///
9633 /// A cache Entry can have a Status of:
9634 ///   NonRecursive:   The type encoding is not recursive;
9635 ///   Recursive:      The type encoding is recursive;
9636 ///   Incomplete:     An incomplete TypeString;
9637 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9638 ///                   Recursive type encoding.
9639 ///
9640 /// A NonRecursive entry will have all of its sub-members expanded as fully
9641 /// as possible. Whilst it may contain types which are recursive, the type
9642 /// itself is not recursive and thus its encoding may be safely used whenever
9643 /// the type is encountered.
9644 ///
9645 /// A Recursive entry will have all of its sub-members expanded as fully as
9646 /// possible. The type itself is recursive and it may contain other types which
9647 /// are recursive. The Recursive encoding must not be used during the expansion
9648 /// of a recursive type's recursive branch. For simplicity the code uses
9649 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9650 ///
9651 /// An Incomplete entry is always a RecordType and only encodes its
9652 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9653 /// are placed into the cache during type expansion as a means to identify and
9654 /// handle recursive inclusion of types as sub-members. If there is recursion
9655 /// the entry becomes IncompleteUsed.
9656 ///
9657 /// During the expansion of a RecordType's members:
9658 ///
9659 ///   If the cache contains a NonRecursive encoding for the member type, the
9660 ///   cached encoding is used;
9661 ///
9662 ///   If the cache contains a Recursive encoding for the member type, the
9663 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9664 ///
9665 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9666 ///   cache to break potential recursive inclusion of itself as a sub-member;
9667 ///
9668 ///   Once a member RecordType has been expanded, its temporary incomplete
9669 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9670 ///   it is swapped back in;
9671 ///
9672 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9673 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9674 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9675 ///
9676 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9677 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9678 ///   Else the member is part of a recursive type and thus the recursion has
9679 ///   been exited too soon for the encoding to be correct for the member.
9680 ///
9681 class TypeStringCache {
9682   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9683   struct Entry {
9684     std::string Str;     // The encoded TypeString for the type.
9685     enum Status State;   // Information about the encoding in 'Str'.
9686     std::string Swapped; // A temporary place holder for a Recursive encoding
9687                          // during the expansion of RecordType's members.
9688   };
9689   std::map<const IdentifierInfo *, struct Entry> Map;
9690   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9691   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9692 public:
9693   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9694   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9695   bool removeIncomplete(const IdentifierInfo *ID);
9696   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9697                      bool IsRecursive);
9698   StringRef lookupStr(const IdentifierInfo *ID);
9699 };
9700 
9701 /// TypeString encodings for enum & union fields must be order.
9702 /// FieldEncoding is a helper for this ordering process.
9703 class FieldEncoding {
9704   bool HasName;
9705   std::string Enc;
9706 public:
9707   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9708   StringRef str() { return Enc; }
9709   bool operator<(const FieldEncoding &rhs) const {
9710     if (HasName != rhs.HasName) return HasName;
9711     return Enc < rhs.Enc;
9712   }
9713 };
9714 
9715 class XCoreABIInfo : public DefaultABIInfo {
9716 public:
9717   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9718   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9719                     QualType Ty) const override;
9720 };
9721 
9722 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9723   mutable TypeStringCache TSC;
9724   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9725                     const CodeGen::CodeGenModule &M) const;
9726 
9727 public:
9728   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9729       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9730   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9731                           const llvm::MapVector<GlobalDecl, StringRef>
9732                               &MangledDeclNames) const override;
9733 };
9734 
9735 } // End anonymous namespace.
9736 
9737 // TODO: this implementation is likely now redundant with the default
9738 // EmitVAArg.
9739 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9740                                 QualType Ty) const {
9741   CGBuilderTy &Builder = CGF.Builder;
9742 
9743   // Get the VAList.
9744   CharUnits SlotSize = CharUnits::fromQuantity(4);
9745   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9746 
9747   // Handle the argument.
9748   ABIArgInfo AI = classifyArgumentType(Ty);
9749   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9750   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9751   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9752     AI.setCoerceToType(ArgTy);
9753   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9754 
9755   Address Val = Address::invalid();
9756   CharUnits ArgSize = CharUnits::Zero();
9757   switch (AI.getKind()) {
9758   case ABIArgInfo::Expand:
9759   case ABIArgInfo::CoerceAndExpand:
9760   case ABIArgInfo::InAlloca:
9761     llvm_unreachable("Unsupported ABI kind for va_arg");
9762   case ABIArgInfo::Ignore:
9763     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9764     ArgSize = CharUnits::Zero();
9765     break;
9766   case ABIArgInfo::Extend:
9767   case ABIArgInfo::Direct:
9768     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9769     ArgSize = CharUnits::fromQuantity(
9770                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9771     ArgSize = ArgSize.alignTo(SlotSize);
9772     break;
9773   case ABIArgInfo::Indirect:
9774   case ABIArgInfo::IndirectAliased:
9775     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9776     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9777     ArgSize = SlotSize;
9778     break;
9779   }
9780 
9781   // Increment the VAList.
9782   if (!ArgSize.isZero()) {
9783     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9784     Builder.CreateStore(APN.getPointer(), VAListAddr);
9785   }
9786 
9787   return Val;
9788 }
9789 
9790 /// During the expansion of a RecordType, an incomplete TypeString is placed
9791 /// into the cache as a means to identify and break recursion.
9792 /// If there is a Recursive encoding in the cache, it is swapped out and will
9793 /// be reinserted by removeIncomplete().
9794 /// All other types of encoding should have been used rather than arriving here.
9795 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9796                                     std::string StubEnc) {
9797   if (!ID)
9798     return;
9799   Entry &E = Map[ID];
9800   assert( (E.Str.empty() || E.State == Recursive) &&
9801          "Incorrectly use of addIncomplete");
9802   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9803   E.Swapped.swap(E.Str); // swap out the Recursive
9804   E.Str.swap(StubEnc);
9805   E.State = Incomplete;
9806   ++IncompleteCount;
9807 }
9808 
9809 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9810 /// must be removed from the cache.
9811 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9812 /// Returns true if the RecordType was defined recursively.
9813 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9814   if (!ID)
9815     return false;
9816   auto I = Map.find(ID);
9817   assert(I != Map.end() && "Entry not present");
9818   Entry &E = I->second;
9819   assert( (E.State == Incomplete ||
9820            E.State == IncompleteUsed) &&
9821          "Entry must be an incomplete type");
9822   bool IsRecursive = false;
9823   if (E.State == IncompleteUsed) {
9824     // We made use of our Incomplete encoding, thus we are recursive.
9825     IsRecursive = true;
9826     --IncompleteUsedCount;
9827   }
9828   if (E.Swapped.empty())
9829     Map.erase(I);
9830   else {
9831     // Swap the Recursive back.
9832     E.Swapped.swap(E.Str);
9833     E.Swapped.clear();
9834     E.State = Recursive;
9835   }
9836   --IncompleteCount;
9837   return IsRecursive;
9838 }
9839 
9840 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9841 /// Recursive (viz: all sub-members were expanded as fully as possible).
9842 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9843                                     bool IsRecursive) {
9844   if (!ID || IncompleteUsedCount)
9845     return; // No key or it is is an incomplete sub-type so don't add.
9846   Entry &E = Map[ID];
9847   if (IsRecursive && !E.Str.empty()) {
9848     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9849            "This is not the same Recursive entry");
9850     // The parent container was not recursive after all, so we could have used
9851     // this Recursive sub-member entry after all, but we assumed the worse when
9852     // we started viz: IncompleteCount!=0.
9853     return;
9854   }
9855   assert(E.Str.empty() && "Entry already present");
9856   E.Str = Str.str();
9857   E.State = IsRecursive? Recursive : NonRecursive;
9858 }
9859 
9860 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9861 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9862 /// encoding is Recursive, return an empty StringRef.
9863 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9864   if (!ID)
9865     return StringRef();   // We have no key.
9866   auto I = Map.find(ID);
9867   if (I == Map.end())
9868     return StringRef();   // We have no encoding.
9869   Entry &E = I->second;
9870   if (E.State == Recursive && IncompleteCount)
9871     return StringRef();   // We don't use Recursive encodings for member types.
9872 
9873   if (E.State == Incomplete) {
9874     // The incomplete type is being used to break out of recursion.
9875     E.State = IncompleteUsed;
9876     ++IncompleteUsedCount;
9877   }
9878   return E.Str;
9879 }
9880 
9881 /// The XCore ABI includes a type information section that communicates symbol
9882 /// type information to the linker. The linker uses this information to verify
9883 /// safety/correctness of things such as array bound and pointers et al.
9884 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9885 /// This type information (TypeString) is emitted into meta data for all global
9886 /// symbols: definitions, declarations, functions & variables.
9887 ///
9888 /// The TypeString carries type, qualifier, name, size & value details.
9889 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9890 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9891 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9892 ///
9893 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9894                           const CodeGen::CodeGenModule &CGM,
9895                           TypeStringCache &TSC);
9896 
9897 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9898 void XCoreTargetCodeGenInfo::emitTargetMD(
9899     const Decl *D, llvm::GlobalValue *GV,
9900     const CodeGen::CodeGenModule &CGM) const {
9901   SmallStringEnc Enc;
9902   if (getTypeString(Enc, D, CGM, TSC)) {
9903     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9904     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9905                                 llvm::MDString::get(Ctx, Enc.str())};
9906     llvm::NamedMDNode *MD =
9907       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9908     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9909   }
9910 }
9911 
9912 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9913     CodeGen::CodeGenModule &CGM,
9914     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9915   // Warning, new MangledDeclNames may be appended within this loop.
9916   // We rely on MapVector insertions adding new elements to the end
9917   // of the container.
9918   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9919     auto Val = *(MangledDeclNames.begin() + I);
9920     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9921     if (GV) {
9922       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9923       emitTargetMD(D, GV, CGM);
9924     }
9925   }
9926 }
9927 //===----------------------------------------------------------------------===//
9928 // SPIR ABI Implementation
9929 //===----------------------------------------------------------------------===//
9930 
9931 namespace {
9932 class SPIRABIInfo : public DefaultABIInfo {
9933 public:
9934   SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
9935 
9936 private:
9937   void setCCs();
9938 };
9939 } // end anonymous namespace
9940 namespace {
9941 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9942 public:
9943   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9944       : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
9945   unsigned getOpenCLKernelCallingConv() const override;
9946 };
9947 
9948 } // End anonymous namespace.
9949 void SPIRABIInfo::setCCs() {
9950   assert(getRuntimeCC() == llvm::CallingConv::C);
9951   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
9952 }
9953 
9954 namespace clang {
9955 namespace CodeGen {
9956 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9957   DefaultABIInfo SPIRABI(CGM.getTypes());
9958   SPIRABI.computeInfo(FI);
9959 }
9960 }
9961 }
9962 
9963 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9964   return llvm::CallingConv::SPIR_KERNEL;
9965 }
9966 
9967 static bool appendType(SmallStringEnc &Enc, QualType QType,
9968                        const CodeGen::CodeGenModule &CGM,
9969                        TypeStringCache &TSC);
9970 
9971 /// Helper function for appendRecordType().
9972 /// Builds a SmallVector containing the encoded field types in declaration
9973 /// order.
9974 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9975                              const RecordDecl *RD,
9976                              const CodeGen::CodeGenModule &CGM,
9977                              TypeStringCache &TSC) {
9978   for (const auto *Field : RD->fields()) {
9979     SmallStringEnc Enc;
9980     Enc += "m(";
9981     Enc += Field->getName();
9982     Enc += "){";
9983     if (Field->isBitField()) {
9984       Enc += "b(";
9985       llvm::raw_svector_ostream OS(Enc);
9986       OS << Field->getBitWidthValue(CGM.getContext());
9987       Enc += ':';
9988     }
9989     if (!appendType(Enc, Field->getType(), CGM, TSC))
9990       return false;
9991     if (Field->isBitField())
9992       Enc += ')';
9993     Enc += '}';
9994     FE.emplace_back(!Field->getName().empty(), Enc);
9995   }
9996   return true;
9997 }
9998 
9999 /// Appends structure and union types to Enc and adds encoding to cache.
10000 /// Recursively calls appendType (via extractFieldType) for each field.
10001 /// Union types have their fields ordered according to the ABI.
10002 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10003                              const CodeGen::CodeGenModule &CGM,
10004                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10005   // Append the cached TypeString if we have one.
10006   StringRef TypeString = TSC.lookupStr(ID);
10007   if (!TypeString.empty()) {
10008     Enc += TypeString;
10009     return true;
10010   }
10011 
10012   // Start to emit an incomplete TypeString.
10013   size_t Start = Enc.size();
10014   Enc += (RT->isUnionType()? 'u' : 's');
10015   Enc += '(';
10016   if (ID)
10017     Enc += ID->getName();
10018   Enc += "){";
10019 
10020   // We collect all encoded fields and order as necessary.
10021   bool IsRecursive = false;
10022   const RecordDecl *RD = RT->getDecl()->getDefinition();
10023   if (RD && !RD->field_empty()) {
10024     // An incomplete TypeString stub is placed in the cache for this RecordType
10025     // so that recursive calls to this RecordType will use it whilst building a
10026     // complete TypeString for this RecordType.
10027     SmallVector<FieldEncoding, 16> FE;
10028     std::string StubEnc(Enc.substr(Start).str());
10029     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10030     TSC.addIncomplete(ID, std::move(StubEnc));
10031     if (!extractFieldType(FE, RD, CGM, TSC)) {
10032       (void) TSC.removeIncomplete(ID);
10033       return false;
10034     }
10035     IsRecursive = TSC.removeIncomplete(ID);
10036     // The ABI requires unions to be sorted but not structures.
10037     // See FieldEncoding::operator< for sort algorithm.
10038     if (RT->isUnionType())
10039       llvm::sort(FE);
10040     // We can now complete the TypeString.
10041     unsigned E = FE.size();
10042     for (unsigned I = 0; I != E; ++I) {
10043       if (I)
10044         Enc += ',';
10045       Enc += FE[I].str();
10046     }
10047   }
10048   Enc += '}';
10049   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10050   return true;
10051 }
10052 
10053 /// Appends enum types to Enc and adds the encoding to the cache.
10054 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10055                            TypeStringCache &TSC,
10056                            const IdentifierInfo *ID) {
10057   // Append the cached TypeString if we have one.
10058   StringRef TypeString = TSC.lookupStr(ID);
10059   if (!TypeString.empty()) {
10060     Enc += TypeString;
10061     return true;
10062   }
10063 
10064   size_t Start = Enc.size();
10065   Enc += "e(";
10066   if (ID)
10067     Enc += ID->getName();
10068   Enc += "){";
10069 
10070   // We collect all encoded enumerations and order them alphanumerically.
10071   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10072     SmallVector<FieldEncoding, 16> FE;
10073     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10074          ++I) {
10075       SmallStringEnc EnumEnc;
10076       EnumEnc += "m(";
10077       EnumEnc += I->getName();
10078       EnumEnc += "){";
10079       I->getInitVal().toString(EnumEnc);
10080       EnumEnc += '}';
10081       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10082     }
10083     llvm::sort(FE);
10084     unsigned E = FE.size();
10085     for (unsigned I = 0; I != E; ++I) {
10086       if (I)
10087         Enc += ',';
10088       Enc += FE[I].str();
10089     }
10090   }
10091   Enc += '}';
10092   TSC.addIfComplete(ID, Enc.substr(Start), false);
10093   return true;
10094 }
10095 
10096 /// Appends type's qualifier to Enc.
10097 /// This is done prior to appending the type's encoding.
10098 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10099   // Qualifiers are emitted in alphabetical order.
10100   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10101   int Lookup = 0;
10102   if (QT.isConstQualified())
10103     Lookup += 1<<0;
10104   if (QT.isRestrictQualified())
10105     Lookup += 1<<1;
10106   if (QT.isVolatileQualified())
10107     Lookup += 1<<2;
10108   Enc += Table[Lookup];
10109 }
10110 
10111 /// Appends built-in types to Enc.
10112 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10113   const char *EncType;
10114   switch (BT->getKind()) {
10115     case BuiltinType::Void:
10116       EncType = "0";
10117       break;
10118     case BuiltinType::Bool:
10119       EncType = "b";
10120       break;
10121     case BuiltinType::Char_U:
10122       EncType = "uc";
10123       break;
10124     case BuiltinType::UChar:
10125       EncType = "uc";
10126       break;
10127     case BuiltinType::SChar:
10128       EncType = "sc";
10129       break;
10130     case BuiltinType::UShort:
10131       EncType = "us";
10132       break;
10133     case BuiltinType::Short:
10134       EncType = "ss";
10135       break;
10136     case BuiltinType::UInt:
10137       EncType = "ui";
10138       break;
10139     case BuiltinType::Int:
10140       EncType = "si";
10141       break;
10142     case BuiltinType::ULong:
10143       EncType = "ul";
10144       break;
10145     case BuiltinType::Long:
10146       EncType = "sl";
10147       break;
10148     case BuiltinType::ULongLong:
10149       EncType = "ull";
10150       break;
10151     case BuiltinType::LongLong:
10152       EncType = "sll";
10153       break;
10154     case BuiltinType::Float:
10155       EncType = "ft";
10156       break;
10157     case BuiltinType::Double:
10158       EncType = "d";
10159       break;
10160     case BuiltinType::LongDouble:
10161       EncType = "ld";
10162       break;
10163     default:
10164       return false;
10165   }
10166   Enc += EncType;
10167   return true;
10168 }
10169 
10170 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10171 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10172                               const CodeGen::CodeGenModule &CGM,
10173                               TypeStringCache &TSC) {
10174   Enc += "p(";
10175   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10176     return false;
10177   Enc += ')';
10178   return true;
10179 }
10180 
10181 /// Appends array encoding to Enc before calling appendType for the element.
10182 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10183                             const ArrayType *AT,
10184                             const CodeGen::CodeGenModule &CGM,
10185                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10186   if (AT->getSizeModifier() != ArrayType::Normal)
10187     return false;
10188   Enc += "a(";
10189   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10190     CAT->getSize().toStringUnsigned(Enc);
10191   else
10192     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10193   Enc += ':';
10194   // The Qualifiers should be attached to the type rather than the array.
10195   appendQualifier(Enc, QT);
10196   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10197     return false;
10198   Enc += ')';
10199   return true;
10200 }
10201 
10202 /// Appends a function encoding to Enc, calling appendType for the return type
10203 /// and the arguments.
10204 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10205                              const CodeGen::CodeGenModule &CGM,
10206                              TypeStringCache &TSC) {
10207   Enc += "f{";
10208   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10209     return false;
10210   Enc += "}(";
10211   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10212     // N.B. we are only interested in the adjusted param types.
10213     auto I = FPT->param_type_begin();
10214     auto E = FPT->param_type_end();
10215     if (I != E) {
10216       do {
10217         if (!appendType(Enc, *I, CGM, TSC))
10218           return false;
10219         ++I;
10220         if (I != E)
10221           Enc += ',';
10222       } while (I != E);
10223       if (FPT->isVariadic())
10224         Enc += ",va";
10225     } else {
10226       if (FPT->isVariadic())
10227         Enc += "va";
10228       else
10229         Enc += '0';
10230     }
10231   }
10232   Enc += ')';
10233   return true;
10234 }
10235 
10236 /// Handles the type's qualifier before dispatching a call to handle specific
10237 /// type encodings.
10238 static bool appendType(SmallStringEnc &Enc, QualType QType,
10239                        const CodeGen::CodeGenModule &CGM,
10240                        TypeStringCache &TSC) {
10241 
10242   QualType QT = QType.getCanonicalType();
10243 
10244   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10245     // The Qualifiers should be attached to the type rather than the array.
10246     // Thus we don't call appendQualifier() here.
10247     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10248 
10249   appendQualifier(Enc, QT);
10250 
10251   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10252     return appendBuiltinType(Enc, BT);
10253 
10254   if (const PointerType *PT = QT->getAs<PointerType>())
10255     return appendPointerType(Enc, PT, CGM, TSC);
10256 
10257   if (const EnumType *ET = QT->getAs<EnumType>())
10258     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10259 
10260   if (const RecordType *RT = QT->getAsStructureType())
10261     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10262 
10263   if (const RecordType *RT = QT->getAsUnionType())
10264     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10265 
10266   if (const FunctionType *FT = QT->getAs<FunctionType>())
10267     return appendFunctionType(Enc, FT, CGM, TSC);
10268 
10269   return false;
10270 }
10271 
10272 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10273                           const CodeGen::CodeGenModule &CGM,
10274                           TypeStringCache &TSC) {
10275   if (!D)
10276     return false;
10277 
10278   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10279     if (FD->getLanguageLinkage() != CLanguageLinkage)
10280       return false;
10281     return appendType(Enc, FD->getType(), CGM, TSC);
10282   }
10283 
10284   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10285     if (VD->getLanguageLinkage() != CLanguageLinkage)
10286       return false;
10287     QualType QT = VD->getType().getCanonicalType();
10288     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10289       // Global ArrayTypes are given a size of '*' if the size is unknown.
10290       // The Qualifiers should be attached to the type rather than the array.
10291       // Thus we don't call appendQualifier() here.
10292       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10293     }
10294     return appendType(Enc, QT, CGM, TSC);
10295   }
10296   return false;
10297 }
10298 
10299 //===----------------------------------------------------------------------===//
10300 // RISCV ABI Implementation
10301 //===----------------------------------------------------------------------===//
10302 
10303 namespace {
10304 class RISCVABIInfo : public DefaultABIInfo {
10305 private:
10306   // Size of the integer ('x') registers in bits.
10307   unsigned XLen;
10308   // Size of the floating point ('f') registers in bits. Note that the target
10309   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10310   // with soft float ABI has FLen==0).
10311   unsigned FLen;
10312   static const int NumArgGPRs = 8;
10313   static const int NumArgFPRs = 8;
10314   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10315                                       llvm::Type *&Field1Ty,
10316                                       CharUnits &Field1Off,
10317                                       llvm::Type *&Field2Ty,
10318                                       CharUnits &Field2Off) const;
10319 
10320 public:
10321   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10322       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10323 
10324   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10325   // non-virtual, but computeInfo is virtual, so we overload it.
10326   void computeInfo(CGFunctionInfo &FI) const override;
10327 
10328   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10329                                   int &ArgFPRsLeft) const;
10330   ABIArgInfo classifyReturnType(QualType RetTy) const;
10331 
10332   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10333                     QualType Ty) const override;
10334 
10335   ABIArgInfo extendType(QualType Ty) const;
10336 
10337   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10338                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10339                                 CharUnits &Field2Off, int &NeededArgGPRs,
10340                                 int &NeededArgFPRs) const;
10341   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10342                                                CharUnits Field1Off,
10343                                                llvm::Type *Field2Ty,
10344                                                CharUnits Field2Off) const;
10345 };
10346 } // end anonymous namespace
10347 
10348 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10349   QualType RetTy = FI.getReturnType();
10350   if (!getCXXABI().classifyReturnType(FI))
10351     FI.getReturnInfo() = classifyReturnType(RetTy);
10352 
10353   // IsRetIndirect is true if classifyArgumentType indicated the value should
10354   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10355   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10356   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10357   // list and pass indirectly on RV32.
10358   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10359   if (!IsRetIndirect && RetTy->isScalarType() &&
10360       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10361     if (RetTy->isComplexType() && FLen) {
10362       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10363       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10364     } else {
10365       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10366       IsRetIndirect = true;
10367     }
10368   }
10369 
10370   // We must track the number of GPRs used in order to conform to the RISC-V
10371   // ABI, as integer scalars passed in registers should have signext/zeroext
10372   // when promoted, but are anyext if passed on the stack. As GPR usage is
10373   // different for variadic arguments, we must also track whether we are
10374   // examining a vararg or not.
10375   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10376   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10377   int NumFixedArgs = FI.getNumRequiredArgs();
10378 
10379   int ArgNum = 0;
10380   for (auto &ArgInfo : FI.arguments()) {
10381     bool IsFixed = ArgNum < NumFixedArgs;
10382     ArgInfo.info =
10383         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10384     ArgNum++;
10385   }
10386 }
10387 
10388 // Returns true if the struct is a potential candidate for the floating point
10389 // calling convention. If this function returns true, the caller is
10390 // responsible for checking that if there is only a single field then that
10391 // field is a float.
10392 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10393                                                   llvm::Type *&Field1Ty,
10394                                                   CharUnits &Field1Off,
10395                                                   llvm::Type *&Field2Ty,
10396                                                   CharUnits &Field2Off) const {
10397   bool IsInt = Ty->isIntegralOrEnumerationType();
10398   bool IsFloat = Ty->isRealFloatingType();
10399 
10400   if (IsInt || IsFloat) {
10401     uint64_t Size = getContext().getTypeSize(Ty);
10402     if (IsInt && Size > XLen)
10403       return false;
10404     // Can't be eligible if larger than the FP registers. Half precision isn't
10405     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10406     // default to the integer ABI in that case.
10407     if (IsFloat && (Size > FLen || Size < 32))
10408       return false;
10409     // Can't be eligible if an integer type was already found (int+int pairs
10410     // are not eligible).
10411     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10412       return false;
10413     if (!Field1Ty) {
10414       Field1Ty = CGT.ConvertType(Ty);
10415       Field1Off = CurOff;
10416       return true;
10417     }
10418     if (!Field2Ty) {
10419       Field2Ty = CGT.ConvertType(Ty);
10420       Field2Off = CurOff;
10421       return true;
10422     }
10423     return false;
10424   }
10425 
10426   if (auto CTy = Ty->getAs<ComplexType>()) {
10427     if (Field1Ty)
10428       return false;
10429     QualType EltTy = CTy->getElementType();
10430     if (getContext().getTypeSize(EltTy) > FLen)
10431       return false;
10432     Field1Ty = CGT.ConvertType(EltTy);
10433     Field1Off = CurOff;
10434     Field2Ty = Field1Ty;
10435     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10436     return true;
10437   }
10438 
10439   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10440     uint64_t ArraySize = ATy->getSize().getZExtValue();
10441     QualType EltTy = ATy->getElementType();
10442     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10443     for (uint64_t i = 0; i < ArraySize; ++i) {
10444       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10445                                                 Field1Off, Field2Ty, Field2Off);
10446       if (!Ret)
10447         return false;
10448       CurOff += EltSize;
10449     }
10450     return true;
10451   }
10452 
10453   if (const auto *RTy = Ty->getAs<RecordType>()) {
10454     // Structures with either a non-trivial destructor or a non-trivial
10455     // copy constructor are not eligible for the FP calling convention.
10456     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10457       return false;
10458     if (isEmptyRecord(getContext(), Ty, true))
10459       return true;
10460     const RecordDecl *RD = RTy->getDecl();
10461     // Unions aren't eligible unless they're empty (which is caught above).
10462     if (RD->isUnion())
10463       return false;
10464     int ZeroWidthBitFieldCount = 0;
10465     for (const FieldDecl *FD : RD->fields()) {
10466       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10467       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10468       QualType QTy = FD->getType();
10469       if (FD->isBitField()) {
10470         unsigned BitWidth = FD->getBitWidthValue(getContext());
10471         // Allow a bitfield with a type greater than XLen as long as the
10472         // bitwidth is XLen or less.
10473         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10474           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10475         if (BitWidth == 0) {
10476           ZeroWidthBitFieldCount++;
10477           continue;
10478         }
10479       }
10480 
10481       bool Ret = detectFPCCEligibleStructHelper(
10482           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10483           Field1Ty, Field1Off, Field2Ty, Field2Off);
10484       if (!Ret)
10485         return false;
10486 
10487       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10488       // or int+fp structs, but are ignored for a struct with an fp field and
10489       // any number of zero-width bitfields.
10490       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10491         return false;
10492     }
10493     return Field1Ty != nullptr;
10494   }
10495 
10496   return false;
10497 }
10498 
10499 // Determine if a struct is eligible for passing according to the floating
10500 // point calling convention (i.e., when flattened it contains a single fp
10501 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10502 // NeededArgGPRs are incremented appropriately.
10503 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10504                                             CharUnits &Field1Off,
10505                                             llvm::Type *&Field2Ty,
10506                                             CharUnits &Field2Off,
10507                                             int &NeededArgGPRs,
10508                                             int &NeededArgFPRs) const {
10509   Field1Ty = nullptr;
10510   Field2Ty = nullptr;
10511   NeededArgGPRs = 0;
10512   NeededArgFPRs = 0;
10513   bool IsCandidate = detectFPCCEligibleStructHelper(
10514       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10515   // Not really a candidate if we have a single int but no float.
10516   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10517     return false;
10518   if (!IsCandidate)
10519     return false;
10520   if (Field1Ty && Field1Ty->isFloatingPointTy())
10521     NeededArgFPRs++;
10522   else if (Field1Ty)
10523     NeededArgGPRs++;
10524   if (Field2Ty && Field2Ty->isFloatingPointTy())
10525     NeededArgFPRs++;
10526   else if (Field2Ty)
10527     NeededArgGPRs++;
10528   return true;
10529 }
10530 
10531 // Call getCoerceAndExpand for the two-element flattened struct described by
10532 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10533 // appropriate coerceToType and unpaddedCoerceToType.
10534 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10535     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10536     CharUnits Field2Off) const {
10537   SmallVector<llvm::Type *, 3> CoerceElts;
10538   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10539   if (!Field1Off.isZero())
10540     CoerceElts.push_back(llvm::ArrayType::get(
10541         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10542 
10543   CoerceElts.push_back(Field1Ty);
10544   UnpaddedCoerceElts.push_back(Field1Ty);
10545 
10546   if (!Field2Ty) {
10547     return ABIArgInfo::getCoerceAndExpand(
10548         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10549         UnpaddedCoerceElts[0]);
10550   }
10551 
10552   CharUnits Field2Align =
10553       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10554   CharUnits Field1End = Field1Off +
10555       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10556   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10557 
10558   CharUnits Padding = CharUnits::Zero();
10559   if (Field2Off > Field2OffNoPadNoPack)
10560     Padding = Field2Off - Field2OffNoPadNoPack;
10561   else if (Field2Off != Field2Align && Field2Off > Field1End)
10562     Padding = Field2Off - Field1End;
10563 
10564   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10565 
10566   if (!Padding.isZero())
10567     CoerceElts.push_back(llvm::ArrayType::get(
10568         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10569 
10570   CoerceElts.push_back(Field2Ty);
10571   UnpaddedCoerceElts.push_back(Field2Ty);
10572 
10573   auto CoerceToType =
10574       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10575   auto UnpaddedCoerceToType =
10576       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10577 
10578   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10579 }
10580 
10581 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10582                                               int &ArgGPRsLeft,
10583                                               int &ArgFPRsLeft) const {
10584   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10585   Ty = useFirstFieldIfTransparentUnion(Ty);
10586 
10587   // Structures with either a non-trivial destructor or a non-trivial
10588   // copy constructor are always passed indirectly.
10589   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10590     if (ArgGPRsLeft)
10591       ArgGPRsLeft -= 1;
10592     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10593                                            CGCXXABI::RAA_DirectInMemory);
10594   }
10595 
10596   // Ignore empty structs/unions.
10597   if (isEmptyRecord(getContext(), Ty, true))
10598     return ABIArgInfo::getIgnore();
10599 
10600   uint64_t Size = getContext().getTypeSize(Ty);
10601 
10602   // Pass floating point values via FPRs if possible.
10603   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10604       FLen >= Size && ArgFPRsLeft) {
10605     ArgFPRsLeft--;
10606     return ABIArgInfo::getDirect();
10607   }
10608 
10609   // Complex types for the hard float ABI must be passed direct rather than
10610   // using CoerceAndExpand.
10611   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10612     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10613     if (getContext().getTypeSize(EltTy) <= FLen) {
10614       ArgFPRsLeft -= 2;
10615       return ABIArgInfo::getDirect();
10616     }
10617   }
10618 
10619   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10620     llvm::Type *Field1Ty = nullptr;
10621     llvm::Type *Field2Ty = nullptr;
10622     CharUnits Field1Off = CharUnits::Zero();
10623     CharUnits Field2Off = CharUnits::Zero();
10624     int NeededArgGPRs;
10625     int NeededArgFPRs;
10626     bool IsCandidate =
10627         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10628                                  NeededArgGPRs, NeededArgFPRs);
10629     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10630         NeededArgFPRs <= ArgFPRsLeft) {
10631       ArgGPRsLeft -= NeededArgGPRs;
10632       ArgFPRsLeft -= NeededArgFPRs;
10633       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10634                                                Field2Off);
10635     }
10636   }
10637 
10638   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10639   bool MustUseStack = false;
10640   // Determine the number of GPRs needed to pass the current argument
10641   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10642   // register pairs, so may consume 3 registers.
10643   int NeededArgGPRs = 1;
10644   if (!IsFixed && NeededAlign == 2 * XLen)
10645     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10646   else if (Size > XLen && Size <= 2 * XLen)
10647     NeededArgGPRs = 2;
10648 
10649   if (NeededArgGPRs > ArgGPRsLeft) {
10650     MustUseStack = true;
10651     NeededArgGPRs = ArgGPRsLeft;
10652   }
10653 
10654   ArgGPRsLeft -= NeededArgGPRs;
10655 
10656   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10657     // Treat an enum type as its underlying type.
10658     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10659       Ty = EnumTy->getDecl()->getIntegerType();
10660 
10661     // All integral types are promoted to XLen width, unless passed on the
10662     // stack.
10663     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10664       return extendType(Ty);
10665     }
10666 
10667     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10668       if (EIT->getNumBits() < XLen && !MustUseStack)
10669         return extendType(Ty);
10670       if (EIT->getNumBits() > 128 ||
10671           (!getContext().getTargetInfo().hasInt128Type() &&
10672            EIT->getNumBits() > 64))
10673         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10674     }
10675 
10676     return ABIArgInfo::getDirect();
10677   }
10678 
10679   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10680   // so coerce to integers.
10681   if (Size <= 2 * XLen) {
10682     unsigned Alignment = getContext().getTypeAlign(Ty);
10683 
10684     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10685     // required, and a 2-element XLen array if only XLen alignment is required.
10686     if (Size <= XLen) {
10687       return ABIArgInfo::getDirect(
10688           llvm::IntegerType::get(getVMContext(), XLen));
10689     } else if (Alignment == 2 * XLen) {
10690       return ABIArgInfo::getDirect(
10691           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10692     } else {
10693       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10694           llvm::IntegerType::get(getVMContext(), XLen), 2));
10695     }
10696   }
10697   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10698 }
10699 
10700 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10701   if (RetTy->isVoidType())
10702     return ABIArgInfo::getIgnore();
10703 
10704   int ArgGPRsLeft = 2;
10705   int ArgFPRsLeft = FLen ? 2 : 0;
10706 
10707   // The rules for return and argument types are the same, so defer to
10708   // classifyArgumentType.
10709   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10710                               ArgFPRsLeft);
10711 }
10712 
10713 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10714                                 QualType Ty) const {
10715   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10716 
10717   // Empty records are ignored for parameter passing purposes.
10718   if (isEmptyRecord(getContext(), Ty, true)) {
10719     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10720     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10721     return Addr;
10722   }
10723 
10724   auto TInfo = getContext().getTypeInfoInChars(Ty);
10725 
10726   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10727   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10728 
10729   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10730                           SlotSize, /*AllowHigherAlign=*/true);
10731 }
10732 
10733 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10734   int TySize = getContext().getTypeSize(Ty);
10735   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10736   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10737     return ABIArgInfo::getSignExtend(Ty);
10738   return ABIArgInfo::getExtend(Ty);
10739 }
10740 
10741 namespace {
10742 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10743 public:
10744   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10745                          unsigned FLen)
10746       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10747 
10748   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10749                            CodeGen::CodeGenModule &CGM) const override {
10750     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10751     if (!FD) return;
10752 
10753     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10754     if (!Attr)
10755       return;
10756 
10757     const char *Kind;
10758     switch (Attr->getInterrupt()) {
10759     case RISCVInterruptAttr::user: Kind = "user"; break;
10760     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10761     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10762     }
10763 
10764     auto *Fn = cast<llvm::Function>(GV);
10765 
10766     Fn->addFnAttr("interrupt", Kind);
10767   }
10768 };
10769 } // namespace
10770 
10771 //===----------------------------------------------------------------------===//
10772 // VE ABI Implementation.
10773 //
10774 namespace {
10775 class VEABIInfo : public DefaultABIInfo {
10776 public:
10777   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10778 
10779 private:
10780   ABIArgInfo classifyReturnType(QualType RetTy) const;
10781   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10782   void computeInfo(CGFunctionInfo &FI) const override;
10783 };
10784 } // end anonymous namespace
10785 
10786 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10787   if (Ty->isAnyComplexType())
10788     return ABIArgInfo::getDirect();
10789   uint64_t Size = getContext().getTypeSize(Ty);
10790   if (Size < 64 && Ty->isIntegerType())
10791     return ABIArgInfo::getExtend(Ty);
10792   return DefaultABIInfo::classifyReturnType(Ty);
10793 }
10794 
10795 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10796   if (Ty->isAnyComplexType())
10797     return ABIArgInfo::getDirect();
10798   uint64_t Size = getContext().getTypeSize(Ty);
10799   if (Size < 64 && Ty->isIntegerType())
10800     return ABIArgInfo::getExtend(Ty);
10801   return DefaultABIInfo::classifyArgumentType(Ty);
10802 }
10803 
10804 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10805   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10806   for (auto &Arg : FI.arguments())
10807     Arg.info = classifyArgumentType(Arg.type);
10808 }
10809 
10810 namespace {
10811 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10812 public:
10813   VETargetCodeGenInfo(CodeGenTypes &CGT)
10814       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10815   // VE ABI requires the arguments of variadic and prototype-less functions
10816   // are passed in both registers and memory.
10817   bool isNoProtoCallVariadic(const CallArgList &args,
10818                              const FunctionNoProtoType *fnType) const override {
10819     return true;
10820   }
10821 };
10822 } // end anonymous namespace
10823 
10824 //===----------------------------------------------------------------------===//
10825 // Driver code
10826 //===----------------------------------------------------------------------===//
10827 
10828 bool CodeGenModule::supportsCOMDAT() const {
10829   return getTriple().supportsCOMDAT();
10830 }
10831 
10832 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10833   if (TheTargetCodeGenInfo)
10834     return *TheTargetCodeGenInfo;
10835 
10836   // Helper to set the unique_ptr while still keeping the return value.
10837   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10838     this->TheTargetCodeGenInfo.reset(P);
10839     return *P;
10840   };
10841 
10842   const llvm::Triple &Triple = getTarget().getTriple();
10843   switch (Triple.getArch()) {
10844   default:
10845     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10846 
10847   case llvm::Triple::le32:
10848     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10849   case llvm::Triple::mips:
10850   case llvm::Triple::mipsel:
10851     if (Triple.getOS() == llvm::Triple::NaCl)
10852       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10853     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10854 
10855   case llvm::Triple::mips64:
10856   case llvm::Triple::mips64el:
10857     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10858 
10859   case llvm::Triple::avr:
10860     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10861 
10862   case llvm::Triple::aarch64:
10863   case llvm::Triple::aarch64_32:
10864   case llvm::Triple::aarch64_be: {
10865     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10866     if (getTarget().getABI() == "darwinpcs")
10867       Kind = AArch64ABIInfo::DarwinPCS;
10868     else if (Triple.isOSWindows())
10869       return SetCGInfo(
10870           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10871 
10872     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10873   }
10874 
10875   case llvm::Triple::wasm32:
10876   case llvm::Triple::wasm64: {
10877     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10878     if (getTarget().getABI() == "experimental-mv")
10879       Kind = WebAssemblyABIInfo::ExperimentalMV;
10880     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10881   }
10882 
10883   case llvm::Triple::arm:
10884   case llvm::Triple::armeb:
10885   case llvm::Triple::thumb:
10886   case llvm::Triple::thumbeb: {
10887     if (Triple.getOS() == llvm::Triple::Win32) {
10888       return SetCGInfo(
10889           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10890     }
10891 
10892     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10893     StringRef ABIStr = getTarget().getABI();
10894     if (ABIStr == "apcs-gnu")
10895       Kind = ARMABIInfo::APCS;
10896     else if (ABIStr == "aapcs16")
10897       Kind = ARMABIInfo::AAPCS16_VFP;
10898     else if (CodeGenOpts.FloatABI == "hard" ||
10899              (CodeGenOpts.FloatABI != "soft" &&
10900               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10901                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10902                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10903       Kind = ARMABIInfo::AAPCS_VFP;
10904 
10905     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10906   }
10907 
10908   case llvm::Triple::ppc: {
10909     if (Triple.isOSAIX())
10910       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10911 
10912     bool IsSoftFloat =
10913         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10914     bool RetSmallStructInRegABI =
10915         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10916     return SetCGInfo(
10917         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10918   }
10919   case llvm::Triple::ppcle: {
10920     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10921     bool RetSmallStructInRegABI =
10922         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10923     return SetCGInfo(
10924         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10925   }
10926   case llvm::Triple::ppc64:
10927     if (Triple.isOSAIX())
10928       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10929 
10930     if (Triple.isOSBinFormatELF()) {
10931       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10932       if (getTarget().getABI() == "elfv2")
10933         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10934       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10935 
10936       return SetCGInfo(
10937           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10938     }
10939     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10940   case llvm::Triple::ppc64le: {
10941     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10942     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10943     if (getTarget().getABI() == "elfv1")
10944       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10945     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10946 
10947     return SetCGInfo(
10948         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10949   }
10950 
10951   case llvm::Triple::nvptx:
10952   case llvm::Triple::nvptx64:
10953     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10954 
10955   case llvm::Triple::msp430:
10956     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10957 
10958   case llvm::Triple::riscv32:
10959   case llvm::Triple::riscv64: {
10960     StringRef ABIStr = getTarget().getABI();
10961     unsigned XLen = getTarget().getPointerWidth(0);
10962     unsigned ABIFLen = 0;
10963     if (ABIStr.endswith("f"))
10964       ABIFLen = 32;
10965     else if (ABIStr.endswith("d"))
10966       ABIFLen = 64;
10967     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10968   }
10969 
10970   case llvm::Triple::systemz: {
10971     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
10972     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
10973     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
10974   }
10975 
10976   case llvm::Triple::tce:
10977   case llvm::Triple::tcele:
10978     return SetCGInfo(new TCETargetCodeGenInfo(Types));
10979 
10980   case llvm::Triple::x86: {
10981     bool IsDarwinVectorABI = Triple.isOSDarwin();
10982     bool RetSmallStructInRegABI =
10983         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10984     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
10985 
10986     if (Triple.getOS() == llvm::Triple::Win32) {
10987       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
10988           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10989           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
10990     } else {
10991       return SetCGInfo(new X86_32TargetCodeGenInfo(
10992           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10993           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
10994           CodeGenOpts.FloatABI == "soft"));
10995     }
10996   }
10997 
10998   case llvm::Triple::x86_64: {
10999     StringRef ABI = getTarget().getABI();
11000     X86AVXABILevel AVXLevel =
11001         (ABI == "avx512"
11002              ? X86AVXABILevel::AVX512
11003              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11004 
11005     switch (Triple.getOS()) {
11006     case llvm::Triple::Win32:
11007       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11008     default:
11009       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11010     }
11011   }
11012   case llvm::Triple::hexagon:
11013     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11014   case llvm::Triple::lanai:
11015     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11016   case llvm::Triple::r600:
11017     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11018   case llvm::Triple::amdgcn:
11019     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11020   case llvm::Triple::sparc:
11021     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11022   case llvm::Triple::sparcv9:
11023     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11024   case llvm::Triple::xcore:
11025     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11026   case llvm::Triple::arc:
11027     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11028   case llvm::Triple::spir:
11029   case llvm::Triple::spir64:
11030     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11031   case llvm::Triple::ve:
11032     return SetCGInfo(new VETargetCodeGenInfo(Types));
11033   }
11034 }
11035 
11036 /// Create an OpenCL kernel for an enqueued block.
11037 ///
11038 /// The kernel has the same function type as the block invoke function. Its
11039 /// name is the name of the block invoke function postfixed with "_kernel".
11040 /// It simply calls the block invoke function then returns.
11041 llvm::Function *
11042 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11043                                              llvm::Function *Invoke,
11044                                              llvm::Value *BlockLiteral) const {
11045   auto *InvokeFT = Invoke->getFunctionType();
11046   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11047   for (auto &P : InvokeFT->params())
11048     ArgTys.push_back(P);
11049   auto &C = CGF.getLLVMContext();
11050   std::string Name = Invoke->getName().str() + "_kernel";
11051   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11052   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11053                                    &CGF.CGM.getModule());
11054   auto IP = CGF.Builder.saveIP();
11055   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11056   auto &Builder = CGF.Builder;
11057   Builder.SetInsertPoint(BB);
11058   llvm::SmallVector<llvm::Value *, 2> Args;
11059   for (auto &A : F->args())
11060     Args.push_back(&A);
11061   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11062   call->setCallingConv(Invoke->getCallingConv());
11063   Builder.CreateRetVoid();
11064   Builder.restoreIP(IP);
11065   return F;
11066 }
11067 
11068 /// Create an OpenCL kernel for an enqueued block.
11069 ///
11070 /// The type of the first argument (the block literal) is the struct type
11071 /// of the block literal instead of a pointer type. The first argument
11072 /// (block literal) is passed directly by value to the kernel. The kernel
11073 /// allocates the same type of struct on stack and stores the block literal
11074 /// to it and passes its pointer to the block invoke function. The kernel
11075 /// has "enqueued-block" function attribute and kernel argument metadata.
11076 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11077     CodeGenFunction &CGF, llvm::Function *Invoke,
11078     llvm::Value *BlockLiteral) const {
11079   auto &Builder = CGF.Builder;
11080   auto &C = CGF.getLLVMContext();
11081 
11082   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11083   auto *InvokeFT = Invoke->getFunctionType();
11084   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11085   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11086   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11087   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11088   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11089   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11090   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11091 
11092   ArgTys.push_back(BlockTy);
11093   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11094   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11095   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11096   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11097   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11098   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11099   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11100     ArgTys.push_back(InvokeFT->getParamType(I));
11101     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11102     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11103     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11104     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11105     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11106     ArgNames.push_back(
11107         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11108   }
11109   std::string Name = Invoke->getName().str() + "_kernel";
11110   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11111   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11112                                    &CGF.CGM.getModule());
11113   F->addFnAttr("enqueued-block");
11114   auto IP = CGF.Builder.saveIP();
11115   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11116   Builder.SetInsertPoint(BB);
11117   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11118   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11119   BlockPtr->setAlignment(BlockAlign);
11120   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11121   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11122   llvm::SmallVector<llvm::Value *, 2> Args;
11123   Args.push_back(Cast);
11124   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11125     Args.push_back(I);
11126   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11127   call->setCallingConv(Invoke->getCallingConv());
11128   Builder.CreateRetVoid();
11129   Builder.restoreIP(IP);
11130 
11131   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11132   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11133   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11134   F->setMetadata("kernel_arg_base_type",
11135                  llvm::MDNode::get(C, ArgBaseTypeNames));
11136   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11137   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11138     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11139 
11140   return F;
11141 }
11142