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/Basic/Builtins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/CodeGen/SwiftCallingConv.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/IntrinsicsNVPTX.h"
34 #include "llvm/IR/IntrinsicsS390.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm> // std::sort
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 // Helper for coercing an aggregate argument or return value into an integer
43 // array of the same size (including padding) and alignment.  This alternate
44 // coercion happens only for the RenderScript ABI and can be removed after
45 // runtimes that rely on it are no longer supported.
46 //
47 // RenderScript assumes that the size of the argument / return value in the IR
48 // is the same as the size of the corresponding qualified type. This helper
49 // coerces the aggregate type into an array of the same size (including
50 // padding).  This coercion is used in lieu of expansion of struct members or
51 // other canonical coercions that return a coerced-type of larger size.
52 //
53 // Ty          - The argument / return value type
54 // Context     - The associated ASTContext
55 // LLVMContext - The associated LLVMContext
56 static ABIArgInfo coerceToIntArray(QualType Ty,
57                                    ASTContext &Context,
58                                    llvm::LLVMContext &LLVMContext) {
59   // Alignment and Size are measured in bits.
60   const uint64_t Size = Context.getTypeSize(Ty);
61   const uint64_t Alignment = Context.getTypeAlign(Ty);
62   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
63   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
64   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
65 }
66 
67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68                                llvm::Value *Array,
69                                llvm::Value *Value,
70                                unsigned FirstIndex,
71                                unsigned LastIndex) {
72   // Alternatively, we could emit this as a loop in the source.
73   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
74     llvm::Value *Cell =
75         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
76     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
77   }
78 }
79 
80 static bool isAggregateTypeForABI(QualType T) {
81   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
82          T->isMemberFunctionPointerType();
83 }
84 
85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
86                                             bool Realign,
87                                             llvm::Type *Padding) const {
88   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
89                                  Realign, Padding);
90 }
91 
92 ABIArgInfo
93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
94   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
95                                       /*ByVal*/ false, Realign);
96 }
97 
98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
99                              QualType Ty) const {
100   return Address::invalid();
101 }
102 
103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
104   if (Ty->isPromotableIntegerType())
105     return true;
106 
107   if (const auto *EIT = Ty->getAs<ExtIntType>())
108     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
109       return true;
110 
111   return false;
112 }
113 
114 ABIInfo::~ABIInfo() {}
115 
116 /// Does the given lowering require more than the given number of
117 /// registers when expanded?
118 ///
119 /// This is intended to be the basis of a reasonable basic implementation
120 /// of should{Pass,Return}IndirectlyForSwift.
121 ///
122 /// For most targets, a limit of four total registers is reasonable; this
123 /// limits the amount of code required in order to move around the value
124 /// in case it wasn't produced immediately prior to the call by the caller
125 /// (or wasn't produced in exactly the right registers) or isn't used
126 /// immediately within the callee.  But some targets may need to further
127 /// limit the register count due to an inability to support that many
128 /// return registers.
129 static bool occupiesMoreThan(CodeGenTypes &cgt,
130                              ArrayRef<llvm::Type*> scalarTypes,
131                              unsigned maxAllRegisters) {
132   unsigned intCount = 0, fpCount = 0;
133   for (llvm::Type *type : scalarTypes) {
134     if (type->isPointerTy()) {
135       intCount++;
136     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
137       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
138       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
139     } else {
140       assert(type->isVectorTy() || type->isFloatingPointTy());
141       fpCount++;
142     }
143   }
144 
145   return (intCount + fpCount > maxAllRegisters);
146 }
147 
148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
149                                              llvm::Type *eltTy,
150                                              unsigned numElts) const {
151   // The default implementation of this assumes that the target guarantees
152   // 128-bit SIMD support but nothing more.
153   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
154 }
155 
156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
157                                               CGCXXABI &CXXABI) {
158   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
159   if (!RD) {
160     if (!RT->getDecl()->canPassInRegisters())
161       return CGCXXABI::RAA_Indirect;
162     return CGCXXABI::RAA_Default;
163   }
164   return CXXABI.getRecordArgABI(RD);
165 }
166 
167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
168                                               CGCXXABI &CXXABI) {
169   const RecordType *RT = T->getAs<RecordType>();
170   if (!RT)
171     return CGCXXABI::RAA_Default;
172   return getRecordArgABI(RT, CXXABI);
173 }
174 
175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
176                                const ABIInfo &Info) {
177   QualType Ty = FI.getReturnType();
178 
179   if (const auto *RT = Ty->getAs<RecordType>())
180     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
181         !RT->getDecl()->canPassInRegisters()) {
182       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
183       return true;
184     }
185 
186   return CXXABI.classifyReturnType(FI);
187 }
188 
189 /// Pass transparent unions as if they were the type of the first element. Sema
190 /// should ensure that all elements of the union have the same "machine type".
191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
192   if (const RecordType *UT = Ty->getAsUnionType()) {
193     const RecordDecl *UD = UT->getDecl();
194     if (UD->hasAttr<TransparentUnionAttr>()) {
195       assert(!UD->field_empty() && "sema created an empty transparent union");
196       return UD->field_begin()->getType();
197     }
198   }
199   return Ty;
200 }
201 
202 CGCXXABI &ABIInfo::getCXXABI() const {
203   return CGT.getCXXABI();
204 }
205 
206 ASTContext &ABIInfo::getContext() const {
207   return CGT.getContext();
208 }
209 
210 llvm::LLVMContext &ABIInfo::getVMContext() const {
211   return CGT.getLLVMContext();
212 }
213 
214 const llvm::DataLayout &ABIInfo::getDataLayout() const {
215   return CGT.getDataLayout();
216 }
217 
218 const TargetInfo &ABIInfo::getTarget() const {
219   return CGT.getTarget();
220 }
221 
222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
223   return CGT.getCodeGenOpts();
224 }
225 
226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
227 
228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
229   return false;
230 }
231 
232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
233                                                 uint64_t Members) const {
234   return false;
235 }
236 
237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
238   raw_ostream &OS = llvm::errs();
239   OS << "(ABIArgInfo Kind=";
240   switch (TheKind) {
241   case Direct:
242     OS << "Direct Type=";
243     if (llvm::Type *Ty = getCoerceToType())
244       Ty->print(OS);
245     else
246       OS << "null";
247     break;
248   case Extend:
249     OS << "Extend";
250     break;
251   case Ignore:
252     OS << "Ignore";
253     break;
254   case InAlloca:
255     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
256     break;
257   case Indirect:
258     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
259        << " ByVal=" << getIndirectByVal()
260        << " Realign=" << getIndirectRealign();
261     break;
262   case IndirectAliased:
263     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264        << " AadrSpace=" << getIndirectAddrSpace()
265        << " Realign=" << getIndirectRealign();
266     break;
267   case Expand:
268     OS << "Expand";
269     break;
270   case CoerceAndExpand:
271     OS << "CoerceAndExpand Type=";
272     getCoerceAndExpandType()->print(OS);
273     break;
274   }
275   OS << ")\n";
276 }
277 
278 // Dynamically round a pointer up to a multiple of the given alignment.
279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
280                                                   llvm::Value *Ptr,
281                                                   CharUnits Align) {
282   llvm::Value *PtrAsInt = Ptr;
283   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
284   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
285   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
286         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
287   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
288            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
289   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
290                                         Ptr->getType(),
291                                         Ptr->getName() + ".aligned");
292   return PtrAsInt;
293 }
294 
295 /// Emit va_arg for a platform using the common void* representation,
296 /// where arguments are simply emitted in an array of slots on the stack.
297 ///
298 /// This version implements the core direct-value passing rules.
299 ///
300 /// \param SlotSize - The size and alignment of a stack slot.
301 ///   Each argument will be allocated to a multiple of this number of
302 ///   slots, and all the slots will be aligned to this value.
303 /// \param AllowHigherAlign - The slot alignment is not a cap;
304 ///   an argument type with an alignment greater than the slot size
305 ///   will be emitted on a higher-alignment address, potentially
306 ///   leaving one or more empty slots behind as padding.  If this
307 ///   is false, the returned address might be less-aligned than
308 ///   DirectAlign.
309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
310                                       Address VAListAddr,
311                                       llvm::Type *DirectTy,
312                                       CharUnits DirectSize,
313                                       CharUnits DirectAlign,
314                                       CharUnits SlotSize,
315                                       bool AllowHigherAlign) {
316   // Cast the element type to i8* if necessary.  Some platforms define
317   // va_list as a struct containing an i8* instead of just an i8*.
318   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
319     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
320 
321   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
322 
323   // If the CC aligns values higher than the slot size, do so if needed.
324   Address Addr = Address::invalid();
325   if (AllowHigherAlign && DirectAlign > SlotSize) {
326     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
327                                                  DirectAlign);
328   } else {
329     Addr = Address(Ptr, SlotSize);
330   }
331 
332   // Advance the pointer past the argument, then store that back.
333   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
334   Address NextPtr =
335       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
336   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
337 
338   // If the argument is smaller than a slot, and this is a big-endian
339   // target, the argument will be right-adjusted in its slot.
340   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
341       !DirectTy->isStructTy()) {
342     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
343   }
344 
345   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
346   return Addr;
347 }
348 
349 /// Emit va_arg for a platform using the common void* representation,
350 /// where arguments are simply emitted in an array of slots on the stack.
351 ///
352 /// \param IsIndirect - Values of this type are passed indirectly.
353 /// \param ValueInfo - The size and alignment of this type, generally
354 ///   computed with getContext().getTypeInfoInChars(ValueTy).
355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
356 ///   Each argument will be allocated to a multiple of this number of
357 ///   slots, and all the slots will be aligned to this value.
358 /// \param AllowHigherAlign - The slot alignment is not a cap;
359 ///   an argument type with an alignment greater than the slot size
360 ///   will be emitted on a higher-alignment address, potentially
361 ///   leaving one or more empty slots behind as padding.
362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
363                                 QualType ValueTy, bool IsIndirect,
364                                 TypeInfoChars ValueInfo,
365                                 CharUnits SlotSizeAndAlign,
366                                 bool AllowHigherAlign) {
367   // The size and alignment of the value that was passed directly.
368   CharUnits DirectSize, DirectAlign;
369   if (IsIndirect) {
370     DirectSize = CGF.getPointerSize();
371     DirectAlign = CGF.getPointerAlign();
372   } else {
373     DirectSize = ValueInfo.Width;
374     DirectAlign = ValueInfo.Align;
375   }
376 
377   // Cast the address we've calculated to the right type.
378   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
379   if (IsIndirect)
380     DirectTy = DirectTy->getPointerTo(0);
381 
382   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
383                                         DirectSize, DirectAlign,
384                                         SlotSizeAndAlign,
385                                         AllowHigherAlign);
386 
387   if (IsIndirect) {
388     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
389   }
390 
391   return Addr;
392 
393 }
394 
395 static Address emitMergePHI(CodeGenFunction &CGF,
396                             Address Addr1, llvm::BasicBlock *Block1,
397                             Address Addr2, llvm::BasicBlock *Block2,
398                             const llvm::Twine &Name = "") {
399   assert(Addr1.getType() == Addr2.getType());
400   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
401   PHI->addIncoming(Addr1.getPointer(), Block1);
402   PHI->addIncoming(Addr2.getPointer(), Block2);
403   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
404   return Address(PHI, Align);
405 }
406 
407 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
408 
409 // If someone can figure out a general rule for this, that would be great.
410 // It's probably just doomed to be platform-dependent, though.
411 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
412   // Verified for:
413   //   x86-64     FreeBSD, Linux, Darwin
414   //   x86-32     FreeBSD, Linux, Darwin
415   //   PowerPC    Linux, Darwin
416   //   ARM        Darwin (*not* EABI)
417   //   AArch64    Linux
418   return 32;
419 }
420 
421 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
422                                      const FunctionNoProtoType *fnType) const {
423   // The following conventions are known to require this to be false:
424   //   x86_stdcall
425   //   MIPS
426   // For everything else, we just prefer false unless we opt out.
427   return false;
428 }
429 
430 void
431 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
432                                              llvm::SmallString<24> &Opt) const {
433   // This assumes the user is passing a library name like "rt" instead of a
434   // filename like "librt.a/so", and that they don't care whether it's static or
435   // dynamic.
436   Opt = "-l";
437   Opt += Lib;
438 }
439 
440 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
441   // OpenCL kernels are called via an explicit runtime API with arguments
442   // set with clSetKernelArg(), not as normal sub-functions.
443   // Return SPIR_KERNEL by default as the kernel calling convention to
444   // ensure the fingerprint is fixed such way that each OpenCL argument
445   // gets one matching argument in the produced kernel function argument
446   // list to enable feasible implementation of clSetKernelArg() with
447   // aggregates etc. In case we would use the default C calling conv here,
448   // clSetKernelArg() might break depending on the target-specific
449   // conventions; different targets might split structs passed as values
450   // to multiple function arguments etc.
451   return llvm::CallingConv::SPIR_KERNEL;
452 }
453 
454 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
455     llvm::PointerType *T, QualType QT) const {
456   return llvm::ConstantPointerNull::get(T);
457 }
458 
459 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
460                                                    const VarDecl *D) const {
461   assert(!CGM.getLangOpts().OpenCL &&
462          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
463          "Address space agnostic languages only");
464   return D ? D->getType().getAddressSpace() : LangAS::Default;
465 }
466 
467 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
468     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
469     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
470   // Since target may map different address spaces in AST to the same address
471   // space, an address space conversion may end up as a bitcast.
472   if (auto *C = dyn_cast<llvm::Constant>(Src))
473     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
474   // Try to preserve the source's name to make IR more readable.
475   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
476       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
477 }
478 
479 llvm::Constant *
480 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
481                                         LangAS SrcAddr, LangAS DestAddr,
482                                         llvm::Type *DestTy) const {
483   // Since target may map different address spaces in AST to the same address
484   // space, an address space conversion may end up as a bitcast.
485   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
486 }
487 
488 llvm::SyncScope::ID
489 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
490                                       SyncScope Scope,
491                                       llvm::AtomicOrdering Ordering,
492                                       llvm::LLVMContext &Ctx) const {
493   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
494 }
495 
496 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
497 
498 /// isEmptyField - Return true iff a the field is "empty", that is it
499 /// is an unnamed bit-field or an (array of) empty record(s).
500 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
501                          bool AllowArrays) {
502   if (FD->isUnnamedBitfield())
503     return true;
504 
505   QualType FT = FD->getType();
506 
507   // Constant arrays of empty records count as empty, strip them off.
508   // Constant arrays of zero length always count as empty.
509   bool WasArray = false;
510   if (AllowArrays)
511     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
512       if (AT->getSize() == 0)
513         return true;
514       FT = AT->getElementType();
515       // The [[no_unique_address]] special case below does not apply to
516       // arrays of C++ empty records, so we need to remember this fact.
517       WasArray = true;
518     }
519 
520   const RecordType *RT = FT->getAs<RecordType>();
521   if (!RT)
522     return false;
523 
524   // C++ record fields are never empty, at least in the Itanium ABI.
525   //
526   // FIXME: We should use a predicate for whether this behavior is true in the
527   // current ABI.
528   //
529   // The exception to the above rule are fields marked with the
530   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
531   // according to the Itanium ABI.  The exception applies only to records,
532   // not arrays of records, so we must also check whether we stripped off an
533   // array type above.
534   if (isa<CXXRecordDecl>(RT->getDecl()) &&
535       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
536     return false;
537 
538   return isEmptyRecord(Context, FT, AllowArrays);
539 }
540 
541 /// isEmptyRecord - Return true iff a structure contains only empty
542 /// fields. Note that a structure with a flexible array member is not
543 /// considered empty.
544 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
545   const RecordType *RT = T->getAs<RecordType>();
546   if (!RT)
547     return false;
548   const RecordDecl *RD = RT->getDecl();
549   if (RD->hasFlexibleArrayMember())
550     return false;
551 
552   // If this is a C++ record, check the bases first.
553   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
554     for (const auto &I : CXXRD->bases())
555       if (!isEmptyRecord(Context, I.getType(), true))
556         return false;
557 
558   for (const auto *I : RD->fields())
559     if (!isEmptyField(Context, I, AllowArrays))
560       return false;
561   return true;
562 }
563 
564 /// isSingleElementStruct - Determine if a structure is a "single
565 /// element struct", i.e. it has exactly one non-empty field or
566 /// exactly one field which is itself a single element
567 /// struct. Structures with flexible array members are never
568 /// considered single element structs.
569 ///
570 /// \return The field declaration for the single non-empty field, if
571 /// it exists.
572 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
573   const RecordType *RT = T->getAs<RecordType>();
574   if (!RT)
575     return nullptr;
576 
577   const RecordDecl *RD = RT->getDecl();
578   if (RD->hasFlexibleArrayMember())
579     return nullptr;
580 
581   const Type *Found = nullptr;
582 
583   // If this is a C++ record, check the bases first.
584   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
585     for (const auto &I : CXXRD->bases()) {
586       // Ignore empty records.
587       if (isEmptyRecord(Context, I.getType(), true))
588         continue;
589 
590       // If we already found an element then this isn't a single-element struct.
591       if (Found)
592         return nullptr;
593 
594       // If this is non-empty and not a single element struct, the composite
595       // cannot be a single element struct.
596       Found = isSingleElementStruct(I.getType(), Context);
597       if (!Found)
598         return nullptr;
599     }
600   }
601 
602   // Check for single element.
603   for (const auto *FD : RD->fields()) {
604     QualType FT = FD->getType();
605 
606     // Ignore empty fields.
607     if (isEmptyField(Context, FD, true))
608       continue;
609 
610     // If we already found an element then this isn't a single-element
611     // struct.
612     if (Found)
613       return nullptr;
614 
615     // Treat single element arrays as the element.
616     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
617       if (AT->getSize().getZExtValue() != 1)
618         break;
619       FT = AT->getElementType();
620     }
621 
622     if (!isAggregateTypeForABI(FT)) {
623       Found = FT.getTypePtr();
624     } else {
625       Found = isSingleElementStruct(FT, Context);
626       if (!Found)
627         return nullptr;
628     }
629   }
630 
631   // We don't consider a struct a single-element struct if it has
632   // padding beyond the element type.
633   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
634     return nullptr;
635 
636   return Found;
637 }
638 
639 namespace {
640 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
641                        const ABIArgInfo &AI) {
642   // This default implementation defers to the llvm backend's va_arg
643   // instruction. It can handle only passing arguments directly
644   // (typically only handled in the backend for primitive types), or
645   // aggregates passed indirectly by pointer (NOTE: if the "byval"
646   // flag has ABI impact in the callee, this implementation cannot
647   // work.)
648 
649   // Only a few cases are covered here at the moment -- those needed
650   // by the default abi.
651   llvm::Value *Val;
652 
653   if (AI.isIndirect()) {
654     assert(!AI.getPaddingType() &&
655            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
656     assert(
657         !AI.getIndirectRealign() &&
658         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
659 
660     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
661     CharUnits TyAlignForABI = TyInfo.Align;
662 
663     llvm::Type *BaseTy =
664         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
665     llvm::Value *Addr =
666         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
667     return Address(Addr, TyAlignForABI);
668   } else {
669     assert((AI.isDirect() || AI.isExtend()) &&
670            "Unexpected ArgInfo Kind in generic VAArg emitter!");
671 
672     assert(!AI.getInReg() &&
673            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
674     assert(!AI.getPaddingType() &&
675            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
676     assert(!AI.getDirectOffset() &&
677            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
678     assert(!AI.getCoerceToType() &&
679            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
680 
681     Address Temp = CGF.CreateMemTemp(Ty, "varet");
682     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
683     CGF.Builder.CreateStore(Val, Temp);
684     return Temp;
685   }
686 }
687 
688 /// DefaultABIInfo - The default implementation for ABI specific
689 /// details. This implementation provides information which results in
690 /// self-consistent and sensible LLVM IR generation, but does not
691 /// conform to any particular ABI.
692 class DefaultABIInfo : public ABIInfo {
693 public:
694   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
695 
696   ABIArgInfo classifyReturnType(QualType RetTy) const;
697   ABIArgInfo classifyArgumentType(QualType RetTy) const;
698 
699   void computeInfo(CGFunctionInfo &FI) const override {
700     if (!getCXXABI().classifyReturnType(FI))
701       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
702     for (auto &I : FI.arguments())
703       I.info = classifyArgumentType(I.type);
704   }
705 
706   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
707                     QualType Ty) const override {
708     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
709   }
710 };
711 
712 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
713 public:
714   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
715       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
716 };
717 
718 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
719   Ty = useFirstFieldIfTransparentUnion(Ty);
720 
721   if (isAggregateTypeForABI(Ty)) {
722     // Records with non-trivial destructors/copy-constructors should not be
723     // passed by value.
724     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
725       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
726 
727     return getNaturalAlignIndirect(Ty);
728   }
729 
730   // Treat an enum type as its underlying type.
731   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
732     Ty = EnumTy->getDecl()->getIntegerType();
733 
734   ASTContext &Context = getContext();
735   if (const auto *EIT = Ty->getAs<ExtIntType>())
736     if (EIT->getNumBits() >
737         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
738                                 ? Context.Int128Ty
739                                 : Context.LongLongTy))
740       return getNaturalAlignIndirect(Ty);
741 
742   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
743                                             : ABIArgInfo::getDirect());
744 }
745 
746 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
747   if (RetTy->isVoidType())
748     return ABIArgInfo::getIgnore();
749 
750   if (isAggregateTypeForABI(RetTy))
751     return getNaturalAlignIndirect(RetTy);
752 
753   // Treat an enum type as its underlying type.
754   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
755     RetTy = EnumTy->getDecl()->getIntegerType();
756 
757   if (const auto *EIT = RetTy->getAs<ExtIntType>())
758     if (EIT->getNumBits() >
759         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
760                                      ? getContext().Int128Ty
761                                      : getContext().LongLongTy))
762       return getNaturalAlignIndirect(RetTy);
763 
764   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
765                                                : ABIArgInfo::getDirect());
766 }
767 
768 //===----------------------------------------------------------------------===//
769 // WebAssembly ABI Implementation
770 //
771 // This is a very simple ABI that relies a lot on DefaultABIInfo.
772 //===----------------------------------------------------------------------===//
773 
774 class WebAssemblyABIInfo final : public SwiftABIInfo {
775 public:
776   enum ABIKind {
777     MVP = 0,
778     ExperimentalMV = 1,
779   };
780 
781 private:
782   DefaultABIInfo defaultInfo;
783   ABIKind Kind;
784 
785 public:
786   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
787       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
788 
789 private:
790   ABIArgInfo classifyReturnType(QualType RetTy) const;
791   ABIArgInfo classifyArgumentType(QualType Ty) const;
792 
793   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
794   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
795   // overload them.
796   void computeInfo(CGFunctionInfo &FI) const override {
797     if (!getCXXABI().classifyReturnType(FI))
798       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
799     for (auto &Arg : FI.arguments())
800       Arg.info = classifyArgumentType(Arg.type);
801   }
802 
803   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
804                     QualType Ty) const override;
805 
806   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
807                                     bool asReturnValue) const override {
808     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
809   }
810 
811   bool isSwiftErrorInRegister() const override {
812     return false;
813   }
814 };
815 
816 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
817 public:
818   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
819                                         WebAssemblyABIInfo::ABIKind K)
820       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
821 
822   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
823                            CodeGen::CodeGenModule &CGM) const override {
824     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
825     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
826       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
827         llvm::Function *Fn = cast<llvm::Function>(GV);
828         llvm::AttrBuilder B;
829         B.addAttribute("wasm-import-module", Attr->getImportModule());
830         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
831       }
832       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
833         llvm::Function *Fn = cast<llvm::Function>(GV);
834         llvm::AttrBuilder B;
835         B.addAttribute("wasm-import-name", Attr->getImportName());
836         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
837       }
838       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
839         llvm::Function *Fn = cast<llvm::Function>(GV);
840         llvm::AttrBuilder B;
841         B.addAttribute("wasm-export-name", Attr->getExportName());
842         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
843       }
844     }
845 
846     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
847       llvm::Function *Fn = cast<llvm::Function>(GV);
848       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
849         Fn->addFnAttr("no-prototype");
850     }
851   }
852 };
853 
854 /// Classify argument of given type \p Ty.
855 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
856   Ty = useFirstFieldIfTransparentUnion(Ty);
857 
858   if (isAggregateTypeForABI(Ty)) {
859     // Records with non-trivial destructors/copy-constructors should not be
860     // passed by value.
861     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
862       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
863     // Ignore empty structs/unions.
864     if (isEmptyRecord(getContext(), Ty, true))
865       return ABIArgInfo::getIgnore();
866     // Lower single-element structs to just pass a regular value. TODO: We
867     // could do reasonable-size multiple-element structs too, using getExpand(),
868     // though watch out for things like bitfields.
869     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
870       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
871     // For the experimental multivalue ABI, fully expand all other aggregates
872     if (Kind == ABIKind::ExperimentalMV) {
873       const RecordType *RT = Ty->getAs<RecordType>();
874       assert(RT);
875       bool HasBitField = false;
876       for (auto *Field : RT->getDecl()->fields()) {
877         if (Field->isBitField()) {
878           HasBitField = true;
879           break;
880         }
881       }
882       if (!HasBitField)
883         return ABIArgInfo::getExpand();
884     }
885   }
886 
887   // Otherwise just do the default thing.
888   return defaultInfo.classifyArgumentType(Ty);
889 }
890 
891 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
892   if (isAggregateTypeForABI(RetTy)) {
893     // Records with non-trivial destructors/copy-constructors should not be
894     // returned by value.
895     if (!getRecordArgABI(RetTy, getCXXABI())) {
896       // Ignore empty structs/unions.
897       if (isEmptyRecord(getContext(), RetTy, true))
898         return ABIArgInfo::getIgnore();
899       // Lower single-element structs to just return a regular value. TODO: We
900       // could do reasonable-size multiple-element structs too, using
901       // ABIArgInfo::getDirect().
902       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
903         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
904       // For the experimental multivalue ABI, return all other aggregates
905       if (Kind == ABIKind::ExperimentalMV)
906         return ABIArgInfo::getDirect();
907     }
908   }
909 
910   // Otherwise just do the default thing.
911   return defaultInfo.classifyReturnType(RetTy);
912 }
913 
914 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
915                                       QualType Ty) const {
916   bool IsIndirect = isAggregateTypeForABI(Ty) &&
917                     !isEmptyRecord(getContext(), Ty, true) &&
918                     !isSingleElementStruct(Ty, getContext());
919   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
920                           getContext().getTypeInfoInChars(Ty),
921                           CharUnits::fromQuantity(4),
922                           /*AllowHigherAlign=*/true);
923 }
924 
925 //===----------------------------------------------------------------------===//
926 // le32/PNaCl bitcode ABI Implementation
927 //
928 // This is a simplified version of the x86_32 ABI.  Arguments and return values
929 // are always passed on the stack.
930 //===----------------------------------------------------------------------===//
931 
932 class PNaClABIInfo : public ABIInfo {
933  public:
934   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
935 
936   ABIArgInfo classifyReturnType(QualType RetTy) const;
937   ABIArgInfo classifyArgumentType(QualType RetTy) const;
938 
939   void computeInfo(CGFunctionInfo &FI) const override;
940   Address EmitVAArg(CodeGenFunction &CGF,
941                     Address VAListAddr, QualType Ty) const override;
942 };
943 
944 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
945  public:
946    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
947        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
948 };
949 
950 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
951   if (!getCXXABI().classifyReturnType(FI))
952     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
953 
954   for (auto &I : FI.arguments())
955     I.info = classifyArgumentType(I.type);
956 }
957 
958 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
959                                 QualType Ty) const {
960   // The PNaCL ABI is a bit odd, in that varargs don't use normal
961   // function classification. Structs get passed directly for varargs
962   // functions, through a rewriting transform in
963   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
964   // this target to actually support a va_arg instructions with an
965   // aggregate type, unlike other targets.
966   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
967 }
968 
969 /// Classify argument of given type \p Ty.
970 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
971   if (isAggregateTypeForABI(Ty)) {
972     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
973       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
974     return getNaturalAlignIndirect(Ty);
975   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
976     // Treat an enum type as its underlying type.
977     Ty = EnumTy->getDecl()->getIntegerType();
978   } else if (Ty->isFloatingType()) {
979     // Floating-point types don't go inreg.
980     return ABIArgInfo::getDirect();
981   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
982     // Treat extended integers as integers if <=64, otherwise pass indirectly.
983     if (EIT->getNumBits() > 64)
984       return getNaturalAlignIndirect(Ty);
985     return ABIArgInfo::getDirect();
986   }
987 
988   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
989                                             : ABIArgInfo::getDirect());
990 }
991 
992 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
993   if (RetTy->isVoidType())
994     return ABIArgInfo::getIgnore();
995 
996   // In the PNaCl ABI we always return records/structures on the stack.
997   if (isAggregateTypeForABI(RetTy))
998     return getNaturalAlignIndirect(RetTy);
999 
1000   // Treat extended integers as integers if <=64, otherwise pass indirectly.
1001   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
1002     if (EIT->getNumBits() > 64)
1003       return getNaturalAlignIndirect(RetTy);
1004     return ABIArgInfo::getDirect();
1005   }
1006 
1007   // Treat an enum type as its underlying type.
1008   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1009     RetTy = EnumTy->getDecl()->getIntegerType();
1010 
1011   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1012                                                : ABIArgInfo::getDirect());
1013 }
1014 
1015 /// IsX86_MMXType - Return true if this is an MMX type.
1016 bool IsX86_MMXType(llvm::Type *IRType) {
1017   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1018   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1019     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1020     IRType->getScalarSizeInBits() != 64;
1021 }
1022 
1023 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1024                                           StringRef Constraint,
1025                                           llvm::Type* Ty) {
1026   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1027                      .Cases("y", "&y", "^Ym", true)
1028                      .Default(false);
1029   if (IsMMXCons && Ty->isVectorTy()) {
1030     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1031         64) {
1032       // Invalid MMX constraint
1033       return nullptr;
1034     }
1035 
1036     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1037   }
1038 
1039   // No operation needed
1040   return Ty;
1041 }
1042 
1043 /// Returns true if this type can be passed in SSE registers with the
1044 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1045 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1046   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1047     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1048       if (BT->getKind() == BuiltinType::LongDouble) {
1049         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1050             &llvm::APFloat::x87DoubleExtended())
1051           return false;
1052       }
1053       return true;
1054     }
1055   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1056     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1057     // registers specially.
1058     unsigned VecSize = Context.getTypeSize(VT);
1059     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1060       return true;
1061   }
1062   return false;
1063 }
1064 
1065 /// Returns true if this aggregate is small enough to be passed in SSE registers
1066 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1067 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1068   return NumMembers <= 4;
1069 }
1070 
1071 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1072 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1073   auto AI = ABIArgInfo::getDirect(T);
1074   AI.setInReg(true);
1075   AI.setCanBeFlattened(false);
1076   return AI;
1077 }
1078 
1079 //===----------------------------------------------------------------------===//
1080 // X86-32 ABI Implementation
1081 //===----------------------------------------------------------------------===//
1082 
1083 /// Similar to llvm::CCState, but for Clang.
1084 struct CCState {
1085   CCState(CGFunctionInfo &FI)
1086       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1087 
1088   llvm::SmallBitVector IsPreassigned;
1089   unsigned CC = CallingConv::CC_C;
1090   unsigned FreeRegs = 0;
1091   unsigned FreeSSERegs = 0;
1092 };
1093 
1094 /// X86_32ABIInfo - The X86-32 ABI information.
1095 class X86_32ABIInfo : public SwiftABIInfo {
1096   enum Class {
1097     Integer,
1098     Float
1099   };
1100 
1101   static const unsigned MinABIStackAlignInBytes = 4;
1102 
1103   bool IsDarwinVectorABI;
1104   bool IsRetSmallStructInRegABI;
1105   bool IsWin32StructABI;
1106   bool IsSoftFloatABI;
1107   bool IsMCUABI;
1108   unsigned DefaultNumRegisterParameters;
1109 
1110   static bool isRegisterSize(unsigned Size) {
1111     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1112   }
1113 
1114   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1115     // FIXME: Assumes vectorcall is in use.
1116     return isX86VectorTypeForVectorCall(getContext(), Ty);
1117   }
1118 
1119   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1120                                          uint64_t NumMembers) const override {
1121     // FIXME: Assumes vectorcall is in use.
1122     return isX86VectorCallAggregateSmallEnough(NumMembers);
1123   }
1124 
1125   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1126 
1127   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1128   /// such that the argument will be passed in memory.
1129   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1130 
1131   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1132 
1133   /// Return the alignment to use for the given type on the stack.
1134   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1135 
1136   Class classify(QualType Ty) const;
1137   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1138   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1139 
1140   /// Updates the number of available free registers, returns
1141   /// true if any registers were allocated.
1142   bool updateFreeRegs(QualType Ty, CCState &State) const;
1143 
1144   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1145                                 bool &NeedsPadding) const;
1146   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1147 
1148   bool canExpandIndirectArgument(QualType Ty) const;
1149 
1150   /// Rewrite the function info so that all memory arguments use
1151   /// inalloca.
1152   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1153 
1154   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1155                            CharUnits &StackOffset, ABIArgInfo &Info,
1156                            QualType Type) const;
1157   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1158 
1159 public:
1160 
1161   void computeInfo(CGFunctionInfo &FI) const override;
1162   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1163                     QualType Ty) const override;
1164 
1165   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1166                 bool RetSmallStructInRegABI, bool Win32StructABI,
1167                 unsigned NumRegisterParameters, bool SoftFloatABI)
1168     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1169       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1170       IsWin32StructABI(Win32StructABI),
1171       IsSoftFloatABI(SoftFloatABI),
1172       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1173       DefaultNumRegisterParameters(NumRegisterParameters) {}
1174 
1175   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1176                                     bool asReturnValue) const override {
1177     // LLVM's x86-32 lowering currently only assigns up to three
1178     // integer registers and three fp registers.  Oddly, it'll use up to
1179     // four vector registers for vectors, but those can overlap with the
1180     // scalar registers.
1181     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1182   }
1183 
1184   bool isSwiftErrorInRegister() const override {
1185     // x86-32 lowering does not support passing swifterror in a register.
1186     return false;
1187   }
1188 };
1189 
1190 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1191 public:
1192   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1193                           bool RetSmallStructInRegABI, bool Win32StructABI,
1194                           unsigned NumRegisterParameters, bool SoftFloatABI)
1195       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1196             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1197             NumRegisterParameters, SoftFloatABI)) {}
1198 
1199   static bool isStructReturnInRegABI(
1200       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1201 
1202   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1203                            CodeGen::CodeGenModule &CGM) const override;
1204 
1205   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1206     // Darwin uses different dwarf register numbers for EH.
1207     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1208     return 4;
1209   }
1210 
1211   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1212                                llvm::Value *Address) const override;
1213 
1214   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1215                                   StringRef Constraint,
1216                                   llvm::Type* Ty) const override {
1217     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1218   }
1219 
1220   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1221                                 std::string &Constraints,
1222                                 std::vector<llvm::Type *> &ResultRegTypes,
1223                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1224                                 std::vector<LValue> &ResultRegDests,
1225                                 std::string &AsmString,
1226                                 unsigned NumOutputs) const override;
1227 
1228   llvm::Constant *
1229   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1230     unsigned Sig = (0xeb << 0) |  // jmp rel8
1231                    (0x06 << 8) |  //           .+0x08
1232                    ('v' << 16) |
1233                    ('2' << 24);
1234     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1235   }
1236 
1237   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1238     return "movl\t%ebp, %ebp"
1239            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1240   }
1241 };
1242 
1243 }
1244 
1245 /// Rewrite input constraint references after adding some output constraints.
1246 /// In the case where there is one output and one input and we add one output,
1247 /// we need to replace all operand references greater than or equal to 1:
1248 ///     mov $0, $1
1249 ///     mov eax, $1
1250 /// The result will be:
1251 ///     mov $0, $2
1252 ///     mov eax, $2
1253 static void rewriteInputConstraintReferences(unsigned FirstIn,
1254                                              unsigned NumNewOuts,
1255                                              std::string &AsmString) {
1256   std::string Buf;
1257   llvm::raw_string_ostream OS(Buf);
1258   size_t Pos = 0;
1259   while (Pos < AsmString.size()) {
1260     size_t DollarStart = AsmString.find('$', Pos);
1261     if (DollarStart == std::string::npos)
1262       DollarStart = AsmString.size();
1263     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1264     if (DollarEnd == std::string::npos)
1265       DollarEnd = AsmString.size();
1266     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1267     Pos = DollarEnd;
1268     size_t NumDollars = DollarEnd - DollarStart;
1269     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1270       // We have an operand reference.
1271       size_t DigitStart = Pos;
1272       if (AsmString[DigitStart] == '{') {
1273         OS << '{';
1274         ++DigitStart;
1275       }
1276       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1277       if (DigitEnd == std::string::npos)
1278         DigitEnd = AsmString.size();
1279       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1280       unsigned OperandIndex;
1281       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1282         if (OperandIndex >= FirstIn)
1283           OperandIndex += NumNewOuts;
1284         OS << OperandIndex;
1285       } else {
1286         OS << OperandStr;
1287       }
1288       Pos = DigitEnd;
1289     }
1290   }
1291   AsmString = std::move(OS.str());
1292 }
1293 
1294 /// Add output constraints for EAX:EDX because they are return registers.
1295 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1296     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1297     std::vector<llvm::Type *> &ResultRegTypes,
1298     std::vector<llvm::Type *> &ResultTruncRegTypes,
1299     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1300     unsigned NumOutputs) const {
1301   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1302 
1303   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1304   // larger.
1305   if (!Constraints.empty())
1306     Constraints += ',';
1307   if (RetWidth <= 32) {
1308     Constraints += "={eax}";
1309     ResultRegTypes.push_back(CGF.Int32Ty);
1310   } else {
1311     // Use the 'A' constraint for EAX:EDX.
1312     Constraints += "=A";
1313     ResultRegTypes.push_back(CGF.Int64Ty);
1314   }
1315 
1316   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1317   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1318   ResultTruncRegTypes.push_back(CoerceTy);
1319 
1320   // Coerce the integer by bitcasting the return slot pointer.
1321   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1322                                                   CoerceTy->getPointerTo()));
1323   ResultRegDests.push_back(ReturnSlot);
1324 
1325   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1326 }
1327 
1328 /// shouldReturnTypeInRegister - Determine if the given type should be
1329 /// returned in a register (for the Darwin and MCU ABI).
1330 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1331                                                ASTContext &Context) const {
1332   uint64_t Size = Context.getTypeSize(Ty);
1333 
1334   // For i386, type must be register sized.
1335   // For the MCU ABI, it only needs to be <= 8-byte
1336   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1337    return false;
1338 
1339   if (Ty->isVectorType()) {
1340     // 64- and 128- bit vectors inside structures are not returned in
1341     // registers.
1342     if (Size == 64 || Size == 128)
1343       return false;
1344 
1345     return true;
1346   }
1347 
1348   // If this is a builtin, pointer, enum, complex type, member pointer, or
1349   // member function pointer it is ok.
1350   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1351       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1352       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1353     return true;
1354 
1355   // Arrays are treated like records.
1356   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1357     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1358 
1359   // Otherwise, it must be a record type.
1360   const RecordType *RT = Ty->getAs<RecordType>();
1361   if (!RT) return false;
1362 
1363   // FIXME: Traverse bases here too.
1364 
1365   // Structure types are passed in register if all fields would be
1366   // passed in a register.
1367   for (const auto *FD : RT->getDecl()->fields()) {
1368     // Empty fields are ignored.
1369     if (isEmptyField(Context, FD, true))
1370       continue;
1371 
1372     // Check fields recursively.
1373     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1374       return false;
1375   }
1376   return true;
1377 }
1378 
1379 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1380   // Treat complex types as the element type.
1381   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1382     Ty = CTy->getElementType();
1383 
1384   // Check for a type which we know has a simple scalar argument-passing
1385   // convention without any padding.  (We're specifically looking for 32
1386   // and 64-bit integer and integer-equivalents, float, and double.)
1387   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1388       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1389     return false;
1390 
1391   uint64_t Size = Context.getTypeSize(Ty);
1392   return Size == 32 || Size == 64;
1393 }
1394 
1395 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1396                           uint64_t &Size) {
1397   for (const auto *FD : RD->fields()) {
1398     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1399     // argument is smaller than 32-bits, expanding the struct will create
1400     // alignment padding.
1401     if (!is32Or64BitBasicType(FD->getType(), Context))
1402       return false;
1403 
1404     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1405     // how to expand them yet, and the predicate for telling if a bitfield still
1406     // counts as "basic" is more complicated than what we were doing previously.
1407     if (FD->isBitField())
1408       return false;
1409 
1410     Size += Context.getTypeSize(FD->getType());
1411   }
1412   return true;
1413 }
1414 
1415 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1416                                  uint64_t &Size) {
1417   // Don't do this if there are any non-empty bases.
1418   for (const CXXBaseSpecifier &Base : RD->bases()) {
1419     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1420                               Size))
1421       return false;
1422   }
1423   if (!addFieldSizes(Context, RD, Size))
1424     return false;
1425   return true;
1426 }
1427 
1428 /// Test whether an argument type which is to be passed indirectly (on the
1429 /// stack) would have the equivalent layout if it was expanded into separate
1430 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1431 /// optimizations.
1432 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1433   // We can only expand structure types.
1434   const RecordType *RT = Ty->getAs<RecordType>();
1435   if (!RT)
1436     return false;
1437   const RecordDecl *RD = RT->getDecl();
1438   uint64_t Size = 0;
1439   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1440     if (!IsWin32StructABI) {
1441       // On non-Windows, we have to conservatively match our old bitcode
1442       // prototypes in order to be ABI-compatible at the bitcode level.
1443       if (!CXXRD->isCLike())
1444         return false;
1445     } else {
1446       // Don't do this for dynamic classes.
1447       if (CXXRD->isDynamicClass())
1448         return false;
1449     }
1450     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1451       return false;
1452   } else {
1453     if (!addFieldSizes(getContext(), RD, Size))
1454       return false;
1455   }
1456 
1457   // We can do this if there was no alignment padding.
1458   return Size == getContext().getTypeSize(Ty);
1459 }
1460 
1461 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1462   // If the return value is indirect, then the hidden argument is consuming one
1463   // integer register.
1464   if (State.FreeRegs) {
1465     --State.FreeRegs;
1466     if (!IsMCUABI)
1467       return getNaturalAlignIndirectInReg(RetTy);
1468   }
1469   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1470 }
1471 
1472 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1473                                              CCState &State) const {
1474   if (RetTy->isVoidType())
1475     return ABIArgInfo::getIgnore();
1476 
1477   const Type *Base = nullptr;
1478   uint64_t NumElts = 0;
1479   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1480        State.CC == llvm::CallingConv::X86_RegCall) &&
1481       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1482     // The LLVM struct type for such an aggregate should lower properly.
1483     return ABIArgInfo::getDirect();
1484   }
1485 
1486   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1487     // On Darwin, some vectors are returned in registers.
1488     if (IsDarwinVectorABI) {
1489       uint64_t Size = getContext().getTypeSize(RetTy);
1490 
1491       // 128-bit vectors are a special case; they are returned in
1492       // registers and we need to make sure to pick a type the LLVM
1493       // backend will like.
1494       if (Size == 128)
1495         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1496             llvm::Type::getInt64Ty(getVMContext()), 2));
1497 
1498       // Always return in register if it fits in a general purpose
1499       // register, or if it is 64 bits and has a single element.
1500       if ((Size == 8 || Size == 16 || Size == 32) ||
1501           (Size == 64 && VT->getNumElements() == 1))
1502         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1503                                                             Size));
1504 
1505       return getIndirectReturnResult(RetTy, State);
1506     }
1507 
1508     return ABIArgInfo::getDirect();
1509   }
1510 
1511   if (isAggregateTypeForABI(RetTy)) {
1512     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1513       // Structures with flexible arrays are always indirect.
1514       if (RT->getDecl()->hasFlexibleArrayMember())
1515         return getIndirectReturnResult(RetTy, State);
1516     }
1517 
1518     // If specified, structs and unions are always indirect.
1519     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1520       return getIndirectReturnResult(RetTy, State);
1521 
1522     // Ignore empty structs/unions.
1523     if (isEmptyRecord(getContext(), RetTy, true))
1524       return ABIArgInfo::getIgnore();
1525 
1526     // Small structures which are register sized are generally returned
1527     // in a register.
1528     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1529       uint64_t Size = getContext().getTypeSize(RetTy);
1530 
1531       // As a special-case, if the struct is a "single-element" struct, and
1532       // the field is of type "float" or "double", return it in a
1533       // floating-point register. (MSVC does not apply this special case.)
1534       // We apply a similar transformation for pointer types to improve the
1535       // quality of the generated IR.
1536       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1537         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1538             || SeltTy->hasPointerRepresentation())
1539           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1540 
1541       // FIXME: We should be able to narrow this integer in cases with dead
1542       // padding.
1543       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1544     }
1545 
1546     return getIndirectReturnResult(RetTy, State);
1547   }
1548 
1549   // Treat an enum type as its underlying type.
1550   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1551     RetTy = EnumTy->getDecl()->getIntegerType();
1552 
1553   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1554     if (EIT->getNumBits() > 64)
1555       return getIndirectReturnResult(RetTy, State);
1556 
1557   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1558                                                : ABIArgInfo::getDirect());
1559 }
1560 
1561 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1562   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1563 }
1564 
1565 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1566   const RecordType *RT = Ty->getAs<RecordType>();
1567   if (!RT)
1568     return 0;
1569   const RecordDecl *RD = RT->getDecl();
1570 
1571   // If this is a C++ record, check the bases first.
1572   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1573     for (const auto &I : CXXRD->bases())
1574       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1575         return false;
1576 
1577   for (const auto *i : RD->fields()) {
1578     QualType FT = i->getType();
1579 
1580     if (isSIMDVectorType(Context, FT))
1581       return true;
1582 
1583     if (isRecordWithSIMDVectorType(Context, FT))
1584       return true;
1585   }
1586 
1587   return false;
1588 }
1589 
1590 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1591                                                  unsigned Align) const {
1592   // Otherwise, if the alignment is less than or equal to the minimum ABI
1593   // alignment, just use the default; the backend will handle this.
1594   if (Align <= MinABIStackAlignInBytes)
1595     return 0; // Use default alignment.
1596 
1597   // On non-Darwin, the stack type alignment is always 4.
1598   if (!IsDarwinVectorABI) {
1599     // Set explicit alignment, since we may need to realign the top.
1600     return MinABIStackAlignInBytes;
1601   }
1602 
1603   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1604   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1605                       isRecordWithSIMDVectorType(getContext(), Ty)))
1606     return 16;
1607 
1608   return MinABIStackAlignInBytes;
1609 }
1610 
1611 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1612                                             CCState &State) const {
1613   if (!ByVal) {
1614     if (State.FreeRegs) {
1615       --State.FreeRegs; // Non-byval indirects just use one pointer.
1616       if (!IsMCUABI)
1617         return getNaturalAlignIndirectInReg(Ty);
1618     }
1619     return getNaturalAlignIndirect(Ty, false);
1620   }
1621 
1622   // Compute the byval alignment.
1623   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1624   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1625   if (StackAlign == 0)
1626     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1627 
1628   // If the stack alignment is less than the type alignment, realign the
1629   // argument.
1630   bool Realign = TypeAlign > StackAlign;
1631   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1632                                  /*ByVal=*/true, Realign);
1633 }
1634 
1635 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1636   const Type *T = isSingleElementStruct(Ty, getContext());
1637   if (!T)
1638     T = Ty.getTypePtr();
1639 
1640   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1641     BuiltinType::Kind K = BT->getKind();
1642     if (K == BuiltinType::Float || K == BuiltinType::Double)
1643       return Float;
1644   }
1645   return Integer;
1646 }
1647 
1648 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1649   if (!IsSoftFloatABI) {
1650     Class C = classify(Ty);
1651     if (C == Float)
1652       return false;
1653   }
1654 
1655   unsigned Size = getContext().getTypeSize(Ty);
1656   unsigned SizeInRegs = (Size + 31) / 32;
1657 
1658   if (SizeInRegs == 0)
1659     return false;
1660 
1661   if (!IsMCUABI) {
1662     if (SizeInRegs > State.FreeRegs) {
1663       State.FreeRegs = 0;
1664       return false;
1665     }
1666   } else {
1667     // The MCU psABI allows passing parameters in-reg even if there are
1668     // earlier parameters that are passed on the stack. Also,
1669     // it does not allow passing >8-byte structs in-register,
1670     // even if there are 3 free registers available.
1671     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1672       return false;
1673   }
1674 
1675   State.FreeRegs -= SizeInRegs;
1676   return true;
1677 }
1678 
1679 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1680                                              bool &InReg,
1681                                              bool &NeedsPadding) const {
1682   // On Windows, aggregates other than HFAs are never passed in registers, and
1683   // they do not consume register slots. Homogenous floating-point aggregates
1684   // (HFAs) have already been dealt with at this point.
1685   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1686     return false;
1687 
1688   NeedsPadding = false;
1689   InReg = !IsMCUABI;
1690 
1691   if (!updateFreeRegs(Ty, State))
1692     return false;
1693 
1694   if (IsMCUABI)
1695     return true;
1696 
1697   if (State.CC == llvm::CallingConv::X86_FastCall ||
1698       State.CC == llvm::CallingConv::X86_VectorCall ||
1699       State.CC == llvm::CallingConv::X86_RegCall) {
1700     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1701       NeedsPadding = true;
1702 
1703     return false;
1704   }
1705 
1706   return true;
1707 }
1708 
1709 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1710   if (!updateFreeRegs(Ty, State))
1711     return false;
1712 
1713   if (IsMCUABI)
1714     return false;
1715 
1716   if (State.CC == llvm::CallingConv::X86_FastCall ||
1717       State.CC == llvm::CallingConv::X86_VectorCall ||
1718       State.CC == llvm::CallingConv::X86_RegCall) {
1719     if (getContext().getTypeSize(Ty) > 32)
1720       return false;
1721 
1722     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1723         Ty->isReferenceType());
1724   }
1725 
1726   return true;
1727 }
1728 
1729 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1730   // Vectorcall x86 works subtly different than in x64, so the format is
1731   // a bit different than the x64 version.  First, all vector types (not HVAs)
1732   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1733   // This differs from the x64 implementation, where the first 6 by INDEX get
1734   // registers.
1735   // In the second pass over the arguments, HVAs are passed in the remaining
1736   // vector registers if possible, or indirectly by address. The address will be
1737   // passed in ECX/EDX if available. Any other arguments are passed according to
1738   // the usual fastcall rules.
1739   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1740   for (int I = 0, E = Args.size(); I < E; ++I) {
1741     const Type *Base = nullptr;
1742     uint64_t NumElts = 0;
1743     const QualType &Ty = Args[I].type;
1744     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1745         isHomogeneousAggregate(Ty, Base, NumElts)) {
1746       if (State.FreeSSERegs >= NumElts) {
1747         State.FreeSSERegs -= NumElts;
1748         Args[I].info = ABIArgInfo::getDirectInReg();
1749         State.IsPreassigned.set(I);
1750       }
1751     }
1752   }
1753 }
1754 
1755 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1756                                                CCState &State) const {
1757   // FIXME: Set alignment on indirect arguments.
1758   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1759   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1760   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1761 
1762   Ty = useFirstFieldIfTransparentUnion(Ty);
1763   TypeInfo TI = getContext().getTypeInfo(Ty);
1764 
1765   // Check with the C++ ABI first.
1766   const RecordType *RT = Ty->getAs<RecordType>();
1767   if (RT) {
1768     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1769     if (RAA == CGCXXABI::RAA_Indirect) {
1770       return getIndirectResult(Ty, false, State);
1771     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1772       // The field index doesn't matter, we'll fix it up later.
1773       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1774     }
1775   }
1776 
1777   // Regcall uses the concept of a homogenous vector aggregate, similar
1778   // to other targets.
1779   const Type *Base = nullptr;
1780   uint64_t NumElts = 0;
1781   if ((IsRegCall || IsVectorCall) &&
1782       isHomogeneousAggregate(Ty, Base, NumElts)) {
1783     if (State.FreeSSERegs >= NumElts) {
1784       State.FreeSSERegs -= NumElts;
1785 
1786       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1787       // does.
1788       if (IsVectorCall)
1789         return getDirectX86Hva();
1790 
1791       if (Ty->isBuiltinType() || Ty->isVectorType())
1792         return ABIArgInfo::getDirect();
1793       return ABIArgInfo::getExpand();
1794     }
1795     return getIndirectResult(Ty, /*ByVal=*/false, State);
1796   }
1797 
1798   if (isAggregateTypeForABI(Ty)) {
1799     // Structures with flexible arrays are always indirect.
1800     // FIXME: This should not be byval!
1801     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1802       return getIndirectResult(Ty, true, State);
1803 
1804     // Ignore empty structs/unions on non-Windows.
1805     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1806       return ABIArgInfo::getIgnore();
1807 
1808     llvm::LLVMContext &LLVMContext = getVMContext();
1809     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1810     bool NeedsPadding = false;
1811     bool InReg;
1812     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1813       unsigned SizeInRegs = (TI.Width + 31) / 32;
1814       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1815       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1816       if (InReg)
1817         return ABIArgInfo::getDirectInReg(Result);
1818       else
1819         return ABIArgInfo::getDirect(Result);
1820     }
1821     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1822 
1823     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1824     // added in MSVC 2015.
1825     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1826       return getIndirectResult(Ty, /*ByVal=*/false, State);
1827 
1828     // Expand small (<= 128-bit) record types when we know that the stack layout
1829     // of those arguments will match the struct. This is important because the
1830     // LLVM backend isn't smart enough to remove byval, which inhibits many
1831     // optimizations.
1832     // Don't do this for the MCU if there are still free integer registers
1833     // (see X86_64 ABI for full explanation).
1834     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1835         canExpandIndirectArgument(Ty))
1836       return ABIArgInfo::getExpandWithPadding(
1837           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1838 
1839     return getIndirectResult(Ty, true, State);
1840   }
1841 
1842   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1843     // On Windows, vectors are passed directly if registers are available, or
1844     // indirectly if not. This avoids the need to align argument memory. Pass
1845     // user-defined vector types larger than 512 bits indirectly for simplicity.
1846     if (IsWin32StructABI) {
1847       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1848         --State.FreeSSERegs;
1849         return ABIArgInfo::getDirectInReg();
1850       }
1851       return getIndirectResult(Ty, /*ByVal=*/false, State);
1852     }
1853 
1854     // On Darwin, some vectors are passed in memory, we handle this by passing
1855     // it as an i8/i16/i32/i64.
1856     if (IsDarwinVectorABI) {
1857       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1858           (TI.Width == 64 && VT->getNumElements() == 1))
1859         return ABIArgInfo::getDirect(
1860             llvm::IntegerType::get(getVMContext(), TI.Width));
1861     }
1862 
1863     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1864       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1865 
1866     return ABIArgInfo::getDirect();
1867   }
1868 
1869 
1870   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1871     Ty = EnumTy->getDecl()->getIntegerType();
1872 
1873   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1874 
1875   if (isPromotableIntegerTypeForABI(Ty)) {
1876     if (InReg)
1877       return ABIArgInfo::getExtendInReg(Ty);
1878     return ABIArgInfo::getExtend(Ty);
1879   }
1880 
1881   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1882     if (EIT->getNumBits() <= 64) {
1883       if (InReg)
1884         return ABIArgInfo::getDirectInReg();
1885       return ABIArgInfo::getDirect();
1886     }
1887     return getIndirectResult(Ty, /*ByVal=*/false, State);
1888   }
1889 
1890   if (InReg)
1891     return ABIArgInfo::getDirectInReg();
1892   return ABIArgInfo::getDirect();
1893 }
1894 
1895 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1896   CCState State(FI);
1897   if (IsMCUABI)
1898     State.FreeRegs = 3;
1899   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1900     State.FreeRegs = 2;
1901     State.FreeSSERegs = 3;
1902   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1903     State.FreeRegs = 2;
1904     State.FreeSSERegs = 6;
1905   } else if (FI.getHasRegParm())
1906     State.FreeRegs = FI.getRegParm();
1907   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1908     State.FreeRegs = 5;
1909     State.FreeSSERegs = 8;
1910   } else if (IsWin32StructABI) {
1911     // Since MSVC 2015, the first three SSE vectors have been passed in
1912     // registers. The rest are passed indirectly.
1913     State.FreeRegs = DefaultNumRegisterParameters;
1914     State.FreeSSERegs = 3;
1915   } else
1916     State.FreeRegs = DefaultNumRegisterParameters;
1917 
1918   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1919     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1920   } else if (FI.getReturnInfo().isIndirect()) {
1921     // The C++ ABI is not aware of register usage, so we have to check if the
1922     // return value was sret and put it in a register ourselves if appropriate.
1923     if (State.FreeRegs) {
1924       --State.FreeRegs;  // The sret parameter consumes a register.
1925       if (!IsMCUABI)
1926         FI.getReturnInfo().setInReg(true);
1927     }
1928   }
1929 
1930   // The chain argument effectively gives us another free register.
1931   if (FI.isChainCall())
1932     ++State.FreeRegs;
1933 
1934   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1935   // arguments to XMM registers as available.
1936   if (State.CC == llvm::CallingConv::X86_VectorCall)
1937     runVectorCallFirstPass(FI, State);
1938 
1939   bool UsedInAlloca = false;
1940   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1941   for (int I = 0, E = Args.size(); I < E; ++I) {
1942     // Skip arguments that have already been assigned.
1943     if (State.IsPreassigned.test(I))
1944       continue;
1945 
1946     Args[I].info = classifyArgumentType(Args[I].type, State);
1947     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1948   }
1949 
1950   // If we needed to use inalloca for any argument, do a second pass and rewrite
1951   // all the memory arguments to use inalloca.
1952   if (UsedInAlloca)
1953     rewriteWithInAlloca(FI);
1954 }
1955 
1956 void
1957 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1958                                    CharUnits &StackOffset, ABIArgInfo &Info,
1959                                    QualType Type) const {
1960   // Arguments are always 4-byte-aligned.
1961   CharUnits WordSize = CharUnits::fromQuantity(4);
1962   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1963 
1964   // sret pointers and indirect things will require an extra pointer
1965   // indirection, unless they are byval. Most things are byval, and will not
1966   // require this indirection.
1967   bool IsIndirect = false;
1968   if (Info.isIndirect() && !Info.getIndirectByVal())
1969     IsIndirect = true;
1970   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1971   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1972   if (IsIndirect)
1973     LLTy = LLTy->getPointerTo(0);
1974   FrameFields.push_back(LLTy);
1975   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1976 
1977   // Insert padding bytes to respect alignment.
1978   CharUnits FieldEnd = StackOffset;
1979   StackOffset = FieldEnd.alignTo(WordSize);
1980   if (StackOffset != FieldEnd) {
1981     CharUnits NumBytes = StackOffset - FieldEnd;
1982     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1983     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1984     FrameFields.push_back(Ty);
1985   }
1986 }
1987 
1988 static bool isArgInAlloca(const ABIArgInfo &Info) {
1989   // Leave ignored and inreg arguments alone.
1990   switch (Info.getKind()) {
1991   case ABIArgInfo::InAlloca:
1992     return true;
1993   case ABIArgInfo::Ignore:
1994   case ABIArgInfo::IndirectAliased:
1995     return false;
1996   case ABIArgInfo::Indirect:
1997   case ABIArgInfo::Direct:
1998   case ABIArgInfo::Extend:
1999     return !Info.getInReg();
2000   case ABIArgInfo::Expand:
2001   case ABIArgInfo::CoerceAndExpand:
2002     // These are aggregate types which are never passed in registers when
2003     // inalloca is involved.
2004     return true;
2005   }
2006   llvm_unreachable("invalid enum");
2007 }
2008 
2009 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2010   assert(IsWin32StructABI && "inalloca only supported on win32");
2011 
2012   // Build a packed struct type for all of the arguments in memory.
2013   SmallVector<llvm::Type *, 6> FrameFields;
2014 
2015   // The stack alignment is always 4.
2016   CharUnits StackAlign = CharUnits::fromQuantity(4);
2017 
2018   CharUnits StackOffset;
2019   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2020 
2021   // Put 'this' into the struct before 'sret', if necessary.
2022   bool IsThisCall =
2023       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2024   ABIArgInfo &Ret = FI.getReturnInfo();
2025   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2026       isArgInAlloca(I->info)) {
2027     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2028     ++I;
2029   }
2030 
2031   // Put the sret parameter into the inalloca struct if it's in memory.
2032   if (Ret.isIndirect() && !Ret.getInReg()) {
2033     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2034     // On Windows, the hidden sret parameter is always returned in eax.
2035     Ret.setInAllocaSRet(IsWin32StructABI);
2036   }
2037 
2038   // Skip the 'this' parameter in ecx.
2039   if (IsThisCall)
2040     ++I;
2041 
2042   // Put arguments passed in memory into the struct.
2043   for (; I != E; ++I) {
2044     if (isArgInAlloca(I->info))
2045       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2046   }
2047 
2048   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2049                                         /*isPacked=*/true),
2050                   StackAlign);
2051 }
2052 
2053 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2054                                  Address VAListAddr, QualType Ty) const {
2055 
2056   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2057 
2058   // x86-32 changes the alignment of certain arguments on the stack.
2059   //
2060   // Just messing with TypeInfo like this works because we never pass
2061   // anything indirectly.
2062   TypeInfo.Align = CharUnits::fromQuantity(
2063                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2064 
2065   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2066                           TypeInfo, CharUnits::fromQuantity(4),
2067                           /*AllowHigherAlign*/ true);
2068 }
2069 
2070 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2071     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2072   assert(Triple.getArch() == llvm::Triple::x86);
2073 
2074   switch (Opts.getStructReturnConvention()) {
2075   case CodeGenOptions::SRCK_Default:
2076     break;
2077   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2078     return false;
2079   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2080     return true;
2081   }
2082 
2083   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2084     return true;
2085 
2086   switch (Triple.getOS()) {
2087   case llvm::Triple::DragonFly:
2088   case llvm::Triple::FreeBSD:
2089   case llvm::Triple::OpenBSD:
2090   case llvm::Triple::Win32:
2091     return true;
2092   default:
2093     return false;
2094   }
2095 }
2096 
2097 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2098                                  CodeGen::CodeGenModule &CGM) {
2099   if (!FD->hasAttr<AnyX86InterruptAttr>())
2100     return;
2101 
2102   llvm::Function *Fn = cast<llvm::Function>(GV);
2103   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2104   if (FD->getNumParams() == 0)
2105     return;
2106 
2107   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2108   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2109   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2110     Fn->getContext(), ByValTy);
2111   Fn->addParamAttr(0, NewAttr);
2112 }
2113 
2114 void X86_32TargetCodeGenInfo::setTargetAttributes(
2115     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2116   if (GV->isDeclaration())
2117     return;
2118   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2119     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2120       llvm::Function *Fn = cast<llvm::Function>(GV);
2121       Fn->addFnAttr("stackrealign");
2122     }
2123 
2124     addX86InterruptAttrs(FD, GV, CGM);
2125   }
2126 }
2127 
2128 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2129                                                CodeGen::CodeGenFunction &CGF,
2130                                                llvm::Value *Address) const {
2131   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2132 
2133   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2134 
2135   // 0-7 are the eight integer registers;  the order is different
2136   //   on Darwin (for EH), but the range is the same.
2137   // 8 is %eip.
2138   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2139 
2140   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2141     // 12-16 are st(0..4).  Not sure why we stop at 4.
2142     // These have size 16, which is sizeof(long double) on
2143     // platforms with 8-byte alignment for that type.
2144     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2145     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2146 
2147   } else {
2148     // 9 is %eflags, which doesn't get a size on Darwin for some
2149     // reason.
2150     Builder.CreateAlignedStore(
2151         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2152                                CharUnits::One());
2153 
2154     // 11-16 are st(0..5).  Not sure why we stop at 5.
2155     // These have size 12, which is sizeof(long double) on
2156     // platforms with 4-byte alignment for that type.
2157     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2158     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2159   }
2160 
2161   return false;
2162 }
2163 
2164 //===----------------------------------------------------------------------===//
2165 // X86-64 ABI Implementation
2166 //===----------------------------------------------------------------------===//
2167 
2168 
2169 namespace {
2170 /// The AVX ABI level for X86 targets.
2171 enum class X86AVXABILevel {
2172   None,
2173   AVX,
2174   AVX512
2175 };
2176 
2177 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2178 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2179   switch (AVXLevel) {
2180   case X86AVXABILevel::AVX512:
2181     return 512;
2182   case X86AVXABILevel::AVX:
2183     return 256;
2184   case X86AVXABILevel::None:
2185     return 128;
2186   }
2187   llvm_unreachable("Unknown AVXLevel");
2188 }
2189 
2190 /// X86_64ABIInfo - The X86_64 ABI information.
2191 class X86_64ABIInfo : public SwiftABIInfo {
2192   enum Class {
2193     Integer = 0,
2194     SSE,
2195     SSEUp,
2196     X87,
2197     X87Up,
2198     ComplexX87,
2199     NoClass,
2200     Memory
2201   };
2202 
2203   /// merge - Implement the X86_64 ABI merging algorithm.
2204   ///
2205   /// Merge an accumulating classification \arg Accum with a field
2206   /// classification \arg Field.
2207   ///
2208   /// \param Accum - The accumulating classification. This should
2209   /// always be either NoClass or the result of a previous merge
2210   /// call. In addition, this should never be Memory (the caller
2211   /// should just return Memory for the aggregate).
2212   static Class merge(Class Accum, Class Field);
2213 
2214   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2215   ///
2216   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2217   /// final MEMORY or SSE classes when necessary.
2218   ///
2219   /// \param AggregateSize - The size of the current aggregate in
2220   /// the classification process.
2221   ///
2222   /// \param Lo - The classification for the parts of the type
2223   /// residing in the low word of the containing object.
2224   ///
2225   /// \param Hi - The classification for the parts of the type
2226   /// residing in the higher words of the containing object.
2227   ///
2228   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2229 
2230   /// classify - Determine the x86_64 register classes in which the
2231   /// given type T should be passed.
2232   ///
2233   /// \param Lo - The classification for the parts of the type
2234   /// residing in the low word of the containing object.
2235   ///
2236   /// \param Hi - The classification for the parts of the type
2237   /// residing in the high word of the containing object.
2238   ///
2239   /// \param OffsetBase - The bit offset of this type in the
2240   /// containing object.  Some parameters are classified different
2241   /// depending on whether they straddle an eightbyte boundary.
2242   ///
2243   /// \param isNamedArg - Whether the argument in question is a "named"
2244   /// argument, as used in AMD64-ABI 3.5.7.
2245   ///
2246   /// If a word is unused its result will be NoClass; if a type should
2247   /// be passed in Memory then at least the classification of \arg Lo
2248   /// will be Memory.
2249   ///
2250   /// The \arg Lo class will be NoClass iff the argument is ignored.
2251   ///
2252   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2253   /// also be ComplexX87.
2254   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2255                 bool isNamedArg) const;
2256 
2257   llvm::Type *GetByteVectorType(QualType Ty) const;
2258   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2259                                  unsigned IROffset, QualType SourceTy,
2260                                  unsigned SourceOffset) const;
2261   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2262                                      unsigned IROffset, QualType SourceTy,
2263                                      unsigned SourceOffset) const;
2264 
2265   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2266   /// such that the argument will be returned in memory.
2267   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2268 
2269   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2270   /// such that the argument will be passed in memory.
2271   ///
2272   /// \param freeIntRegs - The number of free integer registers remaining
2273   /// available.
2274   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2275 
2276   ABIArgInfo classifyReturnType(QualType RetTy) const;
2277 
2278   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2279                                   unsigned &neededInt, unsigned &neededSSE,
2280                                   bool isNamedArg) const;
2281 
2282   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2283                                        unsigned &NeededSSE) const;
2284 
2285   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2286                                            unsigned &NeededSSE) const;
2287 
2288   bool IsIllegalVectorType(QualType Ty) const;
2289 
2290   /// The 0.98 ABI revision clarified a lot of ambiguities,
2291   /// unfortunately in ways that were not always consistent with
2292   /// certain previous compilers.  In particular, platforms which
2293   /// required strict binary compatibility with older versions of GCC
2294   /// may need to exempt themselves.
2295   bool honorsRevision0_98() const {
2296     return !getTarget().getTriple().isOSDarwin();
2297   }
2298 
2299   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2300   /// classify it as INTEGER (for compatibility with older clang compilers).
2301   bool classifyIntegerMMXAsSSE() const {
2302     // Clang <= 3.8 did not do this.
2303     if (getContext().getLangOpts().getClangABICompat() <=
2304         LangOptions::ClangABI::Ver3_8)
2305       return false;
2306 
2307     const llvm::Triple &Triple = getTarget().getTriple();
2308     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2309       return false;
2310     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2311       return false;
2312     return true;
2313   }
2314 
2315   // GCC classifies vectors of __int128 as memory.
2316   bool passInt128VectorsInMem() const {
2317     // Clang <= 9.0 did not do this.
2318     if (getContext().getLangOpts().getClangABICompat() <=
2319         LangOptions::ClangABI::Ver9)
2320       return false;
2321 
2322     const llvm::Triple &T = getTarget().getTriple();
2323     return T.isOSLinux() || T.isOSNetBSD();
2324   }
2325 
2326   X86AVXABILevel AVXLevel;
2327   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2328   // 64-bit hardware.
2329   bool Has64BitPointers;
2330 
2331 public:
2332   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2333       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2334       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2335   }
2336 
2337   bool isPassedUsingAVXType(QualType type) const {
2338     unsigned neededInt, neededSSE;
2339     // The freeIntRegs argument doesn't matter here.
2340     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2341                                            /*isNamedArg*/true);
2342     if (info.isDirect()) {
2343       llvm::Type *ty = info.getCoerceToType();
2344       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2345         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2346     }
2347     return false;
2348   }
2349 
2350   void computeInfo(CGFunctionInfo &FI) const override;
2351 
2352   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2353                     QualType Ty) const override;
2354   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2355                       QualType Ty) const override;
2356 
2357   bool has64BitPointers() const {
2358     return Has64BitPointers;
2359   }
2360 
2361   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2362                                     bool asReturnValue) const override {
2363     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2364   }
2365   bool isSwiftErrorInRegister() const override {
2366     return true;
2367   }
2368 };
2369 
2370 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2371 class WinX86_64ABIInfo : public SwiftABIInfo {
2372 public:
2373   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2374       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2375         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2376 
2377   void computeInfo(CGFunctionInfo &FI) const override;
2378 
2379   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2380                     QualType Ty) const override;
2381 
2382   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2383     // FIXME: Assumes vectorcall is in use.
2384     return isX86VectorTypeForVectorCall(getContext(), Ty);
2385   }
2386 
2387   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2388                                          uint64_t NumMembers) const override {
2389     // FIXME: Assumes vectorcall is in use.
2390     return isX86VectorCallAggregateSmallEnough(NumMembers);
2391   }
2392 
2393   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2394                                     bool asReturnValue) const override {
2395     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2396   }
2397 
2398   bool isSwiftErrorInRegister() const override {
2399     return true;
2400   }
2401 
2402 private:
2403   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2404                       bool IsVectorCall, bool IsRegCall) const;
2405   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2406                                            const ABIArgInfo &current) const;
2407 
2408   X86AVXABILevel AVXLevel;
2409 
2410   bool IsMingw64;
2411 };
2412 
2413 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2414 public:
2415   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2416       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2417 
2418   const X86_64ABIInfo &getABIInfo() const {
2419     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2420   }
2421 
2422   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2423   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2424   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2425 
2426   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2427     return 7;
2428   }
2429 
2430   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2431                                llvm::Value *Address) const override {
2432     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2433 
2434     // 0-15 are the 16 integer registers.
2435     // 16 is %rip.
2436     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2437     return false;
2438   }
2439 
2440   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2441                                   StringRef Constraint,
2442                                   llvm::Type* Ty) const override {
2443     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2444   }
2445 
2446   bool isNoProtoCallVariadic(const CallArgList &args,
2447                              const FunctionNoProtoType *fnType) const override {
2448     // The default CC on x86-64 sets %al to the number of SSA
2449     // registers used, and GCC sets this when calling an unprototyped
2450     // function, so we override the default behavior.  However, don't do
2451     // that when AVX types are involved: the ABI explicitly states it is
2452     // undefined, and it doesn't work in practice because of how the ABI
2453     // defines varargs anyway.
2454     if (fnType->getCallConv() == CC_C) {
2455       bool HasAVXType = false;
2456       for (CallArgList::const_iterator
2457              it = args.begin(), ie = args.end(); it != ie; ++it) {
2458         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2459           HasAVXType = true;
2460           break;
2461         }
2462       }
2463 
2464       if (!HasAVXType)
2465         return true;
2466     }
2467 
2468     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2469   }
2470 
2471   llvm::Constant *
2472   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2473     unsigned Sig = (0xeb << 0) | // jmp rel8
2474                    (0x06 << 8) | //           .+0x08
2475                    ('v' << 16) |
2476                    ('2' << 24);
2477     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2478   }
2479 
2480   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2481                            CodeGen::CodeGenModule &CGM) const override {
2482     if (GV->isDeclaration())
2483       return;
2484     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2485       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2486         llvm::Function *Fn = cast<llvm::Function>(GV);
2487         Fn->addFnAttr("stackrealign");
2488       }
2489 
2490       addX86InterruptAttrs(FD, GV, CGM);
2491     }
2492   }
2493 
2494   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2495                             const FunctionDecl *Caller,
2496                             const FunctionDecl *Callee,
2497                             const CallArgList &Args) const override;
2498 };
2499 
2500 static void initFeatureMaps(const ASTContext &Ctx,
2501                             llvm::StringMap<bool> &CallerMap,
2502                             const FunctionDecl *Caller,
2503                             llvm::StringMap<bool> &CalleeMap,
2504                             const FunctionDecl *Callee) {
2505   if (CalleeMap.empty() && CallerMap.empty()) {
2506     // The caller is potentially nullptr in the case where the call isn't in a
2507     // function.  In this case, the getFunctionFeatureMap ensures we just get
2508     // the TU level setting (since it cannot be modified by 'target'..
2509     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2510     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2511   }
2512 }
2513 
2514 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2515                                  SourceLocation CallLoc,
2516                                  const llvm::StringMap<bool> &CallerMap,
2517                                  const llvm::StringMap<bool> &CalleeMap,
2518                                  QualType Ty, StringRef Feature,
2519                                  bool IsArgument) {
2520   bool CallerHasFeat = CallerMap.lookup(Feature);
2521   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2522   if (!CallerHasFeat && !CalleeHasFeat)
2523     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2524            << IsArgument << Ty << Feature;
2525 
2526   // Mixing calling conventions here is very clearly an error.
2527   if (!CallerHasFeat || !CalleeHasFeat)
2528     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2529            << IsArgument << Ty << Feature;
2530 
2531   // Else, both caller and callee have the required feature, so there is no need
2532   // to diagnose.
2533   return false;
2534 }
2535 
2536 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2537                           SourceLocation CallLoc,
2538                           const llvm::StringMap<bool> &CallerMap,
2539                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2540                           bool IsArgument) {
2541   uint64_t Size = Ctx.getTypeSize(Ty);
2542   if (Size > 256)
2543     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2544                                 "avx512f", IsArgument);
2545 
2546   if (Size > 128)
2547     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2548                                 IsArgument);
2549 
2550   return false;
2551 }
2552 
2553 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2554     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2555     const FunctionDecl *Callee, const CallArgList &Args) const {
2556   llvm::StringMap<bool> CallerMap;
2557   llvm::StringMap<bool> CalleeMap;
2558   unsigned ArgIndex = 0;
2559 
2560   // We need to loop through the actual call arguments rather than the the
2561   // function's parameters, in case this variadic.
2562   for (const CallArg &Arg : Args) {
2563     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2564     // additionally changes how vectors >256 in size are passed. Like GCC, we
2565     // warn when a function is called with an argument where this will change.
2566     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2567     // the caller and callee features are mismatched.
2568     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2569     // change its ABI with attribute-target after this call.
2570     if (Arg.getType()->isVectorType() &&
2571         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2572       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2573       QualType Ty = Arg.getType();
2574       // The CallArg seems to have desugared the type already, so for clearer
2575       // diagnostics, replace it with the type in the FunctionDecl if possible.
2576       if (ArgIndex < Callee->getNumParams())
2577         Ty = Callee->getParamDecl(ArgIndex)->getType();
2578 
2579       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2580                         CalleeMap, Ty, /*IsArgument*/ true))
2581         return;
2582     }
2583     ++ArgIndex;
2584   }
2585 
2586   // Check return always, as we don't have a good way of knowing in codegen
2587   // whether this value is used, tail-called, etc.
2588   if (Callee->getReturnType()->isVectorType() &&
2589       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2590     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2591     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2592                   CalleeMap, Callee->getReturnType(),
2593                   /*IsArgument*/ false);
2594   }
2595 }
2596 
2597 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2598   // If the argument does not end in .lib, automatically add the suffix.
2599   // If the argument contains a space, enclose it in quotes.
2600   // This matches the behavior of MSVC.
2601   bool Quote = (Lib.find(' ') != StringRef::npos);
2602   std::string ArgStr = Quote ? "\"" : "";
2603   ArgStr += Lib;
2604   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2605     ArgStr += ".lib";
2606   ArgStr += Quote ? "\"" : "";
2607   return ArgStr;
2608 }
2609 
2610 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2611 public:
2612   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2613         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2614         unsigned NumRegisterParameters)
2615     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2616         Win32StructABI, NumRegisterParameters, false) {}
2617 
2618   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2619                            CodeGen::CodeGenModule &CGM) const override;
2620 
2621   void getDependentLibraryOption(llvm::StringRef Lib,
2622                                  llvm::SmallString<24> &Opt) const override {
2623     Opt = "/DEFAULTLIB:";
2624     Opt += qualifyWindowsLibrary(Lib);
2625   }
2626 
2627   void getDetectMismatchOption(llvm::StringRef Name,
2628                                llvm::StringRef Value,
2629                                llvm::SmallString<32> &Opt) const override {
2630     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2631   }
2632 };
2633 
2634 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2635                                           CodeGen::CodeGenModule &CGM) {
2636   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2637 
2638     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2639       Fn->addFnAttr("stack-probe-size",
2640                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2641     if (CGM.getCodeGenOpts().NoStackArgProbe)
2642       Fn->addFnAttr("no-stack-arg-probe");
2643   }
2644 }
2645 
2646 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2647     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2648   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2649   if (GV->isDeclaration())
2650     return;
2651   addStackProbeTargetAttributes(D, GV, CGM);
2652 }
2653 
2654 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2655 public:
2656   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2657                              X86AVXABILevel AVXLevel)
2658       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2659 
2660   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2661                            CodeGen::CodeGenModule &CGM) const override;
2662 
2663   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2664     return 7;
2665   }
2666 
2667   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2668                                llvm::Value *Address) const override {
2669     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2670 
2671     // 0-15 are the 16 integer registers.
2672     // 16 is %rip.
2673     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2674     return false;
2675   }
2676 
2677   void getDependentLibraryOption(llvm::StringRef Lib,
2678                                  llvm::SmallString<24> &Opt) const override {
2679     Opt = "/DEFAULTLIB:";
2680     Opt += qualifyWindowsLibrary(Lib);
2681   }
2682 
2683   void getDetectMismatchOption(llvm::StringRef Name,
2684                                llvm::StringRef Value,
2685                                llvm::SmallString<32> &Opt) const override {
2686     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2687   }
2688 };
2689 
2690 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2691     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2692   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2693   if (GV->isDeclaration())
2694     return;
2695   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2696     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2697       llvm::Function *Fn = cast<llvm::Function>(GV);
2698       Fn->addFnAttr("stackrealign");
2699     }
2700 
2701     addX86InterruptAttrs(FD, GV, CGM);
2702   }
2703 
2704   addStackProbeTargetAttributes(D, GV, CGM);
2705 }
2706 }
2707 
2708 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2709                               Class &Hi) const {
2710   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2711   //
2712   // (a) If one of the classes is Memory, the whole argument is passed in
2713   //     memory.
2714   //
2715   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2716   //     memory.
2717   //
2718   // (c) If the size of the aggregate exceeds two eightbytes and the first
2719   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2720   //     argument is passed in memory. NOTE: This is necessary to keep the
2721   //     ABI working for processors that don't support the __m256 type.
2722   //
2723   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2724   //
2725   // Some of these are enforced by the merging logic.  Others can arise
2726   // only with unions; for example:
2727   //   union { _Complex double; unsigned; }
2728   //
2729   // Note that clauses (b) and (c) were added in 0.98.
2730   //
2731   if (Hi == Memory)
2732     Lo = Memory;
2733   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2734     Lo = Memory;
2735   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2736     Lo = Memory;
2737   if (Hi == SSEUp && Lo != SSE)
2738     Hi = SSE;
2739 }
2740 
2741 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2742   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2743   // classified recursively so that always two fields are
2744   // considered. The resulting class is calculated according to
2745   // the classes of the fields in the eightbyte:
2746   //
2747   // (a) If both classes are equal, this is the resulting class.
2748   //
2749   // (b) If one of the classes is NO_CLASS, the resulting class is
2750   // the other class.
2751   //
2752   // (c) If one of the classes is MEMORY, the result is the MEMORY
2753   // class.
2754   //
2755   // (d) If one of the classes is INTEGER, the result is the
2756   // INTEGER.
2757   //
2758   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2759   // MEMORY is used as class.
2760   //
2761   // (f) Otherwise class SSE is used.
2762 
2763   // Accum should never be memory (we should have returned) or
2764   // ComplexX87 (because this cannot be passed in a structure).
2765   assert((Accum != Memory && Accum != ComplexX87) &&
2766          "Invalid accumulated classification during merge.");
2767   if (Accum == Field || Field == NoClass)
2768     return Accum;
2769   if (Field == Memory)
2770     return Memory;
2771   if (Accum == NoClass)
2772     return Field;
2773   if (Accum == Integer || Field == Integer)
2774     return Integer;
2775   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2776       Accum == X87 || Accum == X87Up)
2777     return Memory;
2778   return SSE;
2779 }
2780 
2781 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2782                              Class &Lo, Class &Hi, bool isNamedArg) const {
2783   // FIXME: This code can be simplified by introducing a simple value class for
2784   // Class pairs with appropriate constructor methods for the various
2785   // situations.
2786 
2787   // FIXME: Some of the split computations are wrong; unaligned vectors
2788   // shouldn't be passed in registers for example, so there is no chance they
2789   // can straddle an eightbyte. Verify & simplify.
2790 
2791   Lo = Hi = NoClass;
2792 
2793   Class &Current = OffsetBase < 64 ? Lo : Hi;
2794   Current = Memory;
2795 
2796   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2797     BuiltinType::Kind k = BT->getKind();
2798 
2799     if (k == BuiltinType::Void) {
2800       Current = NoClass;
2801     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2802       Lo = Integer;
2803       Hi = Integer;
2804     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2805       Current = Integer;
2806     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2807       Current = SSE;
2808     } else if (k == BuiltinType::LongDouble) {
2809       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2810       if (LDF == &llvm::APFloat::IEEEquad()) {
2811         Lo = SSE;
2812         Hi = SSEUp;
2813       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2814         Lo = X87;
2815         Hi = X87Up;
2816       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2817         Current = SSE;
2818       } else
2819         llvm_unreachable("unexpected long double representation!");
2820     }
2821     // FIXME: _Decimal32 and _Decimal64 are SSE.
2822     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2823     return;
2824   }
2825 
2826   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2827     // Classify the underlying integer type.
2828     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2829     return;
2830   }
2831 
2832   if (Ty->hasPointerRepresentation()) {
2833     Current = Integer;
2834     return;
2835   }
2836 
2837   if (Ty->isMemberPointerType()) {
2838     if (Ty->isMemberFunctionPointerType()) {
2839       if (Has64BitPointers) {
2840         // If Has64BitPointers, this is an {i64, i64}, so classify both
2841         // Lo and Hi now.
2842         Lo = Hi = Integer;
2843       } else {
2844         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2845         // straddles an eightbyte boundary, Hi should be classified as well.
2846         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2847         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2848         if (EB_FuncPtr != EB_ThisAdj) {
2849           Lo = Hi = Integer;
2850         } else {
2851           Current = Integer;
2852         }
2853       }
2854     } else {
2855       Current = Integer;
2856     }
2857     return;
2858   }
2859 
2860   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2861     uint64_t Size = getContext().getTypeSize(VT);
2862     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2863       // gcc passes the following as integer:
2864       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2865       // 2 bytes - <2 x char>, <1 x short>
2866       // 1 byte  - <1 x char>
2867       Current = Integer;
2868 
2869       // If this type crosses an eightbyte boundary, it should be
2870       // split.
2871       uint64_t EB_Lo = (OffsetBase) / 64;
2872       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2873       if (EB_Lo != EB_Hi)
2874         Hi = Lo;
2875     } else if (Size == 64) {
2876       QualType ElementType = VT->getElementType();
2877 
2878       // gcc passes <1 x double> in memory. :(
2879       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2880         return;
2881 
2882       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2883       // pass them as integer.  For platforms where clang is the de facto
2884       // platform compiler, we must continue to use integer.
2885       if (!classifyIntegerMMXAsSSE() &&
2886           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2887            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2888            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2889            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2890         Current = Integer;
2891       else
2892         Current = SSE;
2893 
2894       // If this type crosses an eightbyte boundary, it should be
2895       // split.
2896       if (OffsetBase && OffsetBase != 64)
2897         Hi = Lo;
2898     } else if (Size == 128 ||
2899                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2900       QualType ElementType = VT->getElementType();
2901 
2902       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2903       if (passInt128VectorsInMem() && Size != 128 &&
2904           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2905            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2906         return;
2907 
2908       // Arguments of 256-bits are split into four eightbyte chunks. The
2909       // least significant one belongs to class SSE and all the others to class
2910       // SSEUP. The original Lo and Hi design considers that types can't be
2911       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2912       // This design isn't correct for 256-bits, but since there're no cases
2913       // where the upper parts would need to be inspected, avoid adding
2914       // complexity and just consider Hi to match the 64-256 part.
2915       //
2916       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2917       // registers if they are "named", i.e. not part of the "..." of a
2918       // variadic function.
2919       //
2920       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2921       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2922       Lo = SSE;
2923       Hi = SSEUp;
2924     }
2925     return;
2926   }
2927 
2928   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2929     QualType ET = getContext().getCanonicalType(CT->getElementType());
2930 
2931     uint64_t Size = getContext().getTypeSize(Ty);
2932     if (ET->isIntegralOrEnumerationType()) {
2933       if (Size <= 64)
2934         Current = Integer;
2935       else if (Size <= 128)
2936         Lo = Hi = Integer;
2937     } else if (ET == getContext().FloatTy) {
2938       Current = SSE;
2939     } else if (ET == getContext().DoubleTy) {
2940       Lo = Hi = SSE;
2941     } else if (ET == getContext().LongDoubleTy) {
2942       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2943       if (LDF == &llvm::APFloat::IEEEquad())
2944         Current = Memory;
2945       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2946         Current = ComplexX87;
2947       else if (LDF == &llvm::APFloat::IEEEdouble())
2948         Lo = Hi = SSE;
2949       else
2950         llvm_unreachable("unexpected long double representation!");
2951     }
2952 
2953     // If this complex type crosses an eightbyte boundary then it
2954     // should be split.
2955     uint64_t EB_Real = (OffsetBase) / 64;
2956     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2957     if (Hi == NoClass && EB_Real != EB_Imag)
2958       Hi = Lo;
2959 
2960     return;
2961   }
2962 
2963   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2964     if (EITy->getNumBits() <= 64)
2965       Current = Integer;
2966     else if (EITy->getNumBits() <= 128)
2967       Lo = Hi = Integer;
2968     // Larger values need to get passed in memory.
2969     return;
2970   }
2971 
2972   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2973     // Arrays are treated like structures.
2974 
2975     uint64_t Size = getContext().getTypeSize(Ty);
2976 
2977     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2978     // than eight eightbytes, ..., it has class MEMORY.
2979     if (Size > 512)
2980       return;
2981 
2982     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2983     // fields, it has class MEMORY.
2984     //
2985     // Only need to check alignment of array base.
2986     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2987       return;
2988 
2989     // Otherwise implement simplified merge. We could be smarter about
2990     // this, but it isn't worth it and would be harder to verify.
2991     Current = NoClass;
2992     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2993     uint64_t ArraySize = AT->getSize().getZExtValue();
2994 
2995     // The only case a 256-bit wide vector could be used is when the array
2996     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2997     // to work for sizes wider than 128, early check and fallback to memory.
2998     //
2999     if (Size > 128 &&
3000         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3001       return;
3002 
3003     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3004       Class FieldLo, FieldHi;
3005       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3006       Lo = merge(Lo, FieldLo);
3007       Hi = merge(Hi, FieldHi);
3008       if (Lo == Memory || Hi == Memory)
3009         break;
3010     }
3011 
3012     postMerge(Size, Lo, Hi);
3013     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3014     return;
3015   }
3016 
3017   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3018     uint64_t Size = getContext().getTypeSize(Ty);
3019 
3020     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3021     // than eight eightbytes, ..., it has class MEMORY.
3022     if (Size > 512)
3023       return;
3024 
3025     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3026     // copy constructor or a non-trivial destructor, it is passed by invisible
3027     // reference.
3028     if (getRecordArgABI(RT, getCXXABI()))
3029       return;
3030 
3031     const RecordDecl *RD = RT->getDecl();
3032 
3033     // Assume variable sized types are passed in memory.
3034     if (RD->hasFlexibleArrayMember())
3035       return;
3036 
3037     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3038 
3039     // Reset Lo class, this will be recomputed.
3040     Current = NoClass;
3041 
3042     // If this is a C++ record, classify the bases first.
3043     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3044       for (const auto &I : CXXRD->bases()) {
3045         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3046                "Unexpected base class!");
3047         const auto *Base =
3048             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3049 
3050         // Classify this field.
3051         //
3052         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3053         // single eightbyte, each is classified separately. Each eightbyte gets
3054         // initialized to class NO_CLASS.
3055         Class FieldLo, FieldHi;
3056         uint64_t Offset =
3057           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3058         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3059         Lo = merge(Lo, FieldLo);
3060         Hi = merge(Hi, FieldHi);
3061         if (Lo == Memory || Hi == Memory) {
3062           postMerge(Size, Lo, Hi);
3063           return;
3064         }
3065       }
3066     }
3067 
3068     // Classify the fields one at a time, merging the results.
3069     unsigned idx = 0;
3070     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3071                                 LangOptions::ClangABI::Ver11 ||
3072                             getContext().getTargetInfo().getTriple().isPS4();
3073     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3074 
3075     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3076            i != e; ++i, ++idx) {
3077       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3078       bool BitField = i->isBitField();
3079 
3080       // Ignore padding bit-fields.
3081       if (BitField && i->isUnnamedBitfield())
3082         continue;
3083 
3084       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3085       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3086       //
3087       // The only case a 256-bit or a 512-bit wide vector could be used is when
3088       // the struct contains a single 256-bit or 512-bit element. Early check
3089       // and fallback to memory.
3090       //
3091       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3092       // than 128.
3093       if (Size > 128 &&
3094           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3095            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3096         Lo = Memory;
3097         postMerge(Size, Lo, Hi);
3098         return;
3099       }
3100       // Note, skip this test for bit-fields, see below.
3101       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3102         Lo = Memory;
3103         postMerge(Size, Lo, Hi);
3104         return;
3105       }
3106 
3107       // Classify this field.
3108       //
3109       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3110       // exceeds a single eightbyte, each is classified
3111       // separately. Each eightbyte gets initialized to class
3112       // NO_CLASS.
3113       Class FieldLo, FieldHi;
3114 
3115       // Bit-fields require special handling, they do not force the
3116       // structure to be passed in memory even if unaligned, and
3117       // therefore they can straddle an eightbyte.
3118       if (BitField) {
3119         assert(!i->isUnnamedBitfield());
3120         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3121         uint64_t Size = i->getBitWidthValue(getContext());
3122 
3123         uint64_t EB_Lo = Offset / 64;
3124         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3125 
3126         if (EB_Lo) {
3127           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3128           FieldLo = NoClass;
3129           FieldHi = Integer;
3130         } else {
3131           FieldLo = Integer;
3132           FieldHi = EB_Hi ? Integer : NoClass;
3133         }
3134       } else
3135         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3136       Lo = merge(Lo, FieldLo);
3137       Hi = merge(Hi, FieldHi);
3138       if (Lo == Memory || Hi == Memory)
3139         break;
3140     }
3141 
3142     postMerge(Size, Lo, Hi);
3143   }
3144 }
3145 
3146 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3147   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3148   // place naturally.
3149   if (!isAggregateTypeForABI(Ty)) {
3150     // Treat an enum type as its underlying type.
3151     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3152       Ty = EnumTy->getDecl()->getIntegerType();
3153 
3154     if (Ty->isExtIntType())
3155       return getNaturalAlignIndirect(Ty);
3156 
3157     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3158                                               : ABIArgInfo::getDirect());
3159   }
3160 
3161   return getNaturalAlignIndirect(Ty);
3162 }
3163 
3164 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3165   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3166     uint64_t Size = getContext().getTypeSize(VecTy);
3167     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3168     if (Size <= 64 || Size > LargestVector)
3169       return true;
3170     QualType EltTy = VecTy->getElementType();
3171     if (passInt128VectorsInMem() &&
3172         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3173          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3174       return true;
3175   }
3176 
3177   return false;
3178 }
3179 
3180 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3181                                             unsigned freeIntRegs) const {
3182   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3183   // place naturally.
3184   //
3185   // This assumption is optimistic, as there could be free registers available
3186   // when we need to pass this argument in memory, and LLVM could try to pass
3187   // the argument in the free register. This does not seem to happen currently,
3188   // but this code would be much safer if we could mark the argument with
3189   // 'onstack'. See PR12193.
3190   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3191       !Ty->isExtIntType()) {
3192     // Treat an enum type as its underlying type.
3193     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3194       Ty = EnumTy->getDecl()->getIntegerType();
3195 
3196     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3197                                               : ABIArgInfo::getDirect());
3198   }
3199 
3200   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3201     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3202 
3203   // Compute the byval alignment. We specify the alignment of the byval in all
3204   // cases so that the mid-level optimizer knows the alignment of the byval.
3205   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3206 
3207   // Attempt to avoid passing indirect results using byval when possible. This
3208   // is important for good codegen.
3209   //
3210   // We do this by coercing the value into a scalar type which the backend can
3211   // handle naturally (i.e., without using byval).
3212   //
3213   // For simplicity, we currently only do this when we have exhausted all of the
3214   // free integer registers. Doing this when there are free integer registers
3215   // would require more care, as we would have to ensure that the coerced value
3216   // did not claim the unused register. That would require either reording the
3217   // arguments to the function (so that any subsequent inreg values came first),
3218   // or only doing this optimization when there were no following arguments that
3219   // might be inreg.
3220   //
3221   // We currently expect it to be rare (particularly in well written code) for
3222   // arguments to be passed on the stack when there are still free integer
3223   // registers available (this would typically imply large structs being passed
3224   // by value), so this seems like a fair tradeoff for now.
3225   //
3226   // We can revisit this if the backend grows support for 'onstack' parameter
3227   // attributes. See PR12193.
3228   if (freeIntRegs == 0) {
3229     uint64_t Size = getContext().getTypeSize(Ty);
3230 
3231     // If this type fits in an eightbyte, coerce it into the matching integral
3232     // type, which will end up on the stack (with alignment 8).
3233     if (Align == 8 && Size <= 64)
3234       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3235                                                           Size));
3236   }
3237 
3238   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3239 }
3240 
3241 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3242 /// register. Pick an LLVM IR type that will be passed as a vector register.
3243 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3244   // Wrapper structs/arrays that only contain vectors are passed just like
3245   // vectors; strip them off if present.
3246   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3247     Ty = QualType(InnerTy, 0);
3248 
3249   llvm::Type *IRType = CGT.ConvertType(Ty);
3250   if (isa<llvm::VectorType>(IRType)) {
3251     // Don't pass vXi128 vectors in their native type, the backend can't
3252     // legalize them.
3253     if (passInt128VectorsInMem() &&
3254         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3255       // Use a vXi64 vector.
3256       uint64_t Size = getContext().getTypeSize(Ty);
3257       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3258                                         Size / 64);
3259     }
3260 
3261     return IRType;
3262   }
3263 
3264   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3265     return IRType;
3266 
3267   // We couldn't find the preferred IR vector type for 'Ty'.
3268   uint64_t Size = getContext().getTypeSize(Ty);
3269   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3270 
3271 
3272   // Return a LLVM IR vector type based on the size of 'Ty'.
3273   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3274                                     Size / 64);
3275 }
3276 
3277 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3278 /// is known to either be off the end of the specified type or being in
3279 /// alignment padding.  The user type specified is known to be at most 128 bits
3280 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3281 /// classification that put one of the two halves in the INTEGER class.
3282 ///
3283 /// It is conservatively correct to return false.
3284 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3285                                   unsigned EndBit, ASTContext &Context) {
3286   // If the bytes being queried are off the end of the type, there is no user
3287   // data hiding here.  This handles analysis of builtins, vectors and other
3288   // types that don't contain interesting padding.
3289   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3290   if (TySize <= StartBit)
3291     return true;
3292 
3293   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3294     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3295     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3296 
3297     // Check each element to see if the element overlaps with the queried range.
3298     for (unsigned i = 0; i != NumElts; ++i) {
3299       // If the element is after the span we care about, then we're done..
3300       unsigned EltOffset = i*EltSize;
3301       if (EltOffset >= EndBit) break;
3302 
3303       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3304       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3305                                  EndBit-EltOffset, Context))
3306         return false;
3307     }
3308     // If it overlaps no elements, then it is safe to process as padding.
3309     return true;
3310   }
3311 
3312   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3313     const RecordDecl *RD = RT->getDecl();
3314     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3315 
3316     // If this is a C++ record, check the bases first.
3317     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3318       for (const auto &I : CXXRD->bases()) {
3319         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3320                "Unexpected base class!");
3321         const auto *Base =
3322             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3323 
3324         // If the base is after the span we care about, ignore it.
3325         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3326         if (BaseOffset >= EndBit) continue;
3327 
3328         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3329         if (!BitsContainNoUserData(I.getType(), BaseStart,
3330                                    EndBit-BaseOffset, Context))
3331           return false;
3332       }
3333     }
3334 
3335     // Verify that no field has data that overlaps the region of interest.  Yes
3336     // this could be sped up a lot by being smarter about queried fields,
3337     // however we're only looking at structs up to 16 bytes, so we don't care
3338     // much.
3339     unsigned idx = 0;
3340     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3341          i != e; ++i, ++idx) {
3342       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3343 
3344       // If we found a field after the region we care about, then we're done.
3345       if (FieldOffset >= EndBit) break;
3346 
3347       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3348       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3349                                  Context))
3350         return false;
3351     }
3352 
3353     // If nothing in this record overlapped the area of interest, then we're
3354     // clean.
3355     return true;
3356   }
3357 
3358   return false;
3359 }
3360 
3361 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3362 /// float member at the specified offset.  For example, {int,{float}} has a
3363 /// float at offset 4.  It is conservatively correct for this routine to return
3364 /// false.
3365 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3366                                   const llvm::DataLayout &TD) {
3367   // Base case if we find a float.
3368   if (IROffset == 0 && IRType->isFloatTy())
3369     return true;
3370 
3371   // If this is a struct, recurse into the field at the specified offset.
3372   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3373     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3374     unsigned Elt = SL->getElementContainingOffset(IROffset);
3375     IROffset -= SL->getElementOffset(Elt);
3376     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3377   }
3378 
3379   // If this is an array, recurse into the field at the specified offset.
3380   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3381     llvm::Type *EltTy = ATy->getElementType();
3382     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3383     IROffset -= IROffset/EltSize*EltSize;
3384     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3385   }
3386 
3387   return false;
3388 }
3389 
3390 
3391 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3392 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3393 llvm::Type *X86_64ABIInfo::
3394 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3395                    QualType SourceTy, unsigned SourceOffset) const {
3396   // The only three choices we have are either double, <2 x float>, or float. We
3397   // pass as float if the last 4 bytes is just padding.  This happens for
3398   // structs that contain 3 floats.
3399   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3400                             SourceOffset*8+64, getContext()))
3401     return llvm::Type::getFloatTy(getVMContext());
3402 
3403   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3404   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3405   // case.
3406   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3407       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3408     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3409                                       2);
3410 
3411   return llvm::Type::getDoubleTy(getVMContext());
3412 }
3413 
3414 
3415 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3416 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3417 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3418 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3419 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3420 /// etc).
3421 ///
3422 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3423 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3424 /// the 8-byte value references.  PrefType may be null.
3425 ///
3426 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3427 /// an offset into this that we're processing (which is always either 0 or 8).
3428 ///
3429 llvm::Type *X86_64ABIInfo::
3430 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3431                        QualType SourceTy, unsigned SourceOffset) const {
3432   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3433   // returning an 8-byte unit starting with it.  See if we can safely use it.
3434   if (IROffset == 0) {
3435     // Pointers and int64's always fill the 8-byte unit.
3436     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3437         IRType->isIntegerTy(64))
3438       return IRType;
3439 
3440     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3441     // goodness in the source type is just tail padding.  This is allowed to
3442     // kick in for struct {double,int} on the int, but not on
3443     // struct{double,int,int} because we wouldn't return the second int.  We
3444     // have to do this analysis on the source type because we can't depend on
3445     // unions being lowered a specific way etc.
3446     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3447         IRType->isIntegerTy(32) ||
3448         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3449       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3450           cast<llvm::IntegerType>(IRType)->getBitWidth();
3451 
3452       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3453                                 SourceOffset*8+64, getContext()))
3454         return IRType;
3455     }
3456   }
3457 
3458   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3459     // If this is a struct, recurse into the field at the specified offset.
3460     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3461     if (IROffset < SL->getSizeInBytes()) {
3462       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3463       IROffset -= SL->getElementOffset(FieldIdx);
3464 
3465       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3466                                     SourceTy, SourceOffset);
3467     }
3468   }
3469 
3470   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3471     llvm::Type *EltTy = ATy->getElementType();
3472     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3473     unsigned EltOffset = IROffset/EltSize*EltSize;
3474     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3475                                   SourceOffset);
3476   }
3477 
3478   // Okay, we don't have any better idea of what to pass, so we pass this in an
3479   // integer register that isn't too big to fit the rest of the struct.
3480   unsigned TySizeInBytes =
3481     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3482 
3483   assert(TySizeInBytes != SourceOffset && "Empty field?");
3484 
3485   // It is always safe to classify this as an integer type up to i64 that
3486   // isn't larger than the structure.
3487   return llvm::IntegerType::get(getVMContext(),
3488                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3489 }
3490 
3491 
3492 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3493 /// be used as elements of a two register pair to pass or return, return a
3494 /// first class aggregate to represent them.  For example, if the low part of
3495 /// a by-value argument should be passed as i32* and the high part as float,
3496 /// return {i32*, float}.
3497 static llvm::Type *
3498 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3499                            const llvm::DataLayout &TD) {
3500   // In order to correctly satisfy the ABI, we need to the high part to start
3501   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3502   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3503   // the second element at offset 8.  Check for this:
3504   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3505   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3506   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3507   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3508 
3509   // To handle this, we have to increase the size of the low part so that the
3510   // second element will start at an 8 byte offset.  We can't increase the size
3511   // of the second element because it might make us access off the end of the
3512   // struct.
3513   if (HiStart != 8) {
3514     // There are usually two sorts of types the ABI generation code can produce
3515     // for the low part of a pair that aren't 8 bytes in size: float or
3516     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3517     // NaCl).
3518     // Promote these to a larger type.
3519     if (Lo->isFloatTy())
3520       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3521     else {
3522       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3523              && "Invalid/unknown lo type");
3524       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3525     }
3526   }
3527 
3528   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3529 
3530   // Verify that the second element is at an 8-byte offset.
3531   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3532          "Invalid x86-64 argument pair!");
3533   return Result;
3534 }
3535 
3536 ABIArgInfo X86_64ABIInfo::
3537 classifyReturnType(QualType RetTy) const {
3538   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3539   // classification algorithm.
3540   X86_64ABIInfo::Class Lo, Hi;
3541   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3542 
3543   // Check some invariants.
3544   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3545   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3546 
3547   llvm::Type *ResType = nullptr;
3548   switch (Lo) {
3549   case NoClass:
3550     if (Hi == NoClass)
3551       return ABIArgInfo::getIgnore();
3552     // If the low part is just padding, it takes no register, leave ResType
3553     // null.
3554     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3555            "Unknown missing lo part");
3556     break;
3557 
3558   case SSEUp:
3559   case X87Up:
3560     llvm_unreachable("Invalid classification for lo word.");
3561 
3562     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3563     // hidden argument.
3564   case Memory:
3565     return getIndirectReturnResult(RetTy);
3566 
3567     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3568     // available register of the sequence %rax, %rdx is used.
3569   case Integer:
3570     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3571 
3572     // If we have a sign or zero extended integer, make sure to return Extend
3573     // so that the parameter gets the right LLVM IR attributes.
3574     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3575       // Treat an enum type as its underlying type.
3576       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3577         RetTy = EnumTy->getDecl()->getIntegerType();
3578 
3579       if (RetTy->isIntegralOrEnumerationType() &&
3580           isPromotableIntegerTypeForABI(RetTy))
3581         return ABIArgInfo::getExtend(RetTy);
3582     }
3583     break;
3584 
3585     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3586     // available SSE register of the sequence %xmm0, %xmm1 is used.
3587   case SSE:
3588     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3589     break;
3590 
3591     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3592     // returned on the X87 stack in %st0 as 80-bit x87 number.
3593   case X87:
3594     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3595     break;
3596 
3597     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3598     // part of the value is returned in %st0 and the imaginary part in
3599     // %st1.
3600   case ComplexX87:
3601     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3602     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3603                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3604     break;
3605   }
3606 
3607   llvm::Type *HighPart = nullptr;
3608   switch (Hi) {
3609     // Memory was handled previously and X87 should
3610     // never occur as a hi class.
3611   case Memory:
3612   case X87:
3613     llvm_unreachable("Invalid classification for hi word.");
3614 
3615   case ComplexX87: // Previously handled.
3616   case NoClass:
3617     break;
3618 
3619   case Integer:
3620     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3621     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3622       return ABIArgInfo::getDirect(HighPart, 8);
3623     break;
3624   case SSE:
3625     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3626     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3627       return ABIArgInfo::getDirect(HighPart, 8);
3628     break;
3629 
3630     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3631     // is passed in the next available eightbyte chunk if the last used
3632     // vector register.
3633     //
3634     // SSEUP should always be preceded by SSE, just widen.
3635   case SSEUp:
3636     assert(Lo == SSE && "Unexpected SSEUp classification.");
3637     ResType = GetByteVectorType(RetTy);
3638     break;
3639 
3640     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3641     // returned together with the previous X87 value in %st0.
3642   case X87Up:
3643     // If X87Up is preceded by X87, we don't need to do
3644     // anything. However, in some cases with unions it may not be
3645     // preceded by X87. In such situations we follow gcc and pass the
3646     // extra bits in an SSE reg.
3647     if (Lo != X87) {
3648       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3649       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3650         return ABIArgInfo::getDirect(HighPart, 8);
3651     }
3652     break;
3653   }
3654 
3655   // If a high part was specified, merge it together with the low part.  It is
3656   // known to pass in the high eightbyte of the result.  We do this by forming a
3657   // first class struct aggregate with the high and low part: {low, high}
3658   if (HighPart)
3659     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3660 
3661   return ABIArgInfo::getDirect(ResType);
3662 }
3663 
3664 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3665   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3666   bool isNamedArg)
3667   const
3668 {
3669   Ty = useFirstFieldIfTransparentUnion(Ty);
3670 
3671   X86_64ABIInfo::Class Lo, Hi;
3672   classify(Ty, 0, Lo, Hi, isNamedArg);
3673 
3674   // Check some invariants.
3675   // FIXME: Enforce these by construction.
3676   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3677   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3678 
3679   neededInt = 0;
3680   neededSSE = 0;
3681   llvm::Type *ResType = nullptr;
3682   switch (Lo) {
3683   case NoClass:
3684     if (Hi == NoClass)
3685       return ABIArgInfo::getIgnore();
3686     // If the low part is just padding, it takes no register, leave ResType
3687     // null.
3688     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3689            "Unknown missing lo part");
3690     break;
3691 
3692     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3693     // on the stack.
3694   case Memory:
3695 
3696     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3697     // COMPLEX_X87, it is passed in memory.
3698   case X87:
3699   case ComplexX87:
3700     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3701       ++neededInt;
3702     return getIndirectResult(Ty, freeIntRegs);
3703 
3704   case SSEUp:
3705   case X87Up:
3706     llvm_unreachable("Invalid classification for lo word.");
3707 
3708     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3709     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3710     // and %r9 is used.
3711   case Integer:
3712     ++neededInt;
3713 
3714     // Pick an 8-byte type based on the preferred type.
3715     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3716 
3717     // If we have a sign or zero extended integer, make sure to return Extend
3718     // so that the parameter gets the right LLVM IR attributes.
3719     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3720       // Treat an enum type as its underlying type.
3721       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3722         Ty = EnumTy->getDecl()->getIntegerType();
3723 
3724       if (Ty->isIntegralOrEnumerationType() &&
3725           isPromotableIntegerTypeForABI(Ty))
3726         return ABIArgInfo::getExtend(Ty);
3727     }
3728 
3729     break;
3730 
3731     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3732     // available SSE register is used, the registers are taken in the
3733     // order from %xmm0 to %xmm7.
3734   case SSE: {
3735     llvm::Type *IRType = CGT.ConvertType(Ty);
3736     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3737     ++neededSSE;
3738     break;
3739   }
3740   }
3741 
3742   llvm::Type *HighPart = nullptr;
3743   switch (Hi) {
3744     // Memory was handled previously, ComplexX87 and X87 should
3745     // never occur as hi classes, and X87Up must be preceded by X87,
3746     // which is passed in memory.
3747   case Memory:
3748   case X87:
3749   case ComplexX87:
3750     llvm_unreachable("Invalid classification for hi word.");
3751 
3752   case NoClass: break;
3753 
3754   case Integer:
3755     ++neededInt;
3756     // Pick an 8-byte type based on the preferred type.
3757     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3758 
3759     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3760       return ABIArgInfo::getDirect(HighPart, 8);
3761     break;
3762 
3763     // X87Up generally doesn't occur here (long double is passed in
3764     // memory), except in situations involving unions.
3765   case X87Up:
3766   case SSE:
3767     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3768 
3769     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3770       return ABIArgInfo::getDirect(HighPart, 8);
3771 
3772     ++neededSSE;
3773     break;
3774 
3775     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3776     // eightbyte is passed in the upper half of the last used SSE
3777     // register.  This only happens when 128-bit vectors are passed.
3778   case SSEUp:
3779     assert(Lo == SSE && "Unexpected SSEUp classification");
3780     ResType = GetByteVectorType(Ty);
3781     break;
3782   }
3783 
3784   // If a high part was specified, merge it together with the low part.  It is
3785   // known to pass in the high eightbyte of the result.  We do this by forming a
3786   // first class struct aggregate with the high and low part: {low, high}
3787   if (HighPart)
3788     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3789 
3790   return ABIArgInfo::getDirect(ResType);
3791 }
3792 
3793 ABIArgInfo
3794 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3795                                              unsigned &NeededSSE) const {
3796   auto RT = Ty->getAs<RecordType>();
3797   assert(RT && "classifyRegCallStructType only valid with struct types");
3798 
3799   if (RT->getDecl()->hasFlexibleArrayMember())
3800     return getIndirectReturnResult(Ty);
3801 
3802   // Sum up bases
3803   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3804     if (CXXRD->isDynamicClass()) {
3805       NeededInt = NeededSSE = 0;
3806       return getIndirectReturnResult(Ty);
3807     }
3808 
3809     for (const auto &I : CXXRD->bases())
3810       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3811               .isIndirect()) {
3812         NeededInt = NeededSSE = 0;
3813         return getIndirectReturnResult(Ty);
3814       }
3815   }
3816 
3817   // Sum up members
3818   for (const auto *FD : RT->getDecl()->fields()) {
3819     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3820       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3821               .isIndirect()) {
3822         NeededInt = NeededSSE = 0;
3823         return getIndirectReturnResult(Ty);
3824       }
3825     } else {
3826       unsigned LocalNeededInt, LocalNeededSSE;
3827       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3828                                LocalNeededSSE, true)
3829               .isIndirect()) {
3830         NeededInt = NeededSSE = 0;
3831         return getIndirectReturnResult(Ty);
3832       }
3833       NeededInt += LocalNeededInt;
3834       NeededSSE += LocalNeededSSE;
3835     }
3836   }
3837 
3838   return ABIArgInfo::getDirect();
3839 }
3840 
3841 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3842                                                     unsigned &NeededInt,
3843                                                     unsigned &NeededSSE) const {
3844 
3845   NeededInt = 0;
3846   NeededSSE = 0;
3847 
3848   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3849 }
3850 
3851 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3852 
3853   const unsigned CallingConv = FI.getCallingConvention();
3854   // It is possible to force Win64 calling convention on any x86_64 target by
3855   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3856   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3857   if (CallingConv == llvm::CallingConv::Win64) {
3858     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3859     Win64ABIInfo.computeInfo(FI);
3860     return;
3861   }
3862 
3863   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3864 
3865   // Keep track of the number of assigned registers.
3866   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3867   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3868   unsigned NeededInt, NeededSSE;
3869 
3870   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3871     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3872         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3873       FI.getReturnInfo() =
3874           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3875       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3876         FreeIntRegs -= NeededInt;
3877         FreeSSERegs -= NeededSSE;
3878       } else {
3879         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3880       }
3881     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3882                getContext().getCanonicalType(FI.getReturnType()
3883                                                  ->getAs<ComplexType>()
3884                                                  ->getElementType()) ==
3885                    getContext().LongDoubleTy)
3886       // Complex Long Double Type is passed in Memory when Regcall
3887       // calling convention is used.
3888       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3889     else
3890       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3891   }
3892 
3893   // If the return value is indirect, then the hidden argument is consuming one
3894   // integer register.
3895   if (FI.getReturnInfo().isIndirect())
3896     --FreeIntRegs;
3897 
3898   // The chain argument effectively gives us another free register.
3899   if (FI.isChainCall())
3900     ++FreeIntRegs;
3901 
3902   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3903   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3904   // get assigned (in left-to-right order) for passing as follows...
3905   unsigned ArgNo = 0;
3906   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3907        it != ie; ++it, ++ArgNo) {
3908     bool IsNamedArg = ArgNo < NumRequiredArgs;
3909 
3910     if (IsRegCall && it->type->isStructureOrClassType())
3911       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3912     else
3913       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3914                                       NeededSSE, IsNamedArg);
3915 
3916     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3917     // eightbyte of an argument, the whole argument is passed on the
3918     // stack. If registers have already been assigned for some
3919     // eightbytes of such an argument, the assignments get reverted.
3920     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3921       FreeIntRegs -= NeededInt;
3922       FreeSSERegs -= NeededSSE;
3923     } else {
3924       it->info = getIndirectResult(it->type, FreeIntRegs);
3925     }
3926   }
3927 }
3928 
3929 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3930                                          Address VAListAddr, QualType Ty) {
3931   Address overflow_arg_area_p =
3932       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3933   llvm::Value *overflow_arg_area =
3934     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3935 
3936   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3937   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3938   // It isn't stated explicitly in the standard, but in practice we use
3939   // alignment greater than 16 where necessary.
3940   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3941   if (Align > CharUnits::fromQuantity(8)) {
3942     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3943                                                       Align);
3944   }
3945 
3946   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3947   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3948   llvm::Value *Res =
3949     CGF.Builder.CreateBitCast(overflow_arg_area,
3950                               llvm::PointerType::getUnqual(LTy));
3951 
3952   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3953   // l->overflow_arg_area + sizeof(type).
3954   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3955   // an 8 byte boundary.
3956 
3957   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3958   llvm::Value *Offset =
3959       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3960   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3961                                             "overflow_arg_area.next");
3962   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3963 
3964   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3965   return Address(Res, Align);
3966 }
3967 
3968 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3969                                  QualType Ty) const {
3970   // Assume that va_list type is correct; should be pointer to LLVM type:
3971   // struct {
3972   //   i32 gp_offset;
3973   //   i32 fp_offset;
3974   //   i8* overflow_arg_area;
3975   //   i8* reg_save_area;
3976   // };
3977   unsigned neededInt, neededSSE;
3978 
3979   Ty = getContext().getCanonicalType(Ty);
3980   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3981                                        /*isNamedArg*/false);
3982 
3983   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3984   // in the registers. If not go to step 7.
3985   if (!neededInt && !neededSSE)
3986     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3987 
3988   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3989   // general purpose registers needed to pass type and num_fp to hold
3990   // the number of floating point registers needed.
3991 
3992   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3993   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3994   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3995   //
3996   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3997   // register save space).
3998 
3999   llvm::Value *InRegs = nullptr;
4000   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4001   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4002   if (neededInt) {
4003     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4004     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4005     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4006     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4007   }
4008 
4009   if (neededSSE) {
4010     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4011     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4012     llvm::Value *FitsInFP =
4013       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4014     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4015     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4016   }
4017 
4018   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4019   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4020   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4021   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4022 
4023   // Emit code to load the value if it was passed in registers.
4024 
4025   CGF.EmitBlock(InRegBlock);
4026 
4027   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4028   // an offset of l->gp_offset and/or l->fp_offset. This may require
4029   // copying to a temporary location in case the parameter is passed
4030   // in different register classes or requires an alignment greater
4031   // than 8 for general purpose registers and 16 for XMM registers.
4032   //
4033   // FIXME: This really results in shameful code when we end up needing to
4034   // collect arguments from different places; often what should result in a
4035   // simple assembling of a structure from scattered addresses has many more
4036   // loads than necessary. Can we clean this up?
4037   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4038   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4039       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4040 
4041   Address RegAddr = Address::invalid();
4042   if (neededInt && neededSSE) {
4043     // FIXME: Cleanup.
4044     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4045     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4046     Address Tmp = CGF.CreateMemTemp(Ty);
4047     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4048     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4049     llvm::Type *TyLo = ST->getElementType(0);
4050     llvm::Type *TyHi = ST->getElementType(1);
4051     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4052            "Unexpected ABI info for mixed regs");
4053     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4054     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4055     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4056     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4057     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4058     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4059 
4060     // Copy the first element.
4061     // FIXME: Our choice of alignment here and below is probably pessimistic.
4062     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4063         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4064         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4065     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4066 
4067     // Copy the second element.
4068     V = CGF.Builder.CreateAlignedLoad(
4069         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4070         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4071     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4072 
4073     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4074   } else if (neededInt) {
4075     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4076                       CharUnits::fromQuantity(8));
4077     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4078 
4079     // Copy to a temporary if necessary to ensure the appropriate alignment.
4080     auto TInfo = getContext().getTypeInfoInChars(Ty);
4081     uint64_t TySize = TInfo.Width.getQuantity();
4082     CharUnits TyAlign = TInfo.Align;
4083 
4084     // Copy into a temporary if the type is more aligned than the
4085     // register save area.
4086     if (TyAlign.getQuantity() > 8) {
4087       Address Tmp = CGF.CreateMemTemp(Ty);
4088       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4089       RegAddr = Tmp;
4090     }
4091 
4092   } else if (neededSSE == 1) {
4093     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4094                       CharUnits::fromQuantity(16));
4095     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4096   } else {
4097     assert(neededSSE == 2 && "Invalid number of needed registers!");
4098     // SSE registers are spaced 16 bytes apart in the register save
4099     // area, we need to collect the two eightbytes together.
4100     // The ABI isn't explicit about this, but it seems reasonable
4101     // to assume that the slots are 16-byte aligned, since the stack is
4102     // naturally 16-byte aligned and the prologue is expected to store
4103     // all the SSE registers to the RSA.
4104     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4105                                 CharUnits::fromQuantity(16));
4106     Address RegAddrHi =
4107       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4108                                              CharUnits::fromQuantity(16));
4109     llvm::Type *ST = AI.canHaveCoerceToType()
4110                          ? AI.getCoerceToType()
4111                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4112     llvm::Value *V;
4113     Address Tmp = CGF.CreateMemTemp(Ty);
4114     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4115     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4116         RegAddrLo, ST->getStructElementType(0)));
4117     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4118     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4119         RegAddrHi, ST->getStructElementType(1)));
4120     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4121 
4122     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4123   }
4124 
4125   // AMD64-ABI 3.5.7p5: Step 5. Set:
4126   // l->gp_offset = l->gp_offset + num_gp * 8
4127   // l->fp_offset = l->fp_offset + num_fp * 16.
4128   if (neededInt) {
4129     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4130     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4131                             gp_offset_p);
4132   }
4133   if (neededSSE) {
4134     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4135     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4136                             fp_offset_p);
4137   }
4138   CGF.EmitBranch(ContBlock);
4139 
4140   // Emit code to load the value if it was passed in memory.
4141 
4142   CGF.EmitBlock(InMemBlock);
4143   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4144 
4145   // Return the appropriate result.
4146 
4147   CGF.EmitBlock(ContBlock);
4148   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4149                                  "vaarg.addr");
4150   return ResAddr;
4151 }
4152 
4153 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4154                                    QualType Ty) const {
4155   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4156                           CGF.getContext().getTypeInfoInChars(Ty),
4157                           CharUnits::fromQuantity(8),
4158                           /*allowHigherAlign*/ false);
4159 }
4160 
4161 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4162     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4163   const Type *Base = nullptr;
4164   uint64_t NumElts = 0;
4165 
4166   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4167       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4168     FreeSSERegs -= NumElts;
4169     return getDirectX86Hva();
4170   }
4171   return current;
4172 }
4173 
4174 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4175                                       bool IsReturnType, bool IsVectorCall,
4176                                       bool IsRegCall) const {
4177 
4178   if (Ty->isVoidType())
4179     return ABIArgInfo::getIgnore();
4180 
4181   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4182     Ty = EnumTy->getDecl()->getIntegerType();
4183 
4184   TypeInfo Info = getContext().getTypeInfo(Ty);
4185   uint64_t Width = Info.Width;
4186   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4187 
4188   const RecordType *RT = Ty->getAs<RecordType>();
4189   if (RT) {
4190     if (!IsReturnType) {
4191       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4192         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4193     }
4194 
4195     if (RT->getDecl()->hasFlexibleArrayMember())
4196       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4197 
4198   }
4199 
4200   const Type *Base = nullptr;
4201   uint64_t NumElts = 0;
4202   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4203   // other targets.
4204   if ((IsVectorCall || IsRegCall) &&
4205       isHomogeneousAggregate(Ty, Base, NumElts)) {
4206     if (IsRegCall) {
4207       if (FreeSSERegs >= NumElts) {
4208         FreeSSERegs -= NumElts;
4209         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4210           return ABIArgInfo::getDirect();
4211         return ABIArgInfo::getExpand();
4212       }
4213       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4214     } else if (IsVectorCall) {
4215       if (FreeSSERegs >= NumElts &&
4216           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4217         FreeSSERegs -= NumElts;
4218         return ABIArgInfo::getDirect();
4219       } else if (IsReturnType) {
4220         return ABIArgInfo::getExpand();
4221       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4222         // HVAs are delayed and reclassified in the 2nd step.
4223         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4224       }
4225     }
4226   }
4227 
4228   if (Ty->isMemberPointerType()) {
4229     // If the member pointer is represented by an LLVM int or ptr, pass it
4230     // directly.
4231     llvm::Type *LLTy = CGT.ConvertType(Ty);
4232     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4233       return ABIArgInfo::getDirect();
4234   }
4235 
4236   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4237     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4238     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4239     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4240       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4241 
4242     // Otherwise, coerce it to a small integer.
4243     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4244   }
4245 
4246   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4247     switch (BT->getKind()) {
4248     case BuiltinType::Bool:
4249       // Bool type is always extended to the ABI, other builtin types are not
4250       // extended.
4251       return ABIArgInfo::getExtend(Ty);
4252 
4253     case BuiltinType::LongDouble:
4254       // Mingw64 GCC uses the old 80 bit extended precision floating point
4255       // unit. It passes them indirectly through memory.
4256       if (IsMingw64) {
4257         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4258         if (LDF == &llvm::APFloat::x87DoubleExtended())
4259           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4260       }
4261       break;
4262 
4263     case BuiltinType::Int128:
4264     case BuiltinType::UInt128:
4265       // If it's a parameter type, the normal ABI rule is that arguments larger
4266       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4267       // even though it isn't particularly efficient.
4268       if (!IsReturnType)
4269         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4270 
4271       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4272       // Clang matches them for compatibility.
4273       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4274           llvm::Type::getInt64Ty(getVMContext()), 2));
4275 
4276     default:
4277       break;
4278     }
4279   }
4280 
4281   if (Ty->isExtIntType()) {
4282     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4283     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4284     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4285     // anyway as long is it fits in them, so we don't have to check the power of
4286     // 2.
4287     if (Width <= 64)
4288       return ABIArgInfo::getDirect();
4289     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4290   }
4291 
4292   return ABIArgInfo::getDirect();
4293 }
4294 
4295 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4296   const unsigned CC = FI.getCallingConvention();
4297   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4298   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4299 
4300   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4301   // classification rules.
4302   if (CC == llvm::CallingConv::X86_64_SysV) {
4303     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4304     SysVABIInfo.computeInfo(FI);
4305     return;
4306   }
4307 
4308   unsigned FreeSSERegs = 0;
4309   if (IsVectorCall) {
4310     // We can use up to 4 SSE return registers with vectorcall.
4311     FreeSSERegs = 4;
4312   } else if (IsRegCall) {
4313     // RegCall gives us 16 SSE registers.
4314     FreeSSERegs = 16;
4315   }
4316 
4317   if (!getCXXABI().classifyReturnType(FI))
4318     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4319                                   IsVectorCall, IsRegCall);
4320 
4321   if (IsVectorCall) {
4322     // We can use up to 6 SSE register parameters with vectorcall.
4323     FreeSSERegs = 6;
4324   } else if (IsRegCall) {
4325     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4326     FreeSSERegs = 16;
4327   }
4328 
4329   unsigned ArgNum = 0;
4330   unsigned ZeroSSERegs = 0;
4331   for (auto &I : FI.arguments()) {
4332     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4333     // XMM/YMM registers. After the sixth argument, pretend no vector
4334     // registers are left.
4335     unsigned *MaybeFreeSSERegs =
4336         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4337     I.info =
4338         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4339     ++ArgNum;
4340   }
4341 
4342   if (IsVectorCall) {
4343     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4344     // second pass.
4345     for (auto &I : FI.arguments())
4346       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4347   }
4348 }
4349 
4350 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4351                                     QualType Ty) const {
4352 
4353   bool IsIndirect = false;
4354 
4355   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4356   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4357   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4358     uint64_t Width = getContext().getTypeSize(Ty);
4359     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4360   }
4361 
4362   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4363                           CGF.getContext().getTypeInfoInChars(Ty),
4364                           CharUnits::fromQuantity(8),
4365                           /*allowHigherAlign*/ false);
4366 }
4367 
4368 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4369                                         llvm::Value *Address, bool Is64Bit,
4370                                         bool IsAIX) {
4371   // This is calculated from the LLVM and GCC tables and verified
4372   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4373 
4374   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4375 
4376   llvm::IntegerType *i8 = CGF.Int8Ty;
4377   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4378   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4379   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4380 
4381   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4382   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4383 
4384   // 32-63: fp0-31, the 8-byte floating-point registers
4385   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4386 
4387   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4388   // 64: mq
4389   // 65: lr
4390   // 66: ctr
4391   // 67: ap
4392   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4393 
4394   // 68-76 are various 4-byte special-purpose registers:
4395   // 68-75 cr0-7
4396   // 76: xer
4397   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4398 
4399   // 77-108: v0-31, the 16-byte vector registers
4400   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4401 
4402   // 109: vrsave
4403   // 110: vscr
4404   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4405 
4406   // AIX does not utilize the rest of the registers.
4407   if (IsAIX)
4408     return false;
4409 
4410   // 111: spe_acc
4411   // 112: spefscr
4412   // 113: sfp
4413   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4414 
4415   if (!Is64Bit)
4416     return false;
4417 
4418   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4419   // or above CPU.
4420   // 64-bit only registers:
4421   // 114: tfhar
4422   // 115: tfiar
4423   // 116: texasr
4424   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4425 
4426   return false;
4427 }
4428 
4429 // AIX
4430 namespace {
4431 /// AIXABIInfo - The AIX XCOFF ABI information.
4432 class AIXABIInfo : public ABIInfo {
4433   const bool Is64Bit;
4434   const unsigned PtrByteSize;
4435   CharUnits getParamTypeAlignment(QualType Ty) const;
4436 
4437 public:
4438   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4439       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4440 
4441   bool isPromotableTypeForABI(QualType Ty) const;
4442 
4443   ABIArgInfo classifyReturnType(QualType RetTy) const;
4444   ABIArgInfo classifyArgumentType(QualType Ty) const;
4445 
4446   void computeInfo(CGFunctionInfo &FI) const override {
4447     if (!getCXXABI().classifyReturnType(FI))
4448       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4449 
4450     for (auto &I : FI.arguments())
4451       I.info = classifyArgumentType(I.type);
4452   }
4453 
4454   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4455                     QualType Ty) const override;
4456 };
4457 
4458 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4459   const bool Is64Bit;
4460 
4461 public:
4462   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4463       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4464         Is64Bit(Is64Bit) {}
4465   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4466     return 1; // r1 is the dedicated stack pointer
4467   }
4468 
4469   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4470                                llvm::Value *Address) const override;
4471 };
4472 } // namespace
4473 
4474 // Return true if the ABI requires Ty to be passed sign- or zero-
4475 // extended to 32/64 bits.
4476 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4477   // Treat an enum type as its underlying type.
4478   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4479     Ty = EnumTy->getDecl()->getIntegerType();
4480 
4481   // Promotable integer types are required to be promoted by the ABI.
4482   if (Ty->isPromotableIntegerType())
4483     return true;
4484 
4485   if (!Is64Bit)
4486     return false;
4487 
4488   // For 64 bit mode, in addition to the usual promotable integer types, we also
4489   // need to extend all 32-bit types, since the ABI requires promotion to 64
4490   // bits.
4491   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4492     switch (BT->getKind()) {
4493     case BuiltinType::Int:
4494     case BuiltinType::UInt:
4495       return true;
4496     default:
4497       break;
4498     }
4499 
4500   return false;
4501 }
4502 
4503 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4504   if (RetTy->isAnyComplexType())
4505     return ABIArgInfo::getDirect();
4506 
4507   if (RetTy->isVectorType())
4508     return ABIArgInfo::getDirect();
4509 
4510   if (RetTy->isVoidType())
4511     return ABIArgInfo::getIgnore();
4512 
4513   if (isAggregateTypeForABI(RetTy))
4514     return getNaturalAlignIndirect(RetTy);
4515 
4516   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4517                                         : ABIArgInfo::getDirect());
4518 }
4519 
4520 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4521   Ty = useFirstFieldIfTransparentUnion(Ty);
4522 
4523   if (Ty->isAnyComplexType())
4524     return ABIArgInfo::getDirect();
4525 
4526   if (Ty->isVectorType())
4527     return ABIArgInfo::getDirect();
4528 
4529   if (isAggregateTypeForABI(Ty)) {
4530     // Records with non-trivial destructors/copy-constructors should not be
4531     // passed by value.
4532     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4533       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4534 
4535     CharUnits CCAlign = getParamTypeAlignment(Ty);
4536     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4537 
4538     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4539                                    /*Realign*/ TyAlign > CCAlign);
4540   }
4541 
4542   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4543                                      : ABIArgInfo::getDirect());
4544 }
4545 
4546 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4547   // Complex types are passed just like their elements.
4548   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4549     Ty = CTy->getElementType();
4550 
4551   if (Ty->isVectorType())
4552     return CharUnits::fromQuantity(16);
4553 
4554   // If the structure contains a vector type, the alignment is 16.
4555   if (isRecordWithSIMDVectorType(getContext(), Ty))
4556     return CharUnits::fromQuantity(16);
4557 
4558   return CharUnits::fromQuantity(PtrByteSize);
4559 }
4560 
4561 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4562                               QualType Ty) const {
4563   if (Ty->isAnyComplexType())
4564     llvm::report_fatal_error("complex type is not supported on AIX yet");
4565 
4566   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4567   TypeInfo.Align = getParamTypeAlignment(Ty);
4568 
4569   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4570 
4571   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4572                           SlotSize, /*AllowHigher*/ true);
4573 }
4574 
4575 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4576     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4577   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4578 }
4579 
4580 // PowerPC-32
4581 namespace {
4582 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4583 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4584   bool IsSoftFloatABI;
4585   bool IsRetSmallStructInRegABI;
4586 
4587   CharUnits getParamTypeAlignment(QualType Ty) const;
4588 
4589 public:
4590   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4591                      bool RetSmallStructInRegABI)
4592       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4593         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4594 
4595   ABIArgInfo classifyReturnType(QualType RetTy) const;
4596 
4597   void computeInfo(CGFunctionInfo &FI) const override {
4598     if (!getCXXABI().classifyReturnType(FI))
4599       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4600     for (auto &I : FI.arguments())
4601       I.info = classifyArgumentType(I.type);
4602   }
4603 
4604   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4605                     QualType Ty) const override;
4606 };
4607 
4608 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4609 public:
4610   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4611                          bool RetSmallStructInRegABI)
4612       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4613             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4614 
4615   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4616                                      const CodeGenOptions &Opts);
4617 
4618   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4619     // This is recovered from gcc output.
4620     return 1; // r1 is the dedicated stack pointer
4621   }
4622 
4623   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4624                                llvm::Value *Address) const override;
4625 };
4626 }
4627 
4628 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4629   // Complex types are passed just like their elements.
4630   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4631     Ty = CTy->getElementType();
4632 
4633   if (Ty->isVectorType())
4634     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4635                                                                        : 4);
4636 
4637   // For single-element float/vector structs, we consider the whole type
4638   // to have the same alignment requirements as its single element.
4639   const Type *AlignTy = nullptr;
4640   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4641     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4642     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4643         (BT && BT->isFloatingPoint()))
4644       AlignTy = EltType;
4645   }
4646 
4647   if (AlignTy)
4648     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4649   return CharUnits::fromQuantity(4);
4650 }
4651 
4652 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4653   uint64_t Size;
4654 
4655   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4656   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4657       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4658     // System V ABI (1995), page 3-22, specified:
4659     // > A structure or union whose size is less than or equal to 8 bytes
4660     // > shall be returned in r3 and r4, as if it were first stored in the
4661     // > 8-byte aligned memory area and then the low addressed word were
4662     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4663     // > the last member of the structure or union are not defined.
4664     //
4665     // GCC for big-endian PPC32 inserts the pad before the first member,
4666     // not "beyond the last member" of the struct.  To stay compatible
4667     // with GCC, we coerce the struct to an integer of the same size.
4668     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4669     if (Size == 0)
4670       return ABIArgInfo::getIgnore();
4671     else {
4672       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4673       return ABIArgInfo::getDirect(CoerceTy);
4674     }
4675   }
4676 
4677   return DefaultABIInfo::classifyReturnType(RetTy);
4678 }
4679 
4680 // TODO: this implementation is now likely redundant with
4681 // DefaultABIInfo::EmitVAArg.
4682 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4683                                       QualType Ty) const {
4684   if (getTarget().getTriple().isOSDarwin()) {
4685     auto TI = getContext().getTypeInfoInChars(Ty);
4686     TI.Align = getParamTypeAlignment(Ty);
4687 
4688     CharUnits SlotSize = CharUnits::fromQuantity(4);
4689     return emitVoidPtrVAArg(CGF, VAList, Ty,
4690                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4691                             /*AllowHigherAlign=*/true);
4692   }
4693 
4694   const unsigned OverflowLimit = 8;
4695   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4696     // TODO: Implement this. For now ignore.
4697     (void)CTy;
4698     return Address::invalid(); // FIXME?
4699   }
4700 
4701   // struct __va_list_tag {
4702   //   unsigned char gpr;
4703   //   unsigned char fpr;
4704   //   unsigned short reserved;
4705   //   void *overflow_arg_area;
4706   //   void *reg_save_area;
4707   // };
4708 
4709   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4710   bool isInt = !Ty->isFloatingType();
4711   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4712 
4713   // All aggregates are passed indirectly?  That doesn't seem consistent
4714   // with the argument-lowering code.
4715   bool isIndirect = isAggregateTypeForABI(Ty);
4716 
4717   CGBuilderTy &Builder = CGF.Builder;
4718 
4719   // The calling convention either uses 1-2 GPRs or 1 FPR.
4720   Address NumRegsAddr = Address::invalid();
4721   if (isInt || IsSoftFloatABI) {
4722     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4723   } else {
4724     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4725   }
4726 
4727   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4728 
4729   // "Align" the register count when TY is i64.
4730   if (isI64 || (isF64 && IsSoftFloatABI)) {
4731     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4732     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4733   }
4734 
4735   llvm::Value *CC =
4736       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4737 
4738   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4739   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4740   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4741 
4742   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4743 
4744   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4745   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4746 
4747   // Case 1: consume registers.
4748   Address RegAddr = Address::invalid();
4749   {
4750     CGF.EmitBlock(UsingRegs);
4751 
4752     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4753     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4754                       CharUnits::fromQuantity(8));
4755     assert(RegAddr.getElementType() == CGF.Int8Ty);
4756 
4757     // Floating-point registers start after the general-purpose registers.
4758     if (!(isInt || IsSoftFloatABI)) {
4759       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4760                                                    CharUnits::fromQuantity(32));
4761     }
4762 
4763     // Get the address of the saved value by scaling the number of
4764     // registers we've used by the number of
4765     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4766     llvm::Value *RegOffset =
4767       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4768     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4769                                             RegAddr.getPointer(), RegOffset),
4770                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4771     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4772 
4773     // Increase the used-register count.
4774     NumRegs =
4775       Builder.CreateAdd(NumRegs,
4776                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4777     Builder.CreateStore(NumRegs, NumRegsAddr);
4778 
4779     CGF.EmitBranch(Cont);
4780   }
4781 
4782   // Case 2: consume space in the overflow area.
4783   Address MemAddr = Address::invalid();
4784   {
4785     CGF.EmitBlock(UsingOverflow);
4786 
4787     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4788 
4789     // Everything in the overflow area is rounded up to a size of at least 4.
4790     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4791 
4792     CharUnits Size;
4793     if (!isIndirect) {
4794       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4795       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4796     } else {
4797       Size = CGF.getPointerSize();
4798     }
4799 
4800     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4801     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4802                          OverflowAreaAlign);
4803     // Round up address of argument to alignment
4804     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4805     if (Align > OverflowAreaAlign) {
4806       llvm::Value *Ptr = OverflowArea.getPointer();
4807       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4808                                                            Align);
4809     }
4810 
4811     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4812 
4813     // Increase the overflow area.
4814     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4815     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4816     CGF.EmitBranch(Cont);
4817   }
4818 
4819   CGF.EmitBlock(Cont);
4820 
4821   // Merge the cases with a phi.
4822   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4823                                 "vaarg.addr");
4824 
4825   // Load the pointer if the argument was passed indirectly.
4826   if (isIndirect) {
4827     Result = Address(Builder.CreateLoad(Result, "aggr"),
4828                      getContext().getTypeAlignInChars(Ty));
4829   }
4830 
4831   return Result;
4832 }
4833 
4834 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4835     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4836   assert(Triple.isPPC32());
4837 
4838   switch (Opts.getStructReturnConvention()) {
4839   case CodeGenOptions::SRCK_Default:
4840     break;
4841   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4842     return false;
4843   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4844     return true;
4845   }
4846 
4847   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4848     return true;
4849 
4850   return false;
4851 }
4852 
4853 bool
4854 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4855                                                 llvm::Value *Address) const {
4856   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4857                                      /*IsAIX*/ false);
4858 }
4859 
4860 // PowerPC-64
4861 
4862 namespace {
4863 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4864 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4865 public:
4866   enum ABIKind {
4867     ELFv1 = 0,
4868     ELFv2
4869   };
4870 
4871 private:
4872   static const unsigned GPRBits = 64;
4873   ABIKind Kind;
4874   bool IsSoftFloatABI;
4875 
4876 public:
4877   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4878                      bool SoftFloatABI)
4879       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4880 
4881   bool isPromotableTypeForABI(QualType Ty) const;
4882   CharUnits getParamTypeAlignment(QualType Ty) const;
4883 
4884   ABIArgInfo classifyReturnType(QualType RetTy) const;
4885   ABIArgInfo classifyArgumentType(QualType Ty) const;
4886 
4887   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4888   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4889                                          uint64_t Members) const override;
4890 
4891   // TODO: We can add more logic to computeInfo to improve performance.
4892   // Example: For aggregate arguments that fit in a register, we could
4893   // use getDirectInReg (as is done below for structs containing a single
4894   // floating-point value) to avoid pushing them to memory on function
4895   // entry.  This would require changing the logic in PPCISelLowering
4896   // when lowering the parameters in the caller and args in the callee.
4897   void computeInfo(CGFunctionInfo &FI) const override {
4898     if (!getCXXABI().classifyReturnType(FI))
4899       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4900     for (auto &I : FI.arguments()) {
4901       // We rely on the default argument classification for the most part.
4902       // One exception:  An aggregate containing a single floating-point
4903       // or vector item must be passed in a register if one is available.
4904       const Type *T = isSingleElementStruct(I.type, getContext());
4905       if (T) {
4906         const BuiltinType *BT = T->getAs<BuiltinType>();
4907         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4908             (BT && BT->isFloatingPoint())) {
4909           QualType QT(T, 0);
4910           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4911           continue;
4912         }
4913       }
4914       I.info = classifyArgumentType(I.type);
4915     }
4916   }
4917 
4918   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4919                     QualType Ty) const override;
4920 
4921   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4922                                     bool asReturnValue) const override {
4923     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4924   }
4925 
4926   bool isSwiftErrorInRegister() const override {
4927     return false;
4928   }
4929 };
4930 
4931 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4932 
4933 public:
4934   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4935                                PPC64_SVR4_ABIInfo::ABIKind Kind,
4936                                bool SoftFloatABI)
4937       : TargetCodeGenInfo(
4938             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
4939 
4940   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4941     // This is recovered from gcc output.
4942     return 1; // r1 is the dedicated stack pointer
4943   }
4944 
4945   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4946                                llvm::Value *Address) const override;
4947 };
4948 
4949 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4950 public:
4951   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4952 
4953   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4954     // This is recovered from gcc output.
4955     return 1; // r1 is the dedicated stack pointer
4956   }
4957 
4958   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4959                                llvm::Value *Address) const override;
4960 };
4961 
4962 }
4963 
4964 // Return true if the ABI requires Ty to be passed sign- or zero-
4965 // extended to 64 bits.
4966 bool
4967 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4968   // Treat an enum type as its underlying type.
4969   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4970     Ty = EnumTy->getDecl()->getIntegerType();
4971 
4972   // Promotable integer types are required to be promoted by the ABI.
4973   if (isPromotableIntegerTypeForABI(Ty))
4974     return true;
4975 
4976   // In addition to the usual promotable integer types, we also need to
4977   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4978   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4979     switch (BT->getKind()) {
4980     case BuiltinType::Int:
4981     case BuiltinType::UInt:
4982       return true;
4983     default:
4984       break;
4985     }
4986 
4987   if (const auto *EIT = Ty->getAs<ExtIntType>())
4988     if (EIT->getNumBits() < 64)
4989       return true;
4990 
4991   return false;
4992 }
4993 
4994 /// isAlignedParamType - Determine whether a type requires 16-byte or
4995 /// higher alignment in the parameter area.  Always returns at least 8.
4996 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4997   // Complex types are passed just like their elements.
4998   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4999     Ty = CTy->getElementType();
5000 
5001   // Only vector types of size 16 bytes need alignment (larger types are
5002   // passed via reference, smaller types are not aligned).
5003   if (Ty->isVectorType()) {
5004     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5005   } else if (Ty->isRealFloatingType() &&
5006              &getContext().getFloatTypeSemantics(Ty) ==
5007                  &llvm::APFloat::IEEEquad()) {
5008     // According to ABI document section 'Optional Save Areas': If extended
5009     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5010     // format are supported, map them to a single quadword, quadword aligned.
5011     return CharUnits::fromQuantity(16);
5012   }
5013 
5014   // For single-element float/vector structs, we consider the whole type
5015   // to have the same alignment requirements as its single element.
5016   const Type *AlignAsType = nullptr;
5017   const Type *EltType = isSingleElementStruct(Ty, getContext());
5018   if (EltType) {
5019     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5020     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5021         (BT && BT->isFloatingPoint()))
5022       AlignAsType = EltType;
5023   }
5024 
5025   // Likewise for ELFv2 homogeneous aggregates.
5026   const Type *Base = nullptr;
5027   uint64_t Members = 0;
5028   if (!AlignAsType && Kind == ELFv2 &&
5029       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5030     AlignAsType = Base;
5031 
5032   // With special case aggregates, only vector base types need alignment.
5033   if (AlignAsType) {
5034     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5035   }
5036 
5037   // Otherwise, we only need alignment for any aggregate type that
5038   // has an alignment requirement of >= 16 bytes.
5039   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5040     return CharUnits::fromQuantity(16);
5041   }
5042 
5043   return CharUnits::fromQuantity(8);
5044 }
5045 
5046 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5047 /// aggregate.  Base is set to the base element type, and Members is set
5048 /// to the number of base elements.
5049 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5050                                      uint64_t &Members) const {
5051   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5052     uint64_t NElements = AT->getSize().getZExtValue();
5053     if (NElements == 0)
5054       return false;
5055     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5056       return false;
5057     Members *= NElements;
5058   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5059     const RecordDecl *RD = RT->getDecl();
5060     if (RD->hasFlexibleArrayMember())
5061       return false;
5062 
5063     Members = 0;
5064 
5065     // If this is a C++ record, check the properties of the record such as
5066     // bases and ABI specific restrictions
5067     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5068       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5069         return false;
5070 
5071       for (const auto &I : CXXRD->bases()) {
5072         // Ignore empty records.
5073         if (isEmptyRecord(getContext(), I.getType(), true))
5074           continue;
5075 
5076         uint64_t FldMembers;
5077         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5078           return false;
5079 
5080         Members += FldMembers;
5081       }
5082     }
5083 
5084     for (const auto *FD : RD->fields()) {
5085       // Ignore (non-zero arrays of) empty records.
5086       QualType FT = FD->getType();
5087       while (const ConstantArrayType *AT =
5088              getContext().getAsConstantArrayType(FT)) {
5089         if (AT->getSize().getZExtValue() == 0)
5090           return false;
5091         FT = AT->getElementType();
5092       }
5093       if (isEmptyRecord(getContext(), FT, true))
5094         continue;
5095 
5096       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5097       if (getContext().getLangOpts().CPlusPlus &&
5098           FD->isZeroLengthBitField(getContext()))
5099         continue;
5100 
5101       uint64_t FldMembers;
5102       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5103         return false;
5104 
5105       Members = (RD->isUnion() ?
5106                  std::max(Members, FldMembers) : Members + FldMembers);
5107     }
5108 
5109     if (!Base)
5110       return false;
5111 
5112     // Ensure there is no padding.
5113     if (getContext().getTypeSize(Base) * Members !=
5114         getContext().getTypeSize(Ty))
5115       return false;
5116   } else {
5117     Members = 1;
5118     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5119       Members = 2;
5120       Ty = CT->getElementType();
5121     }
5122 
5123     // Most ABIs only support float, double, and some vector type widths.
5124     if (!isHomogeneousAggregateBaseType(Ty))
5125       return false;
5126 
5127     // The base type must be the same for all members.  Types that
5128     // agree in both total size and mode (float vs. vector) are
5129     // treated as being equivalent here.
5130     const Type *TyPtr = Ty.getTypePtr();
5131     if (!Base) {
5132       Base = TyPtr;
5133       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5134       // so make sure to widen it explicitly.
5135       if (const VectorType *VT = Base->getAs<VectorType>()) {
5136         QualType EltTy = VT->getElementType();
5137         unsigned NumElements =
5138             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5139         Base = getContext()
5140                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5141                    .getTypePtr();
5142       }
5143     }
5144 
5145     if (Base->isVectorType() != TyPtr->isVectorType() ||
5146         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5147       return false;
5148   }
5149   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5150 }
5151 
5152 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5153   // Homogeneous aggregates for ELFv2 must have base types of float,
5154   // double, long double, or 128-bit vectors.
5155   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5156     if (BT->getKind() == BuiltinType::Float ||
5157         BT->getKind() == BuiltinType::Double ||
5158         BT->getKind() == BuiltinType::LongDouble ||
5159         (getContext().getTargetInfo().hasFloat128Type() &&
5160           (BT->getKind() == BuiltinType::Float128))) {
5161       if (IsSoftFloatABI)
5162         return false;
5163       return true;
5164     }
5165   }
5166   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5167     if (getContext().getTypeSize(VT) == 128)
5168       return true;
5169   }
5170   return false;
5171 }
5172 
5173 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5174     const Type *Base, uint64_t Members) const {
5175   // Vector and fp128 types require one register, other floating point types
5176   // require one or two registers depending on their size.
5177   uint32_t NumRegs =
5178       ((getContext().getTargetInfo().hasFloat128Type() &&
5179           Base->isFloat128Type()) ||
5180         Base->isVectorType()) ? 1
5181                               : (getContext().getTypeSize(Base) + 63) / 64;
5182 
5183   // Homogeneous Aggregates may occupy at most 8 registers.
5184   return Members * NumRegs <= 8;
5185 }
5186 
5187 ABIArgInfo
5188 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5189   Ty = useFirstFieldIfTransparentUnion(Ty);
5190 
5191   if (Ty->isAnyComplexType())
5192     return ABIArgInfo::getDirect();
5193 
5194   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5195   // or via reference (larger than 16 bytes).
5196   if (Ty->isVectorType()) {
5197     uint64_t Size = getContext().getTypeSize(Ty);
5198     if (Size > 128)
5199       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5200     else if (Size < 128) {
5201       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5202       return ABIArgInfo::getDirect(CoerceTy);
5203     }
5204   }
5205 
5206   if (const auto *EIT = Ty->getAs<ExtIntType>())
5207     if (EIT->getNumBits() > 128)
5208       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5209 
5210   if (isAggregateTypeForABI(Ty)) {
5211     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5212       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5213 
5214     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5215     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5216 
5217     // ELFv2 homogeneous aggregates are passed as array types.
5218     const Type *Base = nullptr;
5219     uint64_t Members = 0;
5220     if (Kind == ELFv2 &&
5221         isHomogeneousAggregate(Ty, Base, Members)) {
5222       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5223       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5224       return ABIArgInfo::getDirect(CoerceTy);
5225     }
5226 
5227     // If an aggregate may end up fully in registers, we do not
5228     // use the ByVal method, but pass the aggregate as array.
5229     // This is usually beneficial since we avoid forcing the
5230     // back-end to store the argument to memory.
5231     uint64_t Bits = getContext().getTypeSize(Ty);
5232     if (Bits > 0 && Bits <= 8 * GPRBits) {
5233       llvm::Type *CoerceTy;
5234 
5235       // Types up to 8 bytes are passed as integer type (which will be
5236       // properly aligned in the argument save area doubleword).
5237       if (Bits <= GPRBits)
5238         CoerceTy =
5239             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5240       // Larger types are passed as arrays, with the base type selected
5241       // according to the required alignment in the save area.
5242       else {
5243         uint64_t RegBits = ABIAlign * 8;
5244         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5245         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5246         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5247       }
5248 
5249       return ABIArgInfo::getDirect(CoerceTy);
5250     }
5251 
5252     // All other aggregates are passed ByVal.
5253     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5254                                    /*ByVal=*/true,
5255                                    /*Realign=*/TyAlign > ABIAlign);
5256   }
5257 
5258   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5259                                      : ABIArgInfo::getDirect());
5260 }
5261 
5262 ABIArgInfo
5263 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5264   if (RetTy->isVoidType())
5265     return ABIArgInfo::getIgnore();
5266 
5267   if (RetTy->isAnyComplexType())
5268     return ABIArgInfo::getDirect();
5269 
5270   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5271   // or via reference (larger than 16 bytes).
5272   if (RetTy->isVectorType()) {
5273     uint64_t Size = getContext().getTypeSize(RetTy);
5274     if (Size > 128)
5275       return getNaturalAlignIndirect(RetTy);
5276     else if (Size < 128) {
5277       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5278       return ABIArgInfo::getDirect(CoerceTy);
5279     }
5280   }
5281 
5282   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5283     if (EIT->getNumBits() > 128)
5284       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5285 
5286   if (isAggregateTypeForABI(RetTy)) {
5287     // ELFv2 homogeneous aggregates are returned as array types.
5288     const Type *Base = nullptr;
5289     uint64_t Members = 0;
5290     if (Kind == ELFv2 &&
5291         isHomogeneousAggregate(RetTy, Base, Members)) {
5292       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5293       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5294       return ABIArgInfo::getDirect(CoerceTy);
5295     }
5296 
5297     // ELFv2 small aggregates are returned in up to two registers.
5298     uint64_t Bits = getContext().getTypeSize(RetTy);
5299     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5300       if (Bits == 0)
5301         return ABIArgInfo::getIgnore();
5302 
5303       llvm::Type *CoerceTy;
5304       if (Bits > GPRBits) {
5305         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5306         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5307       } else
5308         CoerceTy =
5309             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5310       return ABIArgInfo::getDirect(CoerceTy);
5311     }
5312 
5313     // All other aggregates are returned indirectly.
5314     return getNaturalAlignIndirect(RetTy);
5315   }
5316 
5317   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5318                                         : ABIArgInfo::getDirect());
5319 }
5320 
5321 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5322 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5323                                       QualType Ty) const {
5324   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5325   TypeInfo.Align = getParamTypeAlignment(Ty);
5326 
5327   CharUnits SlotSize = CharUnits::fromQuantity(8);
5328 
5329   // If we have a complex type and the base type is smaller than 8 bytes,
5330   // the ABI calls for the real and imaginary parts to be right-adjusted
5331   // in separate doublewords.  However, Clang expects us to produce a
5332   // pointer to a structure with the two parts packed tightly.  So generate
5333   // loads of the real and imaginary parts relative to the va_list pointer,
5334   // and store them to a temporary structure.
5335   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5336     CharUnits EltSize = TypeInfo.Width / 2;
5337     if (EltSize < SlotSize) {
5338       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5339                                             SlotSize * 2, SlotSize,
5340                                             SlotSize, /*AllowHigher*/ true);
5341 
5342       Address RealAddr = Addr;
5343       Address ImagAddr = RealAddr;
5344       if (CGF.CGM.getDataLayout().isBigEndian()) {
5345         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5346                                                           SlotSize - EltSize);
5347         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5348                                                       2 * SlotSize - EltSize);
5349       } else {
5350         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5351       }
5352 
5353       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5354       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5355       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5356       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5357       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5358 
5359       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5360       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5361                              /*init*/ true);
5362       return Temp;
5363     }
5364   }
5365 
5366   // Otherwise, just use the general rule.
5367   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5368                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5369 }
5370 
5371 bool
5372 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5373   CodeGen::CodeGenFunction &CGF,
5374   llvm::Value *Address) const {
5375   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5376                                      /*IsAIX*/ false);
5377 }
5378 
5379 bool
5380 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5381                                                 llvm::Value *Address) const {
5382   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5383                                      /*IsAIX*/ false);
5384 }
5385 
5386 //===----------------------------------------------------------------------===//
5387 // AArch64 ABI Implementation
5388 //===----------------------------------------------------------------------===//
5389 
5390 namespace {
5391 
5392 class AArch64ABIInfo : public SwiftABIInfo {
5393 public:
5394   enum ABIKind {
5395     AAPCS = 0,
5396     DarwinPCS,
5397     Win64
5398   };
5399 
5400 private:
5401   ABIKind Kind;
5402 
5403 public:
5404   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5405     : SwiftABIInfo(CGT), Kind(Kind) {}
5406 
5407 private:
5408   ABIKind getABIKind() const { return Kind; }
5409   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5410 
5411   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5412   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5413   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5414   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5415   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5416                                          uint64_t Members) const override;
5417 
5418   bool isIllegalVectorType(QualType Ty) const;
5419 
5420   void computeInfo(CGFunctionInfo &FI) const override {
5421     if (!::classifyReturnType(getCXXABI(), FI, *this))
5422       FI.getReturnInfo() =
5423           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5424 
5425     for (auto &it : FI.arguments())
5426       it.info = classifyArgumentType(it.type);
5427   }
5428 
5429   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5430                           CodeGenFunction &CGF) const;
5431 
5432   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5433                          CodeGenFunction &CGF) const;
5434 
5435   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5436                     QualType Ty) const override {
5437     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5438     if (isa<llvm::ScalableVectorType>(BaseTy))
5439       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5440                                "currently not supported");
5441 
5442     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5443                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5444                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5445   }
5446 
5447   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5448                       QualType Ty) const override;
5449 
5450   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5451                                     bool asReturnValue) const override {
5452     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5453   }
5454   bool isSwiftErrorInRegister() const override {
5455     return true;
5456   }
5457 
5458   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5459                                  unsigned elts) const override;
5460 
5461   bool allowBFloatArgsAndRet() const override {
5462     return getTarget().hasBFloat16Type();
5463   }
5464 };
5465 
5466 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5467 public:
5468   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5469       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5470 
5471   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5472     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5473   }
5474 
5475   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5476     return 31;
5477   }
5478 
5479   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5480 
5481   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5482                            CodeGen::CodeGenModule &CGM) const override {
5483     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5484     if (!FD)
5485       return;
5486 
5487     const auto *TA = FD->getAttr<TargetAttr>();
5488     if (TA == nullptr)
5489       return;
5490 
5491     ParsedTargetAttr Attr = TA->parse();
5492     if (Attr.BranchProtection.empty())
5493       return;
5494 
5495     TargetInfo::BranchProtectionInfo BPI;
5496     StringRef Error;
5497     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5498                                                    BPI, Error);
5499     assert(Error.empty());
5500 
5501     auto *Fn = cast<llvm::Function>(GV);
5502     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5503     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5504 
5505     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5506       Fn->addFnAttr("sign-return-address-key",
5507                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5508                         ? "a_key"
5509                         : "b_key");
5510     }
5511 
5512     Fn->addFnAttr("branch-target-enforcement",
5513                   BPI.BranchTargetEnforcement ? "true" : "false");
5514   }
5515 };
5516 
5517 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5518 public:
5519   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5520       : AArch64TargetCodeGenInfo(CGT, K) {}
5521 
5522   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5523                            CodeGen::CodeGenModule &CGM) const override;
5524 
5525   void getDependentLibraryOption(llvm::StringRef Lib,
5526                                  llvm::SmallString<24> &Opt) const override {
5527     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5528   }
5529 
5530   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5531                                llvm::SmallString<32> &Opt) const override {
5532     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5533   }
5534 };
5535 
5536 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5537     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5538   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5539   if (GV->isDeclaration())
5540     return;
5541   addStackProbeTargetAttributes(D, GV, CGM);
5542 }
5543 }
5544 
5545 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5546   assert(Ty->isVectorType() && "expected vector type!");
5547 
5548   const auto *VT = Ty->castAs<VectorType>();
5549   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5550     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5551     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5552                BuiltinType::UChar &&
5553            "unexpected builtin type for SVE predicate!");
5554     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5555         llvm::Type::getInt1Ty(getVMContext()), 16));
5556   }
5557 
5558   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5559     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5560 
5561     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5562     llvm::ScalableVectorType *ResType = nullptr;
5563     switch (BT->getKind()) {
5564     default:
5565       llvm_unreachable("unexpected builtin type for SVE vector!");
5566     case BuiltinType::SChar:
5567     case BuiltinType::UChar:
5568       ResType = llvm::ScalableVectorType::get(
5569           llvm::Type::getInt8Ty(getVMContext()), 16);
5570       break;
5571     case BuiltinType::Short:
5572     case BuiltinType::UShort:
5573       ResType = llvm::ScalableVectorType::get(
5574           llvm::Type::getInt16Ty(getVMContext()), 8);
5575       break;
5576     case BuiltinType::Int:
5577     case BuiltinType::UInt:
5578       ResType = llvm::ScalableVectorType::get(
5579           llvm::Type::getInt32Ty(getVMContext()), 4);
5580       break;
5581     case BuiltinType::Long:
5582     case BuiltinType::ULong:
5583       ResType = llvm::ScalableVectorType::get(
5584           llvm::Type::getInt64Ty(getVMContext()), 2);
5585       break;
5586     case BuiltinType::Half:
5587       ResType = llvm::ScalableVectorType::get(
5588           llvm::Type::getHalfTy(getVMContext()), 8);
5589       break;
5590     case BuiltinType::Float:
5591       ResType = llvm::ScalableVectorType::get(
5592           llvm::Type::getFloatTy(getVMContext()), 4);
5593       break;
5594     case BuiltinType::Double:
5595       ResType = llvm::ScalableVectorType::get(
5596           llvm::Type::getDoubleTy(getVMContext()), 2);
5597       break;
5598     case BuiltinType::BFloat16:
5599       ResType = llvm::ScalableVectorType::get(
5600           llvm::Type::getBFloatTy(getVMContext()), 8);
5601       break;
5602     }
5603     return ABIArgInfo::getDirect(ResType);
5604   }
5605 
5606   uint64_t Size = getContext().getTypeSize(Ty);
5607   // Android promotes <2 x i8> to i16, not i32
5608   if (isAndroid() && (Size <= 16)) {
5609     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5610     return ABIArgInfo::getDirect(ResType);
5611   }
5612   if (Size <= 32) {
5613     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5614     return ABIArgInfo::getDirect(ResType);
5615   }
5616   if (Size == 64) {
5617     auto *ResType =
5618         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5619     return ABIArgInfo::getDirect(ResType);
5620   }
5621   if (Size == 128) {
5622     auto *ResType =
5623         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5624     return ABIArgInfo::getDirect(ResType);
5625   }
5626   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5627 }
5628 
5629 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5630   Ty = useFirstFieldIfTransparentUnion(Ty);
5631 
5632   // Handle illegal vector types here.
5633   if (isIllegalVectorType(Ty))
5634     return coerceIllegalVector(Ty);
5635 
5636   if (!isAggregateTypeForABI(Ty)) {
5637     // Treat an enum type as its underlying type.
5638     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5639       Ty = EnumTy->getDecl()->getIntegerType();
5640 
5641     if (const auto *EIT = Ty->getAs<ExtIntType>())
5642       if (EIT->getNumBits() > 128)
5643         return getNaturalAlignIndirect(Ty);
5644 
5645     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5646                 ? ABIArgInfo::getExtend(Ty)
5647                 : ABIArgInfo::getDirect());
5648   }
5649 
5650   // Structures with either a non-trivial destructor or a non-trivial
5651   // copy constructor are always indirect.
5652   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5653     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5654                                      CGCXXABI::RAA_DirectInMemory);
5655   }
5656 
5657   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5658   // elsewhere for GNU compatibility.
5659   uint64_t Size = getContext().getTypeSize(Ty);
5660   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5661   if (IsEmpty || Size == 0) {
5662     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5663       return ABIArgInfo::getIgnore();
5664 
5665     // GNU C mode. The only argument that gets ignored is an empty one with size
5666     // 0.
5667     if (IsEmpty && Size == 0)
5668       return ABIArgInfo::getIgnore();
5669     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5670   }
5671 
5672   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5673   const Type *Base = nullptr;
5674   uint64_t Members = 0;
5675   if (isHomogeneousAggregate(Ty, Base, Members)) {
5676     return ABIArgInfo::getDirect(
5677         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5678   }
5679 
5680   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5681   if (Size <= 128) {
5682     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5683     // same size and alignment.
5684     if (getTarget().isRenderScriptTarget()) {
5685       return coerceToIntArray(Ty, getContext(), getVMContext());
5686     }
5687     unsigned Alignment;
5688     if (Kind == AArch64ABIInfo::AAPCS) {
5689       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5690       Alignment = Alignment < 128 ? 64 : 128;
5691     } else {
5692       Alignment = std::max(getContext().getTypeAlign(Ty),
5693                            (unsigned)getTarget().getPointerWidth(0));
5694     }
5695     Size = llvm::alignTo(Size, Alignment);
5696 
5697     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5698     // For aggregates with 16-byte alignment, we use i128.
5699     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5700     return ABIArgInfo::getDirect(
5701         Size == Alignment ? BaseTy
5702                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5703   }
5704 
5705   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5706 }
5707 
5708 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5709                                               bool IsVariadic) const {
5710   if (RetTy->isVoidType())
5711     return ABIArgInfo::getIgnore();
5712 
5713   if (const auto *VT = RetTy->getAs<VectorType>()) {
5714     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5715         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5716       return coerceIllegalVector(RetTy);
5717   }
5718 
5719   // Large vector types should be returned via memory.
5720   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5721     return getNaturalAlignIndirect(RetTy);
5722 
5723   if (!isAggregateTypeForABI(RetTy)) {
5724     // Treat an enum type as its underlying type.
5725     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5726       RetTy = EnumTy->getDecl()->getIntegerType();
5727 
5728     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5729       if (EIT->getNumBits() > 128)
5730         return getNaturalAlignIndirect(RetTy);
5731 
5732     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5733                 ? ABIArgInfo::getExtend(RetTy)
5734                 : ABIArgInfo::getDirect());
5735   }
5736 
5737   uint64_t Size = getContext().getTypeSize(RetTy);
5738   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5739     return ABIArgInfo::getIgnore();
5740 
5741   const Type *Base = nullptr;
5742   uint64_t Members = 0;
5743   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5744       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5745         IsVariadic))
5746     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5747     return ABIArgInfo::getDirect();
5748 
5749   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5750   if (Size <= 128) {
5751     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5752     // same size and alignment.
5753     if (getTarget().isRenderScriptTarget()) {
5754       return coerceToIntArray(RetTy, getContext(), getVMContext());
5755     }
5756     unsigned Alignment = getContext().getTypeAlign(RetTy);
5757     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5758 
5759     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5760     // For aggregates with 16-byte alignment, we use i128.
5761     if (Alignment < 128 && Size == 128) {
5762       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5763       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5764     }
5765     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5766   }
5767 
5768   return getNaturalAlignIndirect(RetTy);
5769 }
5770 
5771 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5772 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5773   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5774     // Check whether VT is a fixed-length SVE vector. These types are
5775     // represented as scalable vectors in function args/return and must be
5776     // coerced from fixed vectors.
5777     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5778         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5779       return true;
5780 
5781     // Check whether VT is legal.
5782     unsigned NumElements = VT->getNumElements();
5783     uint64_t Size = getContext().getTypeSize(VT);
5784     // NumElements should be power of 2.
5785     if (!llvm::isPowerOf2_32(NumElements))
5786       return true;
5787 
5788     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5789     // vectors for some reason.
5790     llvm::Triple Triple = getTarget().getTriple();
5791     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5792         Triple.isOSBinFormatMachO())
5793       return Size <= 32;
5794 
5795     return Size != 64 && (Size != 128 || NumElements == 1);
5796   }
5797   return false;
5798 }
5799 
5800 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5801                                                llvm::Type *eltTy,
5802                                                unsigned elts) const {
5803   if (!llvm::isPowerOf2_32(elts))
5804     return false;
5805   if (totalSize.getQuantity() != 8 &&
5806       (totalSize.getQuantity() != 16 || elts == 1))
5807     return false;
5808   return true;
5809 }
5810 
5811 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5812   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5813   // point type or a short-vector type. This is the same as the 32-bit ABI,
5814   // but with the difference that any floating-point type is allowed,
5815   // including __fp16.
5816   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5817     if (BT->isFloatingPoint())
5818       return true;
5819   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5820     unsigned VecSize = getContext().getTypeSize(VT);
5821     if (VecSize == 64 || VecSize == 128)
5822       return true;
5823   }
5824   return false;
5825 }
5826 
5827 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5828                                                        uint64_t Members) const {
5829   return Members <= 4;
5830 }
5831 
5832 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5833                                             QualType Ty,
5834                                             CodeGenFunction &CGF) const {
5835   ABIArgInfo AI = classifyArgumentType(Ty);
5836   bool IsIndirect = AI.isIndirect();
5837 
5838   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5839   if (IsIndirect)
5840     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5841   else if (AI.getCoerceToType())
5842     BaseTy = AI.getCoerceToType();
5843 
5844   unsigned NumRegs = 1;
5845   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5846     BaseTy = ArrTy->getElementType();
5847     NumRegs = ArrTy->getNumElements();
5848   }
5849   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5850 
5851   // The AArch64 va_list type and handling is specified in the Procedure Call
5852   // Standard, section B.4:
5853   //
5854   // struct {
5855   //   void *__stack;
5856   //   void *__gr_top;
5857   //   void *__vr_top;
5858   //   int __gr_offs;
5859   //   int __vr_offs;
5860   // };
5861 
5862   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5863   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5864   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5865   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5866 
5867   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5868   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5869 
5870   Address reg_offs_p = Address::invalid();
5871   llvm::Value *reg_offs = nullptr;
5872   int reg_top_index;
5873   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5874   if (!IsFPR) {
5875     // 3 is the field number of __gr_offs
5876     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5877     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5878     reg_top_index = 1; // field number for __gr_top
5879     RegSize = llvm::alignTo(RegSize, 8);
5880   } else {
5881     // 4 is the field number of __vr_offs.
5882     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5883     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5884     reg_top_index = 2; // field number for __vr_top
5885     RegSize = 16 * NumRegs;
5886   }
5887 
5888   //=======================================
5889   // Find out where argument was passed
5890   //=======================================
5891 
5892   // If reg_offs >= 0 we're already using the stack for this type of
5893   // argument. We don't want to keep updating reg_offs (in case it overflows,
5894   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5895   // whatever they get).
5896   llvm::Value *UsingStack = nullptr;
5897   UsingStack = CGF.Builder.CreateICmpSGE(
5898       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5899 
5900   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5901 
5902   // Otherwise, at least some kind of argument could go in these registers, the
5903   // question is whether this particular type is too big.
5904   CGF.EmitBlock(MaybeRegBlock);
5905 
5906   // Integer arguments may need to correct register alignment (for example a
5907   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5908   // align __gr_offs to calculate the potential address.
5909   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5910     int Align = TyAlign.getQuantity();
5911 
5912     reg_offs = CGF.Builder.CreateAdd(
5913         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5914         "align_regoffs");
5915     reg_offs = CGF.Builder.CreateAnd(
5916         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5917         "aligned_regoffs");
5918   }
5919 
5920   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5921   // The fact that this is done unconditionally reflects the fact that
5922   // allocating an argument to the stack also uses up all the remaining
5923   // registers of the appropriate kind.
5924   llvm::Value *NewOffset = nullptr;
5925   NewOffset = CGF.Builder.CreateAdd(
5926       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5927   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5928 
5929   // Now we're in a position to decide whether this argument really was in
5930   // registers or not.
5931   llvm::Value *InRegs = nullptr;
5932   InRegs = CGF.Builder.CreateICmpSLE(
5933       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5934 
5935   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5936 
5937   //=======================================
5938   // Argument was in registers
5939   //=======================================
5940 
5941   // Now we emit the code for if the argument was originally passed in
5942   // registers. First start the appropriate block:
5943   CGF.EmitBlock(InRegBlock);
5944 
5945   llvm::Value *reg_top = nullptr;
5946   Address reg_top_p =
5947       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5948   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5949   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5950                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5951   Address RegAddr = Address::invalid();
5952   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5953 
5954   if (IsIndirect) {
5955     // If it's been passed indirectly (actually a struct), whatever we find from
5956     // stored registers or on the stack will actually be a struct **.
5957     MemTy = llvm::PointerType::getUnqual(MemTy);
5958   }
5959 
5960   const Type *Base = nullptr;
5961   uint64_t NumMembers = 0;
5962   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5963   if (IsHFA && NumMembers > 1) {
5964     // Homogeneous aggregates passed in registers will have their elements split
5965     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5966     // qN+1, ...). We reload and store into a temporary local variable
5967     // contiguously.
5968     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5969     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5970     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5971     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5972     Address Tmp = CGF.CreateTempAlloca(HFATy,
5973                                        std::max(TyAlign, BaseTyInfo.Align));
5974 
5975     // On big-endian platforms, the value will be right-aligned in its slot.
5976     int Offset = 0;
5977     if (CGF.CGM.getDataLayout().isBigEndian() &&
5978         BaseTyInfo.Width.getQuantity() < 16)
5979       Offset = 16 - BaseTyInfo.Width.getQuantity();
5980 
5981     for (unsigned i = 0; i < NumMembers; ++i) {
5982       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5983       Address LoadAddr =
5984         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5985       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5986 
5987       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5988 
5989       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5990       CGF.Builder.CreateStore(Elem, StoreAddr);
5991     }
5992 
5993     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5994   } else {
5995     // Otherwise the object is contiguous in memory.
5996 
5997     // It might be right-aligned in its slot.
5998     CharUnits SlotSize = BaseAddr.getAlignment();
5999     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6000         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6001         TySize < SlotSize) {
6002       CharUnits Offset = SlotSize - TySize;
6003       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6004     }
6005 
6006     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6007   }
6008 
6009   CGF.EmitBranch(ContBlock);
6010 
6011   //=======================================
6012   // Argument was on the stack
6013   //=======================================
6014   CGF.EmitBlock(OnStackBlock);
6015 
6016   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6017   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6018 
6019   // Again, stack arguments may need realignment. In this case both integer and
6020   // floating-point ones might be affected.
6021   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6022     int Align = TyAlign.getQuantity();
6023 
6024     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6025 
6026     OnStackPtr = CGF.Builder.CreateAdd(
6027         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6028         "align_stack");
6029     OnStackPtr = CGF.Builder.CreateAnd(
6030         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6031         "align_stack");
6032 
6033     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6034   }
6035   Address OnStackAddr(OnStackPtr,
6036                       std::max(CharUnits::fromQuantity(8), TyAlign));
6037 
6038   // All stack slots are multiples of 8 bytes.
6039   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6040   CharUnits StackSize;
6041   if (IsIndirect)
6042     StackSize = StackSlotSize;
6043   else
6044     StackSize = TySize.alignTo(StackSlotSize);
6045 
6046   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6047   llvm::Value *NewStack =
6048       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6049 
6050   // Write the new value of __stack for the next call to va_arg
6051   CGF.Builder.CreateStore(NewStack, stack_p);
6052 
6053   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6054       TySize < StackSlotSize) {
6055     CharUnits Offset = StackSlotSize - TySize;
6056     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6057   }
6058 
6059   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6060 
6061   CGF.EmitBranch(ContBlock);
6062 
6063   //=======================================
6064   // Tidy up
6065   //=======================================
6066   CGF.EmitBlock(ContBlock);
6067 
6068   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6069                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6070 
6071   if (IsIndirect)
6072     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6073                    TyAlign);
6074 
6075   return ResAddr;
6076 }
6077 
6078 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6079                                         CodeGenFunction &CGF) const {
6080   // The backend's lowering doesn't support va_arg for aggregates or
6081   // illegal vector types.  Lower VAArg here for these cases and use
6082   // the LLVM va_arg instruction for everything else.
6083   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6084     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6085 
6086   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6087   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6088 
6089   // Empty records are ignored for parameter passing purposes.
6090   if (isEmptyRecord(getContext(), Ty, true)) {
6091     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6092     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6093     return Addr;
6094   }
6095 
6096   // The size of the actual thing passed, which might end up just
6097   // being a pointer for indirect types.
6098   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6099 
6100   // Arguments bigger than 16 bytes which aren't homogeneous
6101   // aggregates should be passed indirectly.
6102   bool IsIndirect = false;
6103   if (TyInfo.Width.getQuantity() > 16) {
6104     const Type *Base = nullptr;
6105     uint64_t Members = 0;
6106     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6107   }
6108 
6109   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6110                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6111 }
6112 
6113 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6114                                     QualType Ty) const {
6115   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6116                           CGF.getContext().getTypeInfoInChars(Ty),
6117                           CharUnits::fromQuantity(8),
6118                           /*allowHigherAlign*/ false);
6119 }
6120 
6121 //===----------------------------------------------------------------------===//
6122 // ARM ABI Implementation
6123 //===----------------------------------------------------------------------===//
6124 
6125 namespace {
6126 
6127 class ARMABIInfo : public SwiftABIInfo {
6128 public:
6129   enum ABIKind {
6130     APCS = 0,
6131     AAPCS = 1,
6132     AAPCS_VFP = 2,
6133     AAPCS16_VFP = 3,
6134   };
6135 
6136 private:
6137   ABIKind Kind;
6138   bool IsFloatABISoftFP;
6139 
6140 public:
6141   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6142       : SwiftABIInfo(CGT), Kind(_Kind) {
6143     setCCs();
6144     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6145         CGT.getCodeGenOpts().FloatABI == ""; // default
6146   }
6147 
6148   bool isEABI() const {
6149     switch (getTarget().getTriple().getEnvironment()) {
6150     case llvm::Triple::Android:
6151     case llvm::Triple::EABI:
6152     case llvm::Triple::EABIHF:
6153     case llvm::Triple::GNUEABI:
6154     case llvm::Triple::GNUEABIHF:
6155     case llvm::Triple::MuslEABI:
6156     case llvm::Triple::MuslEABIHF:
6157       return true;
6158     default:
6159       return false;
6160     }
6161   }
6162 
6163   bool isEABIHF() const {
6164     switch (getTarget().getTriple().getEnvironment()) {
6165     case llvm::Triple::EABIHF:
6166     case llvm::Triple::GNUEABIHF:
6167     case llvm::Triple::MuslEABIHF:
6168       return true;
6169     default:
6170       return false;
6171     }
6172   }
6173 
6174   ABIKind getABIKind() const { return Kind; }
6175 
6176   bool allowBFloatArgsAndRet() const override {
6177     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6178   }
6179 
6180 private:
6181   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6182                                 unsigned functionCallConv) const;
6183   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6184                                   unsigned functionCallConv) const;
6185   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6186                                           uint64_t Members) const;
6187   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6188   bool isIllegalVectorType(QualType Ty) const;
6189   bool containsAnyFP16Vectors(QualType Ty) const;
6190 
6191   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6192   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6193                                          uint64_t Members) const override;
6194 
6195   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6196 
6197   void computeInfo(CGFunctionInfo &FI) const override;
6198 
6199   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6200                     QualType Ty) const override;
6201 
6202   llvm::CallingConv::ID getLLVMDefaultCC() const;
6203   llvm::CallingConv::ID getABIDefaultCC() const;
6204   void setCCs();
6205 
6206   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6207                                     bool asReturnValue) const override {
6208     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6209   }
6210   bool isSwiftErrorInRegister() const override {
6211     return true;
6212   }
6213   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6214                                  unsigned elts) const override;
6215 };
6216 
6217 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6218 public:
6219   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6220       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6221 
6222   const ARMABIInfo &getABIInfo() const {
6223     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6224   }
6225 
6226   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6227     return 13;
6228   }
6229 
6230   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6231     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6232   }
6233 
6234   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6235                                llvm::Value *Address) const override {
6236     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6237 
6238     // 0-15 are the 16 integer registers.
6239     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6240     return false;
6241   }
6242 
6243   unsigned getSizeOfUnwindException() const override {
6244     if (getABIInfo().isEABI()) return 88;
6245     return TargetCodeGenInfo::getSizeOfUnwindException();
6246   }
6247 
6248   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6249                            CodeGen::CodeGenModule &CGM) const override {
6250     if (GV->isDeclaration())
6251       return;
6252     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6253     if (!FD)
6254       return;
6255 
6256     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6257     if (!Attr)
6258       return;
6259 
6260     const char *Kind;
6261     switch (Attr->getInterrupt()) {
6262     case ARMInterruptAttr::Generic: Kind = ""; break;
6263     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6264     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6265     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6266     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6267     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6268     }
6269 
6270     llvm::Function *Fn = cast<llvm::Function>(GV);
6271 
6272     Fn->addFnAttr("interrupt", Kind);
6273 
6274     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6275     if (ABI == ARMABIInfo::APCS)
6276       return;
6277 
6278     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6279     // however this is not necessarily true on taking any interrupt. Instruct
6280     // the backend to perform a realignment as part of the function prologue.
6281     llvm::AttrBuilder B;
6282     B.addStackAlignmentAttr(8);
6283     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6284   }
6285 };
6286 
6287 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6288 public:
6289   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6290       : ARMTargetCodeGenInfo(CGT, K) {}
6291 
6292   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6293                            CodeGen::CodeGenModule &CGM) const override;
6294 
6295   void getDependentLibraryOption(llvm::StringRef Lib,
6296                                  llvm::SmallString<24> &Opt) const override {
6297     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6298   }
6299 
6300   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6301                                llvm::SmallString<32> &Opt) const override {
6302     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6303   }
6304 };
6305 
6306 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6307     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6308   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6309   if (GV->isDeclaration())
6310     return;
6311   addStackProbeTargetAttributes(D, GV, CGM);
6312 }
6313 }
6314 
6315 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6316   if (!::classifyReturnType(getCXXABI(), FI, *this))
6317     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6318                                             FI.getCallingConvention());
6319 
6320   for (auto &I : FI.arguments())
6321     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6322                                   FI.getCallingConvention());
6323 
6324 
6325   // Always honor user-specified calling convention.
6326   if (FI.getCallingConvention() != llvm::CallingConv::C)
6327     return;
6328 
6329   llvm::CallingConv::ID cc = getRuntimeCC();
6330   if (cc != llvm::CallingConv::C)
6331     FI.setEffectiveCallingConvention(cc);
6332 }
6333 
6334 /// Return the default calling convention that LLVM will use.
6335 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6336   // The default calling convention that LLVM will infer.
6337   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6338     return llvm::CallingConv::ARM_AAPCS_VFP;
6339   else if (isEABI())
6340     return llvm::CallingConv::ARM_AAPCS;
6341   else
6342     return llvm::CallingConv::ARM_APCS;
6343 }
6344 
6345 /// Return the calling convention that our ABI would like us to use
6346 /// as the C calling convention.
6347 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6348   switch (getABIKind()) {
6349   case APCS: return llvm::CallingConv::ARM_APCS;
6350   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6351   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6352   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6353   }
6354   llvm_unreachable("bad ABI kind");
6355 }
6356 
6357 void ARMABIInfo::setCCs() {
6358   assert(getRuntimeCC() == llvm::CallingConv::C);
6359 
6360   // Don't muddy up the IR with a ton of explicit annotations if
6361   // they'd just match what LLVM will infer from the triple.
6362   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6363   if (abiCC != getLLVMDefaultCC())
6364     RuntimeCC = abiCC;
6365 }
6366 
6367 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6368   uint64_t Size = getContext().getTypeSize(Ty);
6369   if (Size <= 32) {
6370     llvm::Type *ResType =
6371         llvm::Type::getInt32Ty(getVMContext());
6372     return ABIArgInfo::getDirect(ResType);
6373   }
6374   if (Size == 64 || Size == 128) {
6375     auto *ResType = llvm::FixedVectorType::get(
6376         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6377     return ABIArgInfo::getDirect(ResType);
6378   }
6379   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6380 }
6381 
6382 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6383                                                     const Type *Base,
6384                                                     uint64_t Members) const {
6385   assert(Base && "Base class should be set for homogeneous aggregate");
6386   // Base can be a floating-point or a vector.
6387   if (const VectorType *VT = Base->getAs<VectorType>()) {
6388     // FP16 vectors should be converted to integer vectors
6389     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6390       uint64_t Size = getContext().getTypeSize(VT);
6391       auto *NewVecTy = llvm::FixedVectorType::get(
6392           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6393       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6394       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6395     }
6396   }
6397   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6398 }
6399 
6400 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6401                                             unsigned functionCallConv) const {
6402   // 6.1.2.1 The following argument types are VFP CPRCs:
6403   //   A single-precision floating-point type (including promoted
6404   //   half-precision types); A double-precision floating-point type;
6405   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6406   //   with a Base Type of a single- or double-precision floating-point type,
6407   //   64-bit containerized vectors or 128-bit containerized vectors with one
6408   //   to four Elements.
6409   // Variadic functions should always marshal to the base standard.
6410   bool IsAAPCS_VFP =
6411       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6412 
6413   Ty = useFirstFieldIfTransparentUnion(Ty);
6414 
6415   // Handle illegal vector types here.
6416   if (isIllegalVectorType(Ty))
6417     return coerceIllegalVector(Ty);
6418 
6419   if (!isAggregateTypeForABI(Ty)) {
6420     // Treat an enum type as its underlying type.
6421     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6422       Ty = EnumTy->getDecl()->getIntegerType();
6423     }
6424 
6425     if (const auto *EIT = Ty->getAs<ExtIntType>())
6426       if (EIT->getNumBits() > 64)
6427         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6428 
6429     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6430                                               : ABIArgInfo::getDirect());
6431   }
6432 
6433   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6434     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6435   }
6436 
6437   // Ignore empty records.
6438   if (isEmptyRecord(getContext(), Ty, true))
6439     return ABIArgInfo::getIgnore();
6440 
6441   if (IsAAPCS_VFP) {
6442     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6443     // into VFP registers.
6444     const Type *Base = nullptr;
6445     uint64_t Members = 0;
6446     if (isHomogeneousAggregate(Ty, Base, Members))
6447       return classifyHomogeneousAggregate(Ty, Base, Members);
6448   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6449     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6450     // this convention even for a variadic function: the backend will use GPRs
6451     // if needed.
6452     const Type *Base = nullptr;
6453     uint64_t Members = 0;
6454     if (isHomogeneousAggregate(Ty, Base, Members)) {
6455       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6456       llvm::Type *Ty =
6457         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6458       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6459     }
6460   }
6461 
6462   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6463       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6464     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6465     // bigger than 128-bits, they get placed in space allocated by the caller,
6466     // and a pointer is passed.
6467     return ABIArgInfo::getIndirect(
6468         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6469   }
6470 
6471   // Support byval for ARM.
6472   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6473   // most 8-byte. We realign the indirect argument if type alignment is bigger
6474   // than ABI alignment.
6475   uint64_t ABIAlign = 4;
6476   uint64_t TyAlign;
6477   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6478       getABIKind() == ARMABIInfo::AAPCS) {
6479     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6480     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6481   } else {
6482     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6483   }
6484   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6485     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6486     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6487                                    /*ByVal=*/true,
6488                                    /*Realign=*/TyAlign > ABIAlign);
6489   }
6490 
6491   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6492   // same size and alignment.
6493   if (getTarget().isRenderScriptTarget()) {
6494     return coerceToIntArray(Ty, getContext(), getVMContext());
6495   }
6496 
6497   // Otherwise, pass by coercing to a structure of the appropriate size.
6498   llvm::Type* ElemTy;
6499   unsigned SizeRegs;
6500   // FIXME: Try to match the types of the arguments more accurately where
6501   // we can.
6502   if (TyAlign <= 4) {
6503     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6504     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6505   } else {
6506     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6507     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6508   }
6509 
6510   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6511 }
6512 
6513 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6514                               llvm::LLVMContext &VMContext) {
6515   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6516   // is called integer-like if its size is less than or equal to one word, and
6517   // the offset of each of its addressable sub-fields is zero.
6518 
6519   uint64_t Size = Context.getTypeSize(Ty);
6520 
6521   // Check that the type fits in a word.
6522   if (Size > 32)
6523     return false;
6524 
6525   // FIXME: Handle vector types!
6526   if (Ty->isVectorType())
6527     return false;
6528 
6529   // Float types are never treated as "integer like".
6530   if (Ty->isRealFloatingType())
6531     return false;
6532 
6533   // If this is a builtin or pointer type then it is ok.
6534   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6535     return true;
6536 
6537   // Small complex integer types are "integer like".
6538   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6539     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6540 
6541   // Single element and zero sized arrays should be allowed, by the definition
6542   // above, but they are not.
6543 
6544   // Otherwise, it must be a record type.
6545   const RecordType *RT = Ty->getAs<RecordType>();
6546   if (!RT) return false;
6547 
6548   // Ignore records with flexible arrays.
6549   const RecordDecl *RD = RT->getDecl();
6550   if (RD->hasFlexibleArrayMember())
6551     return false;
6552 
6553   // Check that all sub-fields are at offset 0, and are themselves "integer
6554   // like".
6555   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6556 
6557   bool HadField = false;
6558   unsigned idx = 0;
6559   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6560        i != e; ++i, ++idx) {
6561     const FieldDecl *FD = *i;
6562 
6563     // Bit-fields are not addressable, we only need to verify they are "integer
6564     // like". We still have to disallow a subsequent non-bitfield, for example:
6565     //   struct { int : 0; int x }
6566     // is non-integer like according to gcc.
6567     if (FD->isBitField()) {
6568       if (!RD->isUnion())
6569         HadField = true;
6570 
6571       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6572         return false;
6573 
6574       continue;
6575     }
6576 
6577     // Check if this field is at offset 0.
6578     if (Layout.getFieldOffset(idx) != 0)
6579       return false;
6580 
6581     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6582       return false;
6583 
6584     // Only allow at most one field in a structure. This doesn't match the
6585     // wording above, but follows gcc in situations with a field following an
6586     // empty structure.
6587     if (!RD->isUnion()) {
6588       if (HadField)
6589         return false;
6590 
6591       HadField = true;
6592     }
6593   }
6594 
6595   return true;
6596 }
6597 
6598 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6599                                           unsigned functionCallConv) const {
6600 
6601   // Variadic functions should always marshal to the base standard.
6602   bool IsAAPCS_VFP =
6603       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6604 
6605   if (RetTy->isVoidType())
6606     return ABIArgInfo::getIgnore();
6607 
6608   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6609     // Large vector types should be returned via memory.
6610     if (getContext().getTypeSize(RetTy) > 128)
6611       return getNaturalAlignIndirect(RetTy);
6612     // TODO: FP16/BF16 vectors should be converted to integer vectors
6613     // This check is similar  to isIllegalVectorType - refactor?
6614     if ((!getTarget().hasLegalHalfType() &&
6615         (VT->getElementType()->isFloat16Type() ||
6616          VT->getElementType()->isHalfType())) ||
6617         (IsFloatABISoftFP &&
6618          VT->getElementType()->isBFloat16Type()))
6619       return coerceIllegalVector(RetTy);
6620   }
6621 
6622   if (!isAggregateTypeForABI(RetTy)) {
6623     // Treat an enum type as its underlying type.
6624     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6625       RetTy = EnumTy->getDecl()->getIntegerType();
6626 
6627     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6628       if (EIT->getNumBits() > 64)
6629         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6630 
6631     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6632                                                 : ABIArgInfo::getDirect();
6633   }
6634 
6635   // Are we following APCS?
6636   if (getABIKind() == APCS) {
6637     if (isEmptyRecord(getContext(), RetTy, false))
6638       return ABIArgInfo::getIgnore();
6639 
6640     // Complex types are all returned as packed integers.
6641     //
6642     // FIXME: Consider using 2 x vector types if the back end handles them
6643     // correctly.
6644     if (RetTy->isAnyComplexType())
6645       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6646           getVMContext(), getContext().getTypeSize(RetTy)));
6647 
6648     // Integer like structures are returned in r0.
6649     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6650       // Return in the smallest viable integer type.
6651       uint64_t Size = getContext().getTypeSize(RetTy);
6652       if (Size <= 8)
6653         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6654       if (Size <= 16)
6655         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6656       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6657     }
6658 
6659     // Otherwise return in memory.
6660     return getNaturalAlignIndirect(RetTy);
6661   }
6662 
6663   // Otherwise this is an AAPCS variant.
6664 
6665   if (isEmptyRecord(getContext(), RetTy, true))
6666     return ABIArgInfo::getIgnore();
6667 
6668   // Check for homogeneous aggregates with AAPCS-VFP.
6669   if (IsAAPCS_VFP) {
6670     const Type *Base = nullptr;
6671     uint64_t Members = 0;
6672     if (isHomogeneousAggregate(RetTy, Base, Members))
6673       return classifyHomogeneousAggregate(RetTy, Base, Members);
6674   }
6675 
6676   // Aggregates <= 4 bytes are returned in r0; other aggregates
6677   // are returned indirectly.
6678   uint64_t Size = getContext().getTypeSize(RetTy);
6679   if (Size <= 32) {
6680     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6681     // same size and alignment.
6682     if (getTarget().isRenderScriptTarget()) {
6683       return coerceToIntArray(RetTy, getContext(), getVMContext());
6684     }
6685     if (getDataLayout().isBigEndian())
6686       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6687       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6688 
6689     // Return in the smallest viable integer type.
6690     if (Size <= 8)
6691       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6692     if (Size <= 16)
6693       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6694     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6695   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6696     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6697     llvm::Type *CoerceTy =
6698         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6699     return ABIArgInfo::getDirect(CoerceTy);
6700   }
6701 
6702   return getNaturalAlignIndirect(RetTy);
6703 }
6704 
6705 /// isIllegalVector - check whether Ty is an illegal vector type.
6706 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6707   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6708     // On targets that don't support half, fp16 or bfloat, they are expanded
6709     // into float, and we don't want the ABI to depend on whether or not they
6710     // are supported in hardware. Thus return false to coerce vectors of these
6711     // types into integer vectors.
6712     // We do not depend on hasLegalHalfType for bfloat as it is a
6713     // separate IR type.
6714     if ((!getTarget().hasLegalHalfType() &&
6715         (VT->getElementType()->isFloat16Type() ||
6716          VT->getElementType()->isHalfType())) ||
6717         (IsFloatABISoftFP &&
6718          VT->getElementType()->isBFloat16Type()))
6719       return true;
6720     if (isAndroid()) {
6721       // Android shipped using Clang 3.1, which supported a slightly different
6722       // vector ABI. The primary differences were that 3-element vector types
6723       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6724       // accepts that legacy behavior for Android only.
6725       // Check whether VT is legal.
6726       unsigned NumElements = VT->getNumElements();
6727       // NumElements should be power of 2 or equal to 3.
6728       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6729         return true;
6730     } else {
6731       // Check whether VT is legal.
6732       unsigned NumElements = VT->getNumElements();
6733       uint64_t Size = getContext().getTypeSize(VT);
6734       // NumElements should be power of 2.
6735       if (!llvm::isPowerOf2_32(NumElements))
6736         return true;
6737       // Size should be greater than 32 bits.
6738       return Size <= 32;
6739     }
6740   }
6741   return false;
6742 }
6743 
6744 /// Return true if a type contains any 16-bit floating point vectors
6745 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6746   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6747     uint64_t NElements = AT->getSize().getZExtValue();
6748     if (NElements == 0)
6749       return false;
6750     return containsAnyFP16Vectors(AT->getElementType());
6751   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6752     const RecordDecl *RD = RT->getDecl();
6753 
6754     // If this is a C++ record, check the bases first.
6755     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6756       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6757             return containsAnyFP16Vectors(B.getType());
6758           }))
6759         return true;
6760 
6761     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6762           return FD && containsAnyFP16Vectors(FD->getType());
6763         }))
6764       return true;
6765 
6766     return false;
6767   } else {
6768     if (const VectorType *VT = Ty->getAs<VectorType>())
6769       return (VT->getElementType()->isFloat16Type() ||
6770               VT->getElementType()->isBFloat16Type() ||
6771               VT->getElementType()->isHalfType());
6772     return false;
6773   }
6774 }
6775 
6776 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6777                                            llvm::Type *eltTy,
6778                                            unsigned numElts) const {
6779   if (!llvm::isPowerOf2_32(numElts))
6780     return false;
6781   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6782   if (size > 64)
6783     return false;
6784   if (vectorSize.getQuantity() != 8 &&
6785       (vectorSize.getQuantity() != 16 || numElts == 1))
6786     return false;
6787   return true;
6788 }
6789 
6790 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6791   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6792   // double, or 64-bit or 128-bit vectors.
6793   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6794     if (BT->getKind() == BuiltinType::Float ||
6795         BT->getKind() == BuiltinType::Double ||
6796         BT->getKind() == BuiltinType::LongDouble)
6797       return true;
6798   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6799     unsigned VecSize = getContext().getTypeSize(VT);
6800     if (VecSize == 64 || VecSize == 128)
6801       return true;
6802   }
6803   return false;
6804 }
6805 
6806 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6807                                                    uint64_t Members) const {
6808   return Members <= 4;
6809 }
6810 
6811 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6812                                         bool acceptHalf) const {
6813   // Give precedence to user-specified calling conventions.
6814   if (callConvention != llvm::CallingConv::C)
6815     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6816   else
6817     return (getABIKind() == AAPCS_VFP) ||
6818            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6819 }
6820 
6821 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6822                               QualType Ty) const {
6823   CharUnits SlotSize = CharUnits::fromQuantity(4);
6824 
6825   // Empty records are ignored for parameter passing purposes.
6826   if (isEmptyRecord(getContext(), Ty, true)) {
6827     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6828     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6829     return Addr;
6830   }
6831 
6832   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6833   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6834 
6835   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6836   bool IsIndirect = false;
6837   const Type *Base = nullptr;
6838   uint64_t Members = 0;
6839   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6840     IsIndirect = true;
6841 
6842   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6843   // allocated by the caller.
6844   } else if (TySize > CharUnits::fromQuantity(16) &&
6845              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6846              !isHomogeneousAggregate(Ty, Base, Members)) {
6847     IsIndirect = true;
6848 
6849   // Otherwise, bound the type's ABI alignment.
6850   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6851   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6852   // Our callers should be prepared to handle an under-aligned address.
6853   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6854              getABIKind() == ARMABIInfo::AAPCS) {
6855     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6856     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6857   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6858     // ARMv7k allows type alignment up to 16 bytes.
6859     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6860     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6861   } else {
6862     TyAlignForABI = CharUnits::fromQuantity(4);
6863   }
6864 
6865   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6866   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6867                           SlotSize, /*AllowHigherAlign*/ true);
6868 }
6869 
6870 //===----------------------------------------------------------------------===//
6871 // NVPTX ABI Implementation
6872 //===----------------------------------------------------------------------===//
6873 
6874 namespace {
6875 
6876 class NVPTXTargetCodeGenInfo;
6877 
6878 class NVPTXABIInfo : public ABIInfo {
6879   NVPTXTargetCodeGenInfo &CGInfo;
6880 
6881 public:
6882   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6883       : ABIInfo(CGT), CGInfo(Info) {}
6884 
6885   ABIArgInfo classifyReturnType(QualType RetTy) const;
6886   ABIArgInfo classifyArgumentType(QualType Ty) const;
6887 
6888   void computeInfo(CGFunctionInfo &FI) const override;
6889   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6890                     QualType Ty) const override;
6891   bool isUnsupportedType(QualType T) const;
6892   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6893 };
6894 
6895 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6896 public:
6897   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6898       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6899 
6900   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6901                            CodeGen::CodeGenModule &M) const override;
6902   bool shouldEmitStaticExternCAliases() const override;
6903 
6904   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6905     // On the device side, surface reference is represented as an object handle
6906     // in 64-bit integer.
6907     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6908   }
6909 
6910   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6911     // On the device side, texture reference is represented as an object handle
6912     // in 64-bit integer.
6913     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6914   }
6915 
6916   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6917                                               LValue Src) const override {
6918     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6919     return true;
6920   }
6921 
6922   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6923                                               LValue Src) const override {
6924     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6925     return true;
6926   }
6927 
6928 private:
6929   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6930   // resulting MDNode to the nvvm.annotations MDNode.
6931   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6932                               int Operand);
6933 
6934   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6935                                            LValue Src) {
6936     llvm::Value *Handle = nullptr;
6937     llvm::Constant *C =
6938         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6939     // Lookup `addrspacecast` through the constant pointer if any.
6940     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6941       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6942     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6943       // Load the handle from the specific global variable using
6944       // `nvvm.texsurf.handle.internal` intrinsic.
6945       Handle = CGF.EmitRuntimeCall(
6946           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6947                                {GV->getType()}),
6948           {GV}, "texsurf_handle");
6949     } else
6950       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6951     CGF.EmitStoreOfScalar(Handle, Dst);
6952   }
6953 };
6954 
6955 /// Checks if the type is unsupported directly by the current target.
6956 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6957   ASTContext &Context = getContext();
6958   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6959     return true;
6960   if (!Context.getTargetInfo().hasFloat128Type() &&
6961       (T->isFloat128Type() ||
6962        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6963     return true;
6964   if (const auto *EIT = T->getAs<ExtIntType>())
6965     return EIT->getNumBits() >
6966            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6967   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6968       Context.getTypeSize(T) > 64U)
6969     return true;
6970   if (const auto *AT = T->getAsArrayTypeUnsafe())
6971     return isUnsupportedType(AT->getElementType());
6972   const auto *RT = T->getAs<RecordType>();
6973   if (!RT)
6974     return false;
6975   const RecordDecl *RD = RT->getDecl();
6976 
6977   // If this is a C++ record, check the bases first.
6978   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6979     for (const CXXBaseSpecifier &I : CXXRD->bases())
6980       if (isUnsupportedType(I.getType()))
6981         return true;
6982 
6983   for (const FieldDecl *I : RD->fields())
6984     if (isUnsupportedType(I->getType()))
6985       return true;
6986   return false;
6987 }
6988 
6989 /// Coerce the given type into an array with maximum allowed size of elements.
6990 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6991                                                    unsigned MaxSize) const {
6992   // Alignment and Size are measured in bits.
6993   const uint64_t Size = getContext().getTypeSize(Ty);
6994   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6995   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6996   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
6997   const uint64_t NumElements = (Size + Div - 1) / Div;
6998   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6999 }
7000 
7001 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7002   if (RetTy->isVoidType())
7003     return ABIArgInfo::getIgnore();
7004 
7005   if (getContext().getLangOpts().OpenMP &&
7006       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7007     return coerceToIntArrayWithLimit(RetTy, 64);
7008 
7009   // note: this is different from default ABI
7010   if (!RetTy->isScalarType())
7011     return ABIArgInfo::getDirect();
7012 
7013   // Treat an enum type as its underlying type.
7014   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7015     RetTy = EnumTy->getDecl()->getIntegerType();
7016 
7017   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7018                                                : ABIArgInfo::getDirect());
7019 }
7020 
7021 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7022   // Treat an enum type as its underlying type.
7023   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7024     Ty = EnumTy->getDecl()->getIntegerType();
7025 
7026   // Return aggregates type as indirect by value
7027   if (isAggregateTypeForABI(Ty)) {
7028     // Under CUDA device compilation, tex/surf builtin types are replaced with
7029     // object types and passed directly.
7030     if (getContext().getLangOpts().CUDAIsDevice) {
7031       if (Ty->isCUDADeviceBuiltinSurfaceType())
7032         return ABIArgInfo::getDirect(
7033             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7034       if (Ty->isCUDADeviceBuiltinTextureType())
7035         return ABIArgInfo::getDirect(
7036             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7037     }
7038     return getNaturalAlignIndirect(Ty, /* byval */ true);
7039   }
7040 
7041   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7042     if ((EIT->getNumBits() > 128) ||
7043         (!getContext().getTargetInfo().hasInt128Type() &&
7044          EIT->getNumBits() > 64))
7045       return getNaturalAlignIndirect(Ty, /* byval */ true);
7046   }
7047 
7048   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7049                                             : ABIArgInfo::getDirect());
7050 }
7051 
7052 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7053   if (!getCXXABI().classifyReturnType(FI))
7054     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7055   for (auto &I : FI.arguments())
7056     I.info = classifyArgumentType(I.type);
7057 
7058   // Always honor user-specified calling convention.
7059   if (FI.getCallingConvention() != llvm::CallingConv::C)
7060     return;
7061 
7062   FI.setEffectiveCallingConvention(getRuntimeCC());
7063 }
7064 
7065 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7066                                 QualType Ty) const {
7067   llvm_unreachable("NVPTX does not support varargs");
7068 }
7069 
7070 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7071     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7072   if (GV->isDeclaration())
7073     return;
7074   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7075   if (VD) {
7076     if (M.getLangOpts().CUDA) {
7077       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7078         addNVVMMetadata(GV, "surface", 1);
7079       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7080         addNVVMMetadata(GV, "texture", 1);
7081       return;
7082     }
7083   }
7084 
7085   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7086   if (!FD) return;
7087 
7088   llvm::Function *F = cast<llvm::Function>(GV);
7089 
7090   // Perform special handling in OpenCL mode
7091   if (M.getLangOpts().OpenCL) {
7092     // Use OpenCL function attributes to check for kernel functions
7093     // By default, all functions are device functions
7094     if (FD->hasAttr<OpenCLKernelAttr>()) {
7095       // OpenCL __kernel functions get kernel metadata
7096       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7097       addNVVMMetadata(F, "kernel", 1);
7098       // And kernel functions are not subject to inlining
7099       F->addFnAttr(llvm::Attribute::NoInline);
7100     }
7101   }
7102 
7103   // Perform special handling in CUDA mode.
7104   if (M.getLangOpts().CUDA) {
7105     // CUDA __global__ functions get a kernel metadata entry.  Since
7106     // __global__ functions cannot be called from the device, we do not
7107     // need to set the noinline attribute.
7108     if (FD->hasAttr<CUDAGlobalAttr>()) {
7109       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7110       addNVVMMetadata(F, "kernel", 1);
7111     }
7112     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7113       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7114       llvm::APSInt MaxThreads(32);
7115       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7116       if (MaxThreads > 0)
7117         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7118 
7119       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7120       // not specified in __launch_bounds__ or if the user specified a 0 value,
7121       // we don't have to add a PTX directive.
7122       if (Attr->getMinBlocks()) {
7123         llvm::APSInt MinBlocks(32);
7124         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7125         if (MinBlocks > 0)
7126           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7127           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7128       }
7129     }
7130   }
7131 }
7132 
7133 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7134                                              StringRef Name, int Operand) {
7135   llvm::Module *M = GV->getParent();
7136   llvm::LLVMContext &Ctx = M->getContext();
7137 
7138   // Get "nvvm.annotations" metadata node
7139   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7140 
7141   llvm::Metadata *MDVals[] = {
7142       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7143       llvm::ConstantAsMetadata::get(
7144           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7145   // Append metadata to nvvm.annotations
7146   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7147 }
7148 
7149 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7150   return false;
7151 }
7152 }
7153 
7154 //===----------------------------------------------------------------------===//
7155 // SystemZ ABI Implementation
7156 //===----------------------------------------------------------------------===//
7157 
7158 namespace {
7159 
7160 class SystemZABIInfo : public SwiftABIInfo {
7161   bool HasVector;
7162   bool IsSoftFloatABI;
7163 
7164 public:
7165   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7166     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7167 
7168   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7169   bool isCompoundType(QualType Ty) const;
7170   bool isVectorArgumentType(QualType Ty) const;
7171   bool isFPArgumentType(QualType Ty) const;
7172   QualType GetSingleElementType(QualType Ty) const;
7173 
7174   ABIArgInfo classifyReturnType(QualType RetTy) const;
7175   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7176 
7177   void computeInfo(CGFunctionInfo &FI) const override {
7178     if (!getCXXABI().classifyReturnType(FI))
7179       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7180     for (auto &I : FI.arguments())
7181       I.info = classifyArgumentType(I.type);
7182   }
7183 
7184   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7185                     QualType Ty) const override;
7186 
7187   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7188                                     bool asReturnValue) const override {
7189     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7190   }
7191   bool isSwiftErrorInRegister() const override {
7192     return false;
7193   }
7194 };
7195 
7196 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7197 public:
7198   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7199       : TargetCodeGenInfo(
7200             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7201 
7202   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7203                           CGBuilderTy &Builder,
7204                           CodeGenModule &CGM) const override {
7205     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7206     // Only use TDC in constrained FP mode.
7207     if (!Builder.getIsFPConstrained())
7208       return nullptr;
7209 
7210     llvm::Type *Ty = V->getType();
7211     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7212       llvm::Module &M = CGM.getModule();
7213       auto &Ctx = M.getContext();
7214       llvm::Function *TDCFunc =
7215           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7216       unsigned TDCBits = 0;
7217       switch (BuiltinID) {
7218       case Builtin::BI__builtin_isnan:
7219         TDCBits = 0xf;
7220         break;
7221       default:
7222         break;
7223       }
7224       if (TDCBits)
7225         return Builder.CreateCall(
7226             TDCFunc,
7227             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7228     }
7229     return nullptr;
7230   }
7231 };
7232 }
7233 
7234 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7235   // Treat an enum type as its underlying type.
7236   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7237     Ty = EnumTy->getDecl()->getIntegerType();
7238 
7239   // Promotable integer types are required to be promoted by the ABI.
7240   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7241     return true;
7242 
7243   if (const auto *EIT = Ty->getAs<ExtIntType>())
7244     if (EIT->getNumBits() < 64)
7245       return true;
7246 
7247   // 32-bit values must also be promoted.
7248   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7249     switch (BT->getKind()) {
7250     case BuiltinType::Int:
7251     case BuiltinType::UInt:
7252       return true;
7253     default:
7254       return false;
7255     }
7256   return false;
7257 }
7258 
7259 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7260   return (Ty->isAnyComplexType() ||
7261           Ty->isVectorType() ||
7262           isAggregateTypeForABI(Ty));
7263 }
7264 
7265 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7266   return (HasVector &&
7267           Ty->isVectorType() &&
7268           getContext().getTypeSize(Ty) <= 128);
7269 }
7270 
7271 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7272   if (IsSoftFloatABI)
7273     return false;
7274 
7275   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7276     switch (BT->getKind()) {
7277     case BuiltinType::Float:
7278     case BuiltinType::Double:
7279       return true;
7280     default:
7281       return false;
7282     }
7283 
7284   return false;
7285 }
7286 
7287 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7288   const RecordType *RT = Ty->getAs<RecordType>();
7289 
7290   if (RT && RT->isStructureOrClassType()) {
7291     const RecordDecl *RD = RT->getDecl();
7292     QualType Found;
7293 
7294     // If this is a C++ record, check the bases first.
7295     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7296       for (const auto &I : CXXRD->bases()) {
7297         QualType Base = I.getType();
7298 
7299         // Empty bases don't affect things either way.
7300         if (isEmptyRecord(getContext(), Base, true))
7301           continue;
7302 
7303         if (!Found.isNull())
7304           return Ty;
7305         Found = GetSingleElementType(Base);
7306       }
7307 
7308     // Check the fields.
7309     for (const auto *FD : RD->fields()) {
7310       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7311       // Unlike isSingleElementStruct(), empty structure and array fields
7312       // do count.  So do anonymous bitfields that aren't zero-sized.
7313       if (getContext().getLangOpts().CPlusPlus &&
7314           FD->isZeroLengthBitField(getContext()))
7315         continue;
7316       // Like isSingleElementStruct(), ignore C++20 empty data members.
7317       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7318           isEmptyRecord(getContext(), FD->getType(), true))
7319         continue;
7320 
7321       // Unlike isSingleElementStruct(), arrays do not count.
7322       // Nested structures still do though.
7323       if (!Found.isNull())
7324         return Ty;
7325       Found = GetSingleElementType(FD->getType());
7326     }
7327 
7328     // Unlike isSingleElementStruct(), trailing padding is allowed.
7329     // An 8-byte aligned struct s { float f; } is passed as a double.
7330     if (!Found.isNull())
7331       return Found;
7332   }
7333 
7334   return Ty;
7335 }
7336 
7337 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7338                                   QualType Ty) const {
7339   // Assume that va_list type is correct; should be pointer to LLVM type:
7340   // struct {
7341   //   i64 __gpr;
7342   //   i64 __fpr;
7343   //   i8 *__overflow_arg_area;
7344   //   i8 *__reg_save_area;
7345   // };
7346 
7347   // Every non-vector argument occupies 8 bytes and is passed by preference
7348   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7349   // always passed on the stack.
7350   Ty = getContext().getCanonicalType(Ty);
7351   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7352   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7353   llvm::Type *DirectTy = ArgTy;
7354   ABIArgInfo AI = classifyArgumentType(Ty);
7355   bool IsIndirect = AI.isIndirect();
7356   bool InFPRs = false;
7357   bool IsVector = false;
7358   CharUnits UnpaddedSize;
7359   CharUnits DirectAlign;
7360   if (IsIndirect) {
7361     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7362     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7363   } else {
7364     if (AI.getCoerceToType())
7365       ArgTy = AI.getCoerceToType();
7366     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7367     IsVector = ArgTy->isVectorTy();
7368     UnpaddedSize = TyInfo.Width;
7369     DirectAlign = TyInfo.Align;
7370   }
7371   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7372   if (IsVector && UnpaddedSize > PaddedSize)
7373     PaddedSize = CharUnits::fromQuantity(16);
7374   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7375 
7376   CharUnits Padding = (PaddedSize - UnpaddedSize);
7377 
7378   llvm::Type *IndexTy = CGF.Int64Ty;
7379   llvm::Value *PaddedSizeV =
7380     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7381 
7382   if (IsVector) {
7383     // Work out the address of a vector argument on the stack.
7384     // Vector arguments are always passed in the high bits of a
7385     // single (8 byte) or double (16 byte) stack slot.
7386     Address OverflowArgAreaPtr =
7387         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7388     Address OverflowArgArea =
7389       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7390               TyInfo.Align);
7391     Address MemAddr =
7392       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7393 
7394     // Update overflow_arg_area_ptr pointer
7395     llvm::Value *NewOverflowArgArea =
7396       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7397                             "overflow_arg_area");
7398     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7399 
7400     return MemAddr;
7401   }
7402 
7403   assert(PaddedSize.getQuantity() == 8);
7404 
7405   unsigned MaxRegs, RegCountField, RegSaveIndex;
7406   CharUnits RegPadding;
7407   if (InFPRs) {
7408     MaxRegs = 4; // Maximum of 4 FPR arguments
7409     RegCountField = 1; // __fpr
7410     RegSaveIndex = 16; // save offset for f0
7411     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7412   } else {
7413     MaxRegs = 5; // Maximum of 5 GPR arguments
7414     RegCountField = 0; // __gpr
7415     RegSaveIndex = 2; // save offset for r2
7416     RegPadding = Padding; // values are passed in the low bits of a GPR
7417   }
7418 
7419   Address RegCountPtr =
7420       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7421   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7422   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7423   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7424                                                  "fits_in_regs");
7425 
7426   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7427   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7428   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7429   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7430 
7431   // Emit code to load the value if it was passed in registers.
7432   CGF.EmitBlock(InRegBlock);
7433 
7434   // Work out the address of an argument register.
7435   llvm::Value *ScaledRegCount =
7436     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7437   llvm::Value *RegBase =
7438     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7439                                       + RegPadding.getQuantity());
7440   llvm::Value *RegOffset =
7441     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7442   Address RegSaveAreaPtr =
7443       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7444   llvm::Value *RegSaveArea =
7445     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7446   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7447                                            "raw_reg_addr"),
7448                      PaddedSize);
7449   Address RegAddr =
7450     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7451 
7452   // Update the register count
7453   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7454   llvm::Value *NewRegCount =
7455     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7456   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7457   CGF.EmitBranch(ContBlock);
7458 
7459   // Emit code to load the value if it was passed in memory.
7460   CGF.EmitBlock(InMemBlock);
7461 
7462   // Work out the address of a stack argument.
7463   Address OverflowArgAreaPtr =
7464       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7465   Address OverflowArgArea =
7466     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7467             PaddedSize);
7468   Address RawMemAddr =
7469     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7470   Address MemAddr =
7471     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7472 
7473   // Update overflow_arg_area_ptr pointer
7474   llvm::Value *NewOverflowArgArea =
7475     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7476                           "overflow_arg_area");
7477   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7478   CGF.EmitBranch(ContBlock);
7479 
7480   // Return the appropriate result.
7481   CGF.EmitBlock(ContBlock);
7482   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7483                                  MemAddr, InMemBlock, "va_arg.addr");
7484 
7485   if (IsIndirect)
7486     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7487                       TyInfo.Align);
7488 
7489   return ResAddr;
7490 }
7491 
7492 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7493   if (RetTy->isVoidType())
7494     return ABIArgInfo::getIgnore();
7495   if (isVectorArgumentType(RetTy))
7496     return ABIArgInfo::getDirect();
7497   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7498     return getNaturalAlignIndirect(RetTy);
7499   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7500                                                : ABIArgInfo::getDirect());
7501 }
7502 
7503 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7504   // Handle the generic C++ ABI.
7505   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7506     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7507 
7508   // Integers and enums are extended to full register width.
7509   if (isPromotableIntegerTypeForABI(Ty))
7510     return ABIArgInfo::getExtend(Ty);
7511 
7512   // Handle vector types and vector-like structure types.  Note that
7513   // as opposed to float-like structure types, we do not allow any
7514   // padding for vector-like structures, so verify the sizes match.
7515   uint64_t Size = getContext().getTypeSize(Ty);
7516   QualType SingleElementTy = GetSingleElementType(Ty);
7517   if (isVectorArgumentType(SingleElementTy) &&
7518       getContext().getTypeSize(SingleElementTy) == Size)
7519     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7520 
7521   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7522   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7523     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7524 
7525   // Handle small structures.
7526   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7527     // Structures with flexible arrays have variable length, so really
7528     // fail the size test above.
7529     const RecordDecl *RD = RT->getDecl();
7530     if (RD->hasFlexibleArrayMember())
7531       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7532 
7533     // The structure is passed as an unextended integer, a float, or a double.
7534     llvm::Type *PassTy;
7535     if (isFPArgumentType(SingleElementTy)) {
7536       assert(Size == 32 || Size == 64);
7537       if (Size == 32)
7538         PassTy = llvm::Type::getFloatTy(getVMContext());
7539       else
7540         PassTy = llvm::Type::getDoubleTy(getVMContext());
7541     } else
7542       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7543     return ABIArgInfo::getDirect(PassTy);
7544   }
7545 
7546   // Non-structure compounds are passed indirectly.
7547   if (isCompoundType(Ty))
7548     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7549 
7550   return ABIArgInfo::getDirect(nullptr);
7551 }
7552 
7553 //===----------------------------------------------------------------------===//
7554 // MSP430 ABI Implementation
7555 //===----------------------------------------------------------------------===//
7556 
7557 namespace {
7558 
7559 class MSP430ABIInfo : public DefaultABIInfo {
7560   static ABIArgInfo complexArgInfo() {
7561     ABIArgInfo Info = ABIArgInfo::getDirect();
7562     Info.setCanBeFlattened(false);
7563     return Info;
7564   }
7565 
7566 public:
7567   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7568 
7569   ABIArgInfo classifyReturnType(QualType RetTy) const {
7570     if (RetTy->isAnyComplexType())
7571       return complexArgInfo();
7572 
7573     return DefaultABIInfo::classifyReturnType(RetTy);
7574   }
7575 
7576   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7577     if (RetTy->isAnyComplexType())
7578       return complexArgInfo();
7579 
7580     return DefaultABIInfo::classifyArgumentType(RetTy);
7581   }
7582 
7583   // Just copy the original implementations because
7584   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7585   void computeInfo(CGFunctionInfo &FI) const override {
7586     if (!getCXXABI().classifyReturnType(FI))
7587       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7588     for (auto &I : FI.arguments())
7589       I.info = classifyArgumentType(I.type);
7590   }
7591 
7592   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7593                     QualType Ty) const override {
7594     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7595   }
7596 };
7597 
7598 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7599 public:
7600   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7601       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7602   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7603                            CodeGen::CodeGenModule &M) const override;
7604 };
7605 
7606 }
7607 
7608 void MSP430TargetCodeGenInfo::setTargetAttributes(
7609     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7610   if (GV->isDeclaration())
7611     return;
7612   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7613     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7614     if (!InterruptAttr)
7615       return;
7616 
7617     // Handle 'interrupt' attribute:
7618     llvm::Function *F = cast<llvm::Function>(GV);
7619 
7620     // Step 1: Set ISR calling convention.
7621     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7622 
7623     // Step 2: Add attributes goodness.
7624     F->addFnAttr(llvm::Attribute::NoInline);
7625     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7626   }
7627 }
7628 
7629 //===----------------------------------------------------------------------===//
7630 // MIPS ABI Implementation.  This works for both little-endian and
7631 // big-endian variants.
7632 //===----------------------------------------------------------------------===//
7633 
7634 namespace {
7635 class MipsABIInfo : public ABIInfo {
7636   bool IsO32;
7637   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7638   void CoerceToIntArgs(uint64_t TySize,
7639                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7640   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7641   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7642   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7643 public:
7644   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7645     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7646     StackAlignInBytes(IsO32 ? 8 : 16) {}
7647 
7648   ABIArgInfo classifyReturnType(QualType RetTy) const;
7649   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7650   void computeInfo(CGFunctionInfo &FI) const override;
7651   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7652                     QualType Ty) const override;
7653   ABIArgInfo extendType(QualType Ty) const;
7654 };
7655 
7656 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7657   unsigned SizeOfUnwindException;
7658 public:
7659   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7660       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7661         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7662 
7663   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7664     return 29;
7665   }
7666 
7667   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7668                            CodeGen::CodeGenModule &CGM) const override {
7669     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7670     if (!FD) return;
7671     llvm::Function *Fn = cast<llvm::Function>(GV);
7672 
7673     if (FD->hasAttr<MipsLongCallAttr>())
7674       Fn->addFnAttr("long-call");
7675     else if (FD->hasAttr<MipsShortCallAttr>())
7676       Fn->addFnAttr("short-call");
7677 
7678     // Other attributes do not have a meaning for declarations.
7679     if (GV->isDeclaration())
7680       return;
7681 
7682     if (FD->hasAttr<Mips16Attr>()) {
7683       Fn->addFnAttr("mips16");
7684     }
7685     else if (FD->hasAttr<NoMips16Attr>()) {
7686       Fn->addFnAttr("nomips16");
7687     }
7688 
7689     if (FD->hasAttr<MicroMipsAttr>())
7690       Fn->addFnAttr("micromips");
7691     else if (FD->hasAttr<NoMicroMipsAttr>())
7692       Fn->addFnAttr("nomicromips");
7693 
7694     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7695     if (!Attr)
7696       return;
7697 
7698     const char *Kind;
7699     switch (Attr->getInterrupt()) {
7700     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7701     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7702     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7703     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7704     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7705     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7706     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7707     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7708     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7709     }
7710 
7711     Fn->addFnAttr("interrupt", Kind);
7712 
7713   }
7714 
7715   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7716                                llvm::Value *Address) const override;
7717 
7718   unsigned getSizeOfUnwindException() const override {
7719     return SizeOfUnwindException;
7720   }
7721 };
7722 }
7723 
7724 void MipsABIInfo::CoerceToIntArgs(
7725     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7726   llvm::IntegerType *IntTy =
7727     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7728 
7729   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7730   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7731     ArgList.push_back(IntTy);
7732 
7733   // If necessary, add one more integer type to ArgList.
7734   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7735 
7736   if (R)
7737     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7738 }
7739 
7740 // In N32/64, an aligned double precision floating point field is passed in
7741 // a register.
7742 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7743   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7744 
7745   if (IsO32) {
7746     CoerceToIntArgs(TySize, ArgList);
7747     return llvm::StructType::get(getVMContext(), ArgList);
7748   }
7749 
7750   if (Ty->isComplexType())
7751     return CGT.ConvertType(Ty);
7752 
7753   const RecordType *RT = Ty->getAs<RecordType>();
7754 
7755   // Unions/vectors are passed in integer registers.
7756   if (!RT || !RT->isStructureOrClassType()) {
7757     CoerceToIntArgs(TySize, ArgList);
7758     return llvm::StructType::get(getVMContext(), ArgList);
7759   }
7760 
7761   const RecordDecl *RD = RT->getDecl();
7762   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7763   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7764 
7765   uint64_t LastOffset = 0;
7766   unsigned idx = 0;
7767   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7768 
7769   // Iterate over fields in the struct/class and check if there are any aligned
7770   // double fields.
7771   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7772        i != e; ++i, ++idx) {
7773     const QualType Ty = i->getType();
7774     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7775 
7776     if (!BT || BT->getKind() != BuiltinType::Double)
7777       continue;
7778 
7779     uint64_t Offset = Layout.getFieldOffset(idx);
7780     if (Offset % 64) // Ignore doubles that are not aligned.
7781       continue;
7782 
7783     // Add ((Offset - LastOffset) / 64) args of type i64.
7784     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7785       ArgList.push_back(I64);
7786 
7787     // Add double type.
7788     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7789     LastOffset = Offset + 64;
7790   }
7791 
7792   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7793   ArgList.append(IntArgList.begin(), IntArgList.end());
7794 
7795   return llvm::StructType::get(getVMContext(), ArgList);
7796 }
7797 
7798 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7799                                         uint64_t Offset) const {
7800   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7801     return nullptr;
7802 
7803   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7804 }
7805 
7806 ABIArgInfo
7807 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7808   Ty = useFirstFieldIfTransparentUnion(Ty);
7809 
7810   uint64_t OrigOffset = Offset;
7811   uint64_t TySize = getContext().getTypeSize(Ty);
7812   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7813 
7814   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7815                    (uint64_t)StackAlignInBytes);
7816   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7817   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7818 
7819   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7820     // Ignore empty aggregates.
7821     if (TySize == 0)
7822       return ABIArgInfo::getIgnore();
7823 
7824     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7825       Offset = OrigOffset + MinABIStackAlignInBytes;
7826       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7827     }
7828 
7829     // If we have reached here, aggregates are passed directly by coercing to
7830     // another structure type. Padding is inserted if the offset of the
7831     // aggregate is unaligned.
7832     ABIArgInfo ArgInfo =
7833         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7834                               getPaddingType(OrigOffset, CurrOffset));
7835     ArgInfo.setInReg(true);
7836     return ArgInfo;
7837   }
7838 
7839   // Treat an enum type as its underlying type.
7840   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7841     Ty = EnumTy->getDecl()->getIntegerType();
7842 
7843   // Make sure we pass indirectly things that are too large.
7844   if (const auto *EIT = Ty->getAs<ExtIntType>())
7845     if (EIT->getNumBits() > 128 ||
7846         (EIT->getNumBits() > 64 &&
7847          !getContext().getTargetInfo().hasInt128Type()))
7848       return getNaturalAlignIndirect(Ty);
7849 
7850   // All integral types are promoted to the GPR width.
7851   if (Ty->isIntegralOrEnumerationType())
7852     return extendType(Ty);
7853 
7854   return ABIArgInfo::getDirect(
7855       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7856 }
7857 
7858 llvm::Type*
7859 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7860   const RecordType *RT = RetTy->getAs<RecordType>();
7861   SmallVector<llvm::Type*, 8> RTList;
7862 
7863   if (RT && RT->isStructureOrClassType()) {
7864     const RecordDecl *RD = RT->getDecl();
7865     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7866     unsigned FieldCnt = Layout.getFieldCount();
7867 
7868     // N32/64 returns struct/classes in floating point registers if the
7869     // following conditions are met:
7870     // 1. The size of the struct/class is no larger than 128-bit.
7871     // 2. The struct/class has one or two fields all of which are floating
7872     //    point types.
7873     // 3. The offset of the first field is zero (this follows what gcc does).
7874     //
7875     // Any other composite results are returned in integer registers.
7876     //
7877     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7878       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7879       for (; b != e; ++b) {
7880         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7881 
7882         if (!BT || !BT->isFloatingPoint())
7883           break;
7884 
7885         RTList.push_back(CGT.ConvertType(b->getType()));
7886       }
7887 
7888       if (b == e)
7889         return llvm::StructType::get(getVMContext(), RTList,
7890                                      RD->hasAttr<PackedAttr>());
7891 
7892       RTList.clear();
7893     }
7894   }
7895 
7896   CoerceToIntArgs(Size, RTList);
7897   return llvm::StructType::get(getVMContext(), RTList);
7898 }
7899 
7900 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7901   uint64_t Size = getContext().getTypeSize(RetTy);
7902 
7903   if (RetTy->isVoidType())
7904     return ABIArgInfo::getIgnore();
7905 
7906   // O32 doesn't treat zero-sized structs differently from other structs.
7907   // However, N32/N64 ignores zero sized return values.
7908   if (!IsO32 && Size == 0)
7909     return ABIArgInfo::getIgnore();
7910 
7911   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7912     if (Size <= 128) {
7913       if (RetTy->isAnyComplexType())
7914         return ABIArgInfo::getDirect();
7915 
7916       // O32 returns integer vectors in registers and N32/N64 returns all small
7917       // aggregates in registers.
7918       if (!IsO32 ||
7919           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7920         ABIArgInfo ArgInfo =
7921             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7922         ArgInfo.setInReg(true);
7923         return ArgInfo;
7924       }
7925     }
7926 
7927     return getNaturalAlignIndirect(RetTy);
7928   }
7929 
7930   // Treat an enum type as its underlying type.
7931   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7932     RetTy = EnumTy->getDecl()->getIntegerType();
7933 
7934   // Make sure we pass indirectly things that are too large.
7935   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7936     if (EIT->getNumBits() > 128 ||
7937         (EIT->getNumBits() > 64 &&
7938          !getContext().getTargetInfo().hasInt128Type()))
7939       return getNaturalAlignIndirect(RetTy);
7940 
7941   if (isPromotableIntegerTypeForABI(RetTy))
7942     return ABIArgInfo::getExtend(RetTy);
7943 
7944   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7945       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7946     return ABIArgInfo::getSignExtend(RetTy);
7947 
7948   return ABIArgInfo::getDirect();
7949 }
7950 
7951 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7952   ABIArgInfo &RetInfo = FI.getReturnInfo();
7953   if (!getCXXABI().classifyReturnType(FI))
7954     RetInfo = classifyReturnType(FI.getReturnType());
7955 
7956   // Check if a pointer to an aggregate is passed as a hidden argument.
7957   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7958 
7959   for (auto &I : FI.arguments())
7960     I.info = classifyArgumentType(I.type, Offset);
7961 }
7962 
7963 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7964                                QualType OrigTy) const {
7965   QualType Ty = OrigTy;
7966 
7967   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7968   // Pointers are also promoted in the same way but this only matters for N32.
7969   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7970   unsigned PtrWidth = getTarget().getPointerWidth(0);
7971   bool DidPromote = false;
7972   if ((Ty->isIntegerType() &&
7973           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7974       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7975     DidPromote = true;
7976     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7977                                             Ty->isSignedIntegerType());
7978   }
7979 
7980   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7981 
7982   // The alignment of things in the argument area is never larger than
7983   // StackAlignInBytes.
7984   TyInfo.Align =
7985     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7986 
7987   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7988   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7989 
7990   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7991                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7992 
7993 
7994   // If there was a promotion, "unpromote" into a temporary.
7995   // TODO: can we just use a pointer into a subset of the original slot?
7996   if (DidPromote) {
7997     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7998     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7999 
8000     // Truncate down to the right width.
8001     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8002                                                  : CGF.IntPtrTy);
8003     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8004     if (OrigTy->isPointerType())
8005       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8006 
8007     CGF.Builder.CreateStore(V, Temp);
8008     Addr = Temp;
8009   }
8010 
8011   return Addr;
8012 }
8013 
8014 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8015   int TySize = getContext().getTypeSize(Ty);
8016 
8017   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8018   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8019     return ABIArgInfo::getSignExtend(Ty);
8020 
8021   return ABIArgInfo::getExtend(Ty);
8022 }
8023 
8024 bool
8025 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8026                                                llvm::Value *Address) const {
8027   // This information comes from gcc's implementation, which seems to
8028   // as canonical as it gets.
8029 
8030   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8031   // are aliased to pairs of single-precision FP registers.
8032   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8033 
8034   // 0-31 are the general purpose registers, $0 - $31.
8035   // 32-63 are the floating-point registers, $f0 - $f31.
8036   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8037   // 66 is the (notional, I think) register for signal-handler return.
8038   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8039 
8040   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8041   // They are one bit wide and ignored here.
8042 
8043   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8044   // (coprocessor 1 is the FP unit)
8045   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8046   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8047   // 176-181 are the DSP accumulator registers.
8048   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8049   return false;
8050 }
8051 
8052 //===----------------------------------------------------------------------===//
8053 // M68k ABI Implementation
8054 //===----------------------------------------------------------------------===//
8055 
8056 namespace {
8057 
8058 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8059 public:
8060   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8061       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8062   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8063                            CodeGen::CodeGenModule &M) const override;
8064 };
8065 
8066 } // namespace
8067 
8068 void M68kTargetCodeGenInfo::setTargetAttributes(
8069     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8070   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8071     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8072       // Handle 'interrupt' attribute:
8073       llvm::Function *F = cast<llvm::Function>(GV);
8074 
8075       // Step 1: Set ISR calling convention.
8076       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8077 
8078       // Step 2: Add attributes goodness.
8079       F->addFnAttr(llvm::Attribute::NoInline);
8080 
8081       // Step 3: Emit ISR vector alias.
8082       unsigned Num = attr->getNumber() / 2;
8083       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8084                                 "__isr_" + Twine(Num), F);
8085     }
8086   }
8087 }
8088 
8089 //===----------------------------------------------------------------------===//
8090 // AVR ABI Implementation.
8091 //===----------------------------------------------------------------------===//
8092 
8093 namespace {
8094 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8095 public:
8096   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8097       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8098 
8099   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8100                            CodeGen::CodeGenModule &CGM) const override {
8101     if (GV->isDeclaration())
8102       return;
8103     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8104     if (!FD) return;
8105     auto *Fn = cast<llvm::Function>(GV);
8106 
8107     if (FD->getAttr<AVRInterruptAttr>())
8108       Fn->addFnAttr("interrupt");
8109 
8110     if (FD->getAttr<AVRSignalAttr>())
8111       Fn->addFnAttr("signal");
8112   }
8113 };
8114 }
8115 
8116 //===----------------------------------------------------------------------===//
8117 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8118 // Currently subclassed only to implement custom OpenCL C function attribute
8119 // handling.
8120 //===----------------------------------------------------------------------===//
8121 
8122 namespace {
8123 
8124 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8125 public:
8126   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8127     : DefaultTargetCodeGenInfo(CGT) {}
8128 
8129   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8130                            CodeGen::CodeGenModule &M) const override;
8131 };
8132 
8133 void TCETargetCodeGenInfo::setTargetAttributes(
8134     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8135   if (GV->isDeclaration())
8136     return;
8137   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8138   if (!FD) return;
8139 
8140   llvm::Function *F = cast<llvm::Function>(GV);
8141 
8142   if (M.getLangOpts().OpenCL) {
8143     if (FD->hasAttr<OpenCLKernelAttr>()) {
8144       // OpenCL C Kernel functions are not subject to inlining
8145       F->addFnAttr(llvm::Attribute::NoInline);
8146       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8147       if (Attr) {
8148         // Convert the reqd_work_group_size() attributes to metadata.
8149         llvm::LLVMContext &Context = F->getContext();
8150         llvm::NamedMDNode *OpenCLMetadata =
8151             M.getModule().getOrInsertNamedMetadata(
8152                 "opencl.kernel_wg_size_info");
8153 
8154         SmallVector<llvm::Metadata *, 5> Operands;
8155         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8156 
8157         Operands.push_back(
8158             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8159                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8160         Operands.push_back(
8161             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8162                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8163         Operands.push_back(
8164             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8165                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8166 
8167         // Add a boolean constant operand for "required" (true) or "hint"
8168         // (false) for implementing the work_group_size_hint attr later.
8169         // Currently always true as the hint is not yet implemented.
8170         Operands.push_back(
8171             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8172         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8173       }
8174     }
8175   }
8176 }
8177 
8178 }
8179 
8180 //===----------------------------------------------------------------------===//
8181 // Hexagon ABI Implementation
8182 //===----------------------------------------------------------------------===//
8183 
8184 namespace {
8185 
8186 class HexagonABIInfo : public DefaultABIInfo {
8187 public:
8188   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8189 
8190 private:
8191   ABIArgInfo classifyReturnType(QualType RetTy) const;
8192   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8193   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8194 
8195   void computeInfo(CGFunctionInfo &FI) const override;
8196 
8197   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8198                     QualType Ty) const override;
8199   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8200                               QualType Ty) const;
8201   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8202                               QualType Ty) const;
8203   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8204                                    QualType Ty) const;
8205 };
8206 
8207 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8208 public:
8209   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8210       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8211 
8212   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8213     return 29;
8214   }
8215 
8216   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8217                            CodeGen::CodeGenModule &GCM) const override {
8218     if (GV->isDeclaration())
8219       return;
8220     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8221     if (!FD)
8222       return;
8223   }
8224 };
8225 
8226 } // namespace
8227 
8228 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8229   unsigned RegsLeft = 6;
8230   if (!getCXXABI().classifyReturnType(FI))
8231     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8232   for (auto &I : FI.arguments())
8233     I.info = classifyArgumentType(I.type, &RegsLeft);
8234 }
8235 
8236 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8237   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8238                        " through registers");
8239 
8240   if (*RegsLeft == 0)
8241     return false;
8242 
8243   if (Size <= 32) {
8244     (*RegsLeft)--;
8245     return true;
8246   }
8247 
8248   if (2 <= (*RegsLeft & (~1U))) {
8249     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8250     return true;
8251   }
8252 
8253   // Next available register was r5 but candidate was greater than 32-bits so it
8254   // has to go on the stack. However we still consume r5
8255   if (*RegsLeft == 1)
8256     *RegsLeft = 0;
8257 
8258   return false;
8259 }
8260 
8261 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8262                                                 unsigned *RegsLeft) const {
8263   if (!isAggregateTypeForABI(Ty)) {
8264     // Treat an enum type as its underlying type.
8265     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8266       Ty = EnumTy->getDecl()->getIntegerType();
8267 
8268     uint64_t Size = getContext().getTypeSize(Ty);
8269     if (Size <= 64)
8270       HexagonAdjustRegsLeft(Size, RegsLeft);
8271 
8272     if (Size > 64 && Ty->isExtIntType())
8273       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8274 
8275     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8276                                              : ABIArgInfo::getDirect();
8277   }
8278 
8279   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8280     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8281 
8282   // Ignore empty records.
8283   if (isEmptyRecord(getContext(), Ty, true))
8284     return ABIArgInfo::getIgnore();
8285 
8286   uint64_t Size = getContext().getTypeSize(Ty);
8287   unsigned Align = getContext().getTypeAlign(Ty);
8288 
8289   if (Size > 64)
8290     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8291 
8292   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8293     Align = Size <= 32 ? 32 : 64;
8294   if (Size <= Align) {
8295     // Pass in the smallest viable integer type.
8296     if (!llvm::isPowerOf2_64(Size))
8297       Size = llvm::NextPowerOf2(Size);
8298     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8299   }
8300   return DefaultABIInfo::classifyArgumentType(Ty);
8301 }
8302 
8303 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8304   if (RetTy->isVoidType())
8305     return ABIArgInfo::getIgnore();
8306 
8307   const TargetInfo &T = CGT.getTarget();
8308   uint64_t Size = getContext().getTypeSize(RetTy);
8309 
8310   if (RetTy->getAs<VectorType>()) {
8311     // HVX vectors are returned in vector registers or register pairs.
8312     if (T.hasFeature("hvx")) {
8313       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8314       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8315       if (Size == VecSize || Size == 2*VecSize)
8316         return ABIArgInfo::getDirectInReg();
8317     }
8318     // Large vector types should be returned via memory.
8319     if (Size > 64)
8320       return getNaturalAlignIndirect(RetTy);
8321   }
8322 
8323   if (!isAggregateTypeForABI(RetTy)) {
8324     // Treat an enum type as its underlying type.
8325     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8326       RetTy = EnumTy->getDecl()->getIntegerType();
8327 
8328     if (Size > 64 && RetTy->isExtIntType())
8329       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8330 
8331     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8332                                                 : ABIArgInfo::getDirect();
8333   }
8334 
8335   if (isEmptyRecord(getContext(), RetTy, true))
8336     return ABIArgInfo::getIgnore();
8337 
8338   // Aggregates <= 8 bytes are returned in registers, other aggregates
8339   // are returned indirectly.
8340   if (Size <= 64) {
8341     // Return in the smallest viable integer type.
8342     if (!llvm::isPowerOf2_64(Size))
8343       Size = llvm::NextPowerOf2(Size);
8344     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8345   }
8346   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8347 }
8348 
8349 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8350                                             Address VAListAddr,
8351                                             QualType Ty) const {
8352   // Load the overflow area pointer.
8353   Address __overflow_area_pointer_p =
8354       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8355   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8356       __overflow_area_pointer_p, "__overflow_area_pointer");
8357 
8358   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8359   if (Align > 4) {
8360     // Alignment should be a power of 2.
8361     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8362 
8363     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8364     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8365 
8366     // Add offset to the current pointer to access the argument.
8367     __overflow_area_pointer =
8368         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8369     llvm::Value *AsInt =
8370         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8371 
8372     // Create a mask which should be "AND"ed
8373     // with (overflow_arg_area + align - 1)
8374     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8375     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8376         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8377         "__overflow_area_pointer.align");
8378   }
8379 
8380   // Get the type of the argument from memory and bitcast
8381   // overflow area pointer to the argument type.
8382   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8383   Address AddrTyped = CGF.Builder.CreateBitCast(
8384       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8385       llvm::PointerType::getUnqual(PTy));
8386 
8387   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8388   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8389 
8390   __overflow_area_pointer = CGF.Builder.CreateGEP(
8391       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8392       "__overflow_area_pointer.next");
8393   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8394 
8395   return AddrTyped;
8396 }
8397 
8398 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8399                                             Address VAListAddr,
8400                                             QualType Ty) const {
8401   // FIXME: Need to handle alignment
8402   llvm::Type *BP = CGF.Int8PtrTy;
8403   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8404   CGBuilderTy &Builder = CGF.Builder;
8405   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8406   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8407   // Handle address alignment for type alignment > 32 bits
8408   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8409   if (TyAlign > 4) {
8410     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8411     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8412     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8413     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8414     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8415   }
8416   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8417   Address AddrTyped = Builder.CreateBitCast(
8418       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8419 
8420   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8421   llvm::Value *NextAddr = Builder.CreateGEP(
8422       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8423   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8424 
8425   return AddrTyped;
8426 }
8427 
8428 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8429                                                  Address VAListAddr,
8430                                                  QualType Ty) const {
8431   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8432 
8433   if (ArgSize > 8)
8434     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8435 
8436   // Here we have check if the argument is in register area or
8437   // in overflow area.
8438   // If the saved register area pointer + argsize rounded up to alignment >
8439   // saved register area end pointer, argument is in overflow area.
8440   unsigned RegsLeft = 6;
8441   Ty = CGF.getContext().getCanonicalType(Ty);
8442   (void)classifyArgumentType(Ty, &RegsLeft);
8443 
8444   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8445   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8446   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8447   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8448 
8449   // Get rounded size of the argument.GCC does not allow vararg of
8450   // size < 4 bytes. We follow the same logic here.
8451   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8452   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8453 
8454   // Argument may be in saved register area
8455   CGF.EmitBlock(MaybeRegBlock);
8456 
8457   // Load the current saved register area pointer.
8458   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8459       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8460   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8461       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8462 
8463   // Load the saved register area end pointer.
8464   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8465       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8466   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8467       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8468 
8469   // If the size of argument is > 4 bytes, check if the stack
8470   // location is aligned to 8 bytes
8471   if (ArgAlign > 4) {
8472 
8473     llvm::Value *__current_saved_reg_area_pointer_int =
8474         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8475                                    CGF.Int32Ty);
8476 
8477     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8478         __current_saved_reg_area_pointer_int,
8479         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8480         "align_current_saved_reg_area_pointer");
8481 
8482     __current_saved_reg_area_pointer_int =
8483         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8484                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8485                               "align_current_saved_reg_area_pointer");
8486 
8487     __current_saved_reg_area_pointer =
8488         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8489                                    __current_saved_reg_area_pointer->getType(),
8490                                    "align_current_saved_reg_area_pointer");
8491   }
8492 
8493   llvm::Value *__new_saved_reg_area_pointer =
8494       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8495                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8496                             "__new_saved_reg_area_pointer");
8497 
8498   llvm::Value *UsingStack = 0;
8499   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8500                                          __saved_reg_area_end_pointer);
8501 
8502   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8503 
8504   // Argument in saved register area
8505   // Implement the block where argument is in register saved area
8506   CGF.EmitBlock(InRegBlock);
8507 
8508   llvm::Type *PTy = CGF.ConvertType(Ty);
8509   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8510       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8511 
8512   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8513                           __current_saved_reg_area_pointer_p);
8514 
8515   CGF.EmitBranch(ContBlock);
8516 
8517   // Argument in overflow area
8518   // Implement the block where the argument is in overflow area.
8519   CGF.EmitBlock(OnStackBlock);
8520 
8521   // Load the overflow area pointer
8522   Address __overflow_area_pointer_p =
8523       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8524   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8525       __overflow_area_pointer_p, "__overflow_area_pointer");
8526 
8527   // Align the overflow area pointer according to the alignment of the argument
8528   if (ArgAlign > 4) {
8529     llvm::Value *__overflow_area_pointer_int =
8530         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8531 
8532     __overflow_area_pointer_int =
8533         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8534                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8535                               "align_overflow_area_pointer");
8536 
8537     __overflow_area_pointer_int =
8538         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8539                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8540                               "align_overflow_area_pointer");
8541 
8542     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8543         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8544         "align_overflow_area_pointer");
8545   }
8546 
8547   // Get the pointer for next argument in overflow area and store it
8548   // to overflow area pointer.
8549   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8550       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8551       "__overflow_area_pointer.next");
8552 
8553   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8554                           __overflow_area_pointer_p);
8555 
8556   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8557                           __current_saved_reg_area_pointer_p);
8558 
8559   // Bitcast the overflow area pointer to the type of argument.
8560   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8561   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8562       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8563 
8564   CGF.EmitBranch(ContBlock);
8565 
8566   // Get the correct pointer to load the variable argument
8567   // Implement the ContBlock
8568   CGF.EmitBlock(ContBlock);
8569 
8570   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8571   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8572   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8573   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8574 
8575   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8576 }
8577 
8578 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8579                                   QualType Ty) const {
8580 
8581   if (getTarget().getTriple().isMusl())
8582     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8583 
8584   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8585 }
8586 
8587 //===----------------------------------------------------------------------===//
8588 // Lanai ABI Implementation
8589 //===----------------------------------------------------------------------===//
8590 
8591 namespace {
8592 class LanaiABIInfo : public DefaultABIInfo {
8593 public:
8594   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8595 
8596   bool shouldUseInReg(QualType Ty, CCState &State) const;
8597 
8598   void computeInfo(CGFunctionInfo &FI) const override {
8599     CCState State(FI);
8600     // Lanai uses 4 registers to pass arguments unless the function has the
8601     // regparm attribute set.
8602     if (FI.getHasRegParm()) {
8603       State.FreeRegs = FI.getRegParm();
8604     } else {
8605       State.FreeRegs = 4;
8606     }
8607 
8608     if (!getCXXABI().classifyReturnType(FI))
8609       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8610     for (auto &I : FI.arguments())
8611       I.info = classifyArgumentType(I.type, State);
8612   }
8613 
8614   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8615   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8616 };
8617 } // end anonymous namespace
8618 
8619 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8620   unsigned Size = getContext().getTypeSize(Ty);
8621   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8622 
8623   if (SizeInRegs == 0)
8624     return false;
8625 
8626   if (SizeInRegs > State.FreeRegs) {
8627     State.FreeRegs = 0;
8628     return false;
8629   }
8630 
8631   State.FreeRegs -= SizeInRegs;
8632 
8633   return true;
8634 }
8635 
8636 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8637                                            CCState &State) const {
8638   if (!ByVal) {
8639     if (State.FreeRegs) {
8640       --State.FreeRegs; // Non-byval indirects just use one pointer.
8641       return getNaturalAlignIndirectInReg(Ty);
8642     }
8643     return getNaturalAlignIndirect(Ty, false);
8644   }
8645 
8646   // Compute the byval alignment.
8647   const unsigned MinABIStackAlignInBytes = 4;
8648   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8649   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8650                                  /*Realign=*/TypeAlign >
8651                                      MinABIStackAlignInBytes);
8652 }
8653 
8654 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8655                                               CCState &State) const {
8656   // Check with the C++ ABI first.
8657   const RecordType *RT = Ty->getAs<RecordType>();
8658   if (RT) {
8659     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8660     if (RAA == CGCXXABI::RAA_Indirect) {
8661       return getIndirectResult(Ty, /*ByVal=*/false, State);
8662     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8663       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8664     }
8665   }
8666 
8667   if (isAggregateTypeForABI(Ty)) {
8668     // Structures with flexible arrays are always indirect.
8669     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8670       return getIndirectResult(Ty, /*ByVal=*/true, State);
8671 
8672     // Ignore empty structs/unions.
8673     if (isEmptyRecord(getContext(), Ty, true))
8674       return ABIArgInfo::getIgnore();
8675 
8676     llvm::LLVMContext &LLVMContext = getVMContext();
8677     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8678     if (SizeInRegs <= State.FreeRegs) {
8679       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8680       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8681       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8682       State.FreeRegs -= SizeInRegs;
8683       return ABIArgInfo::getDirectInReg(Result);
8684     } else {
8685       State.FreeRegs = 0;
8686     }
8687     return getIndirectResult(Ty, true, State);
8688   }
8689 
8690   // Treat an enum type as its underlying type.
8691   if (const auto *EnumTy = Ty->getAs<EnumType>())
8692     Ty = EnumTy->getDecl()->getIntegerType();
8693 
8694   bool InReg = shouldUseInReg(Ty, State);
8695 
8696   // Don't pass >64 bit integers in registers.
8697   if (const auto *EIT = Ty->getAs<ExtIntType>())
8698     if (EIT->getNumBits() > 64)
8699       return getIndirectResult(Ty, /*ByVal=*/true, State);
8700 
8701   if (isPromotableIntegerTypeForABI(Ty)) {
8702     if (InReg)
8703       return ABIArgInfo::getDirectInReg();
8704     return ABIArgInfo::getExtend(Ty);
8705   }
8706   if (InReg)
8707     return ABIArgInfo::getDirectInReg();
8708   return ABIArgInfo::getDirect();
8709 }
8710 
8711 namespace {
8712 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8713 public:
8714   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8715       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8716 };
8717 }
8718 
8719 //===----------------------------------------------------------------------===//
8720 // AMDGPU ABI Implementation
8721 //===----------------------------------------------------------------------===//
8722 
8723 namespace {
8724 
8725 class AMDGPUABIInfo final : public DefaultABIInfo {
8726 private:
8727   static const unsigned MaxNumRegsForArgsRet = 16;
8728 
8729   unsigned numRegsForType(QualType Ty) const;
8730 
8731   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8732   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8733                                          uint64_t Members) const override;
8734 
8735   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8736   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8737                                        unsigned ToAS) const {
8738     // Single value types.
8739     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8740       return llvm::PointerType::get(
8741           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8742     return Ty;
8743   }
8744 
8745 public:
8746   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8747     DefaultABIInfo(CGT) {}
8748 
8749   ABIArgInfo classifyReturnType(QualType RetTy) const;
8750   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8751   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8752 
8753   void computeInfo(CGFunctionInfo &FI) const override;
8754   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8755                     QualType Ty) const override;
8756 };
8757 
8758 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8759   return true;
8760 }
8761 
8762 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8763   const Type *Base, uint64_t Members) const {
8764   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8765 
8766   // Homogeneous Aggregates may occupy at most 16 registers.
8767   return Members * NumRegs <= MaxNumRegsForArgsRet;
8768 }
8769 
8770 /// Estimate number of registers the type will use when passed in registers.
8771 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8772   unsigned NumRegs = 0;
8773 
8774   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8775     // Compute from the number of elements. The reported size is based on the
8776     // in-memory size, which includes the padding 4th element for 3-vectors.
8777     QualType EltTy = VT->getElementType();
8778     unsigned EltSize = getContext().getTypeSize(EltTy);
8779 
8780     // 16-bit element vectors should be passed as packed.
8781     if (EltSize == 16)
8782       return (VT->getNumElements() + 1) / 2;
8783 
8784     unsigned EltNumRegs = (EltSize + 31) / 32;
8785     return EltNumRegs * VT->getNumElements();
8786   }
8787 
8788   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8789     const RecordDecl *RD = RT->getDecl();
8790     assert(!RD->hasFlexibleArrayMember());
8791 
8792     for (const FieldDecl *Field : RD->fields()) {
8793       QualType FieldTy = Field->getType();
8794       NumRegs += numRegsForType(FieldTy);
8795     }
8796 
8797     return NumRegs;
8798   }
8799 
8800   return (getContext().getTypeSize(Ty) + 31) / 32;
8801 }
8802 
8803 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8804   llvm::CallingConv::ID CC = FI.getCallingConvention();
8805 
8806   if (!getCXXABI().classifyReturnType(FI))
8807     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8808 
8809   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8810   for (auto &Arg : FI.arguments()) {
8811     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8812       Arg.info = classifyKernelArgumentType(Arg.type);
8813     } else {
8814       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8815     }
8816   }
8817 }
8818 
8819 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8820                                  QualType Ty) const {
8821   llvm_unreachable("AMDGPU does not support varargs");
8822 }
8823 
8824 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8825   if (isAggregateTypeForABI(RetTy)) {
8826     // Records with non-trivial destructors/copy-constructors should not be
8827     // returned by value.
8828     if (!getRecordArgABI(RetTy, getCXXABI())) {
8829       // Ignore empty structs/unions.
8830       if (isEmptyRecord(getContext(), RetTy, true))
8831         return ABIArgInfo::getIgnore();
8832 
8833       // Lower single-element structs to just return a regular value.
8834       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8835         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8836 
8837       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8838         const RecordDecl *RD = RT->getDecl();
8839         if (RD->hasFlexibleArrayMember())
8840           return DefaultABIInfo::classifyReturnType(RetTy);
8841       }
8842 
8843       // Pack aggregates <= 4 bytes into single VGPR or pair.
8844       uint64_t Size = getContext().getTypeSize(RetTy);
8845       if (Size <= 16)
8846         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8847 
8848       if (Size <= 32)
8849         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8850 
8851       if (Size <= 64) {
8852         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8853         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8854       }
8855 
8856       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8857         return ABIArgInfo::getDirect();
8858     }
8859   }
8860 
8861   // Otherwise just do the default thing.
8862   return DefaultABIInfo::classifyReturnType(RetTy);
8863 }
8864 
8865 /// For kernels all parameters are really passed in a special buffer. It doesn't
8866 /// make sense to pass anything byval, so everything must be direct.
8867 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8868   Ty = useFirstFieldIfTransparentUnion(Ty);
8869 
8870   // TODO: Can we omit empty structs?
8871 
8872   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8873     Ty = QualType(SeltTy, 0);
8874 
8875   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8876   llvm::Type *LTy = OrigLTy;
8877   if (getContext().getLangOpts().HIP) {
8878     LTy = coerceKernelArgumentType(
8879         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8880         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8881   }
8882 
8883   // FIXME: Should also use this for OpenCL, but it requires addressing the
8884   // problem of kernels being called.
8885   //
8886   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8887   // to global address space when using byref. This would require implementing a
8888   // new kind of coercion of the in-memory type when for indirect arguments.
8889   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8890       isAggregateTypeForABI(Ty)) {
8891     return ABIArgInfo::getIndirectAliased(
8892         getContext().getTypeAlignInChars(Ty),
8893         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8894         false /*Realign*/, nullptr /*Padding*/);
8895   }
8896 
8897   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8898   // individual elements, which confuses the Clover OpenCL backend; therefore we
8899   // have to set it to false here. Other args of getDirect() are just defaults.
8900   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8901 }
8902 
8903 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8904                                                unsigned &NumRegsLeft) const {
8905   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8906 
8907   Ty = useFirstFieldIfTransparentUnion(Ty);
8908 
8909   if (isAggregateTypeForABI(Ty)) {
8910     // Records with non-trivial destructors/copy-constructors should not be
8911     // passed by value.
8912     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8913       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8914 
8915     // Ignore empty structs/unions.
8916     if (isEmptyRecord(getContext(), Ty, true))
8917       return ABIArgInfo::getIgnore();
8918 
8919     // Lower single-element structs to just pass a regular value. TODO: We
8920     // could do reasonable-size multiple-element structs too, using getExpand(),
8921     // though watch out for things like bitfields.
8922     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8923       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8924 
8925     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8926       const RecordDecl *RD = RT->getDecl();
8927       if (RD->hasFlexibleArrayMember())
8928         return DefaultABIInfo::classifyArgumentType(Ty);
8929     }
8930 
8931     // Pack aggregates <= 8 bytes into single VGPR or pair.
8932     uint64_t Size = getContext().getTypeSize(Ty);
8933     if (Size <= 64) {
8934       unsigned NumRegs = (Size + 31) / 32;
8935       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8936 
8937       if (Size <= 16)
8938         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8939 
8940       if (Size <= 32)
8941         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8942 
8943       // XXX: Should this be i64 instead, and should the limit increase?
8944       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8945       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8946     }
8947 
8948     if (NumRegsLeft > 0) {
8949       unsigned NumRegs = numRegsForType(Ty);
8950       if (NumRegsLeft >= NumRegs) {
8951         NumRegsLeft -= NumRegs;
8952         return ABIArgInfo::getDirect();
8953       }
8954     }
8955   }
8956 
8957   // Otherwise just do the default thing.
8958   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8959   if (!ArgInfo.isIndirect()) {
8960     unsigned NumRegs = numRegsForType(Ty);
8961     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8962   }
8963 
8964   return ArgInfo;
8965 }
8966 
8967 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8968 public:
8969   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8970       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8971   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8972                            CodeGen::CodeGenModule &M) const override;
8973   unsigned getOpenCLKernelCallingConv() const override;
8974 
8975   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8976       llvm::PointerType *T, QualType QT) const override;
8977 
8978   LangAS getASTAllocaAddressSpace() const override {
8979     return getLangASFromTargetAS(
8980         getABIInfo().getDataLayout().getAllocaAddrSpace());
8981   }
8982   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8983                                   const VarDecl *D) const override;
8984   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8985                                          SyncScope Scope,
8986                                          llvm::AtomicOrdering Ordering,
8987                                          llvm::LLVMContext &Ctx) const override;
8988   llvm::Function *
8989   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8990                             llvm::Function *BlockInvokeFunc,
8991                             llvm::Value *BlockLiteral) const override;
8992   bool shouldEmitStaticExternCAliases() const override;
8993   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8994 };
8995 }
8996 
8997 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8998                                               llvm::GlobalValue *GV) {
8999   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9000     return false;
9001 
9002   return D->hasAttr<OpenCLKernelAttr>() ||
9003          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9004          (isa<VarDecl>(D) &&
9005           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9006            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9007            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9008 }
9009 
9010 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9011     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9012   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9013     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9014     GV->setDSOLocal(true);
9015   }
9016 
9017   if (GV->isDeclaration())
9018     return;
9019   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9020   if (!FD)
9021     return;
9022 
9023   llvm::Function *F = cast<llvm::Function>(GV);
9024 
9025   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
9026     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9027 
9028 
9029   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
9030                               FD->hasAttr<OpenCLKernelAttr>();
9031   const bool IsHIPKernel = M.getLangOpts().HIP &&
9032                            FD->hasAttr<CUDAGlobalAttr>();
9033   if ((IsOpenCLKernel || IsHIPKernel) &&
9034       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
9035     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
9036 
9037   if (IsHIPKernel)
9038     F->addFnAttr("uniform-work-group-size", "true");
9039 
9040 
9041   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9042   if (ReqdWGS || FlatWGS) {
9043     unsigned Min = 0;
9044     unsigned Max = 0;
9045     if (FlatWGS) {
9046       Min = FlatWGS->getMin()
9047                 ->EvaluateKnownConstInt(M.getContext())
9048                 .getExtValue();
9049       Max = FlatWGS->getMax()
9050                 ->EvaluateKnownConstInt(M.getContext())
9051                 .getExtValue();
9052     }
9053     if (ReqdWGS && Min == 0 && Max == 0)
9054       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9055 
9056     if (Min != 0) {
9057       assert(Min <= Max && "Min must be less than or equal Max");
9058 
9059       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9060       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9061     } else
9062       assert(Max == 0 && "Max must be zero");
9063   } else if (IsOpenCLKernel || IsHIPKernel) {
9064     // By default, restrict the maximum size to a value specified by
9065     // --gpu-max-threads-per-block=n or its default value for HIP.
9066     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9067     const unsigned DefaultMaxWorkGroupSize =
9068         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9069                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9070     std::string AttrVal =
9071         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9072     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9073   }
9074 
9075   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9076     unsigned Min =
9077         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9078     unsigned Max = Attr->getMax() ? Attr->getMax()
9079                                         ->EvaluateKnownConstInt(M.getContext())
9080                                         .getExtValue()
9081                                   : 0;
9082 
9083     if (Min != 0) {
9084       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9085 
9086       std::string AttrVal = llvm::utostr(Min);
9087       if (Max != 0)
9088         AttrVal = AttrVal + "," + llvm::utostr(Max);
9089       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9090     } else
9091       assert(Max == 0 && "Max must be zero");
9092   }
9093 
9094   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9095     unsigned NumSGPR = Attr->getNumSGPR();
9096 
9097     if (NumSGPR != 0)
9098       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9099   }
9100 
9101   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9102     uint32_t NumVGPR = Attr->getNumVGPR();
9103 
9104     if (NumVGPR != 0)
9105       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9106   }
9107 
9108   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9109     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9110 }
9111 
9112 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9113   return llvm::CallingConv::AMDGPU_KERNEL;
9114 }
9115 
9116 // Currently LLVM assumes null pointers always have value 0,
9117 // which results in incorrectly transformed IR. Therefore, instead of
9118 // emitting null pointers in private and local address spaces, a null
9119 // pointer in generic address space is emitted which is casted to a
9120 // pointer in local or private address space.
9121 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9122     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9123     QualType QT) const {
9124   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9125     return llvm::ConstantPointerNull::get(PT);
9126 
9127   auto &Ctx = CGM.getContext();
9128   auto NPT = llvm::PointerType::get(PT->getElementType(),
9129       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9130   return llvm::ConstantExpr::getAddrSpaceCast(
9131       llvm::ConstantPointerNull::get(NPT), PT);
9132 }
9133 
9134 LangAS
9135 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9136                                                   const VarDecl *D) const {
9137   assert(!CGM.getLangOpts().OpenCL &&
9138          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9139          "Address space agnostic languages only");
9140   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9141       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9142   if (!D)
9143     return DefaultGlobalAS;
9144 
9145   LangAS AddrSpace = D->getType().getAddressSpace();
9146   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9147   if (AddrSpace != LangAS::Default)
9148     return AddrSpace;
9149 
9150   if (CGM.isTypeConstant(D->getType(), false)) {
9151     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9152       return ConstAS.getValue();
9153   }
9154   return DefaultGlobalAS;
9155 }
9156 
9157 llvm::SyncScope::ID
9158 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9159                                             SyncScope Scope,
9160                                             llvm::AtomicOrdering Ordering,
9161                                             llvm::LLVMContext &Ctx) const {
9162   std::string Name;
9163   switch (Scope) {
9164   case SyncScope::OpenCLWorkGroup:
9165     Name = "workgroup";
9166     break;
9167   case SyncScope::OpenCLDevice:
9168     Name = "agent";
9169     break;
9170   case SyncScope::OpenCLAllSVMDevices:
9171     Name = "";
9172     break;
9173   case SyncScope::OpenCLSubGroup:
9174     Name = "wavefront";
9175   }
9176 
9177   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9178     if (!Name.empty())
9179       Name = Twine(Twine(Name) + Twine("-")).str();
9180 
9181     Name = Twine(Twine(Name) + Twine("one-as")).str();
9182   }
9183 
9184   return Ctx.getOrInsertSyncScopeID(Name);
9185 }
9186 
9187 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9188   return false;
9189 }
9190 
9191 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9192     const FunctionType *&FT) const {
9193   FT = getABIInfo().getContext().adjustFunctionType(
9194       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9195 }
9196 
9197 //===----------------------------------------------------------------------===//
9198 // SPARC v8 ABI Implementation.
9199 // Based on the SPARC Compliance Definition version 2.4.1.
9200 //
9201 // Ensures that complex values are passed in registers.
9202 //
9203 namespace {
9204 class SparcV8ABIInfo : public DefaultABIInfo {
9205 public:
9206   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9207 
9208 private:
9209   ABIArgInfo classifyReturnType(QualType RetTy) const;
9210   void computeInfo(CGFunctionInfo &FI) const override;
9211 };
9212 } // end anonymous namespace
9213 
9214 
9215 ABIArgInfo
9216 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9217   if (Ty->isAnyComplexType()) {
9218     return ABIArgInfo::getDirect();
9219   }
9220   else {
9221     return DefaultABIInfo::classifyReturnType(Ty);
9222   }
9223 }
9224 
9225 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9226 
9227   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9228   for (auto &Arg : FI.arguments())
9229     Arg.info = classifyArgumentType(Arg.type);
9230 }
9231 
9232 namespace {
9233 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9234 public:
9235   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9236       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9237 };
9238 } // end anonymous namespace
9239 
9240 //===----------------------------------------------------------------------===//
9241 // SPARC v9 ABI Implementation.
9242 // Based on the SPARC Compliance Definition version 2.4.1.
9243 //
9244 // Function arguments a mapped to a nominal "parameter array" and promoted to
9245 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9246 // the array, structs larger than 16 bytes are passed indirectly.
9247 //
9248 // One case requires special care:
9249 //
9250 //   struct mixed {
9251 //     int i;
9252 //     float f;
9253 //   };
9254 //
9255 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9256 // parameter array, but the int is passed in an integer register, and the float
9257 // is passed in a floating point register. This is represented as two arguments
9258 // with the LLVM IR inreg attribute:
9259 //
9260 //   declare void f(i32 inreg %i, float inreg %f)
9261 //
9262 // The code generator will only allocate 4 bytes from the parameter array for
9263 // the inreg arguments. All other arguments are allocated a multiple of 8
9264 // bytes.
9265 //
9266 namespace {
9267 class SparcV9ABIInfo : public ABIInfo {
9268 public:
9269   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9270 
9271 private:
9272   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9273   void computeInfo(CGFunctionInfo &FI) const override;
9274   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9275                     QualType Ty) const override;
9276 
9277   // Coercion type builder for structs passed in registers. The coercion type
9278   // serves two purposes:
9279   //
9280   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9281   //    in registers.
9282   // 2. Expose aligned floating point elements as first-level elements, so the
9283   //    code generator knows to pass them in floating point registers.
9284   //
9285   // We also compute the InReg flag which indicates that the struct contains
9286   // aligned 32-bit floats.
9287   //
9288   struct CoerceBuilder {
9289     llvm::LLVMContext &Context;
9290     const llvm::DataLayout &DL;
9291     SmallVector<llvm::Type*, 8> Elems;
9292     uint64_t Size;
9293     bool InReg;
9294 
9295     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9296       : Context(c), DL(dl), Size(0), InReg(false) {}
9297 
9298     // Pad Elems with integers until Size is ToSize.
9299     void pad(uint64_t ToSize) {
9300       assert(ToSize >= Size && "Cannot remove elements");
9301       if (ToSize == Size)
9302         return;
9303 
9304       // Finish the current 64-bit word.
9305       uint64_t Aligned = llvm::alignTo(Size, 64);
9306       if (Aligned > Size && Aligned <= ToSize) {
9307         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9308         Size = Aligned;
9309       }
9310 
9311       // Add whole 64-bit words.
9312       while (Size + 64 <= ToSize) {
9313         Elems.push_back(llvm::Type::getInt64Ty(Context));
9314         Size += 64;
9315       }
9316 
9317       // Final in-word padding.
9318       if (Size < ToSize) {
9319         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9320         Size = ToSize;
9321       }
9322     }
9323 
9324     // Add a floating point element at Offset.
9325     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9326       // Unaligned floats are treated as integers.
9327       if (Offset % Bits)
9328         return;
9329       // The InReg flag is only required if there are any floats < 64 bits.
9330       if (Bits < 64)
9331         InReg = true;
9332       pad(Offset);
9333       Elems.push_back(Ty);
9334       Size = Offset + Bits;
9335     }
9336 
9337     // Add a struct type to the coercion type, starting at Offset (in bits).
9338     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9339       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9340       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9341         llvm::Type *ElemTy = StrTy->getElementType(i);
9342         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9343         switch (ElemTy->getTypeID()) {
9344         case llvm::Type::StructTyID:
9345           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9346           break;
9347         case llvm::Type::FloatTyID:
9348           addFloat(ElemOffset, ElemTy, 32);
9349           break;
9350         case llvm::Type::DoubleTyID:
9351           addFloat(ElemOffset, ElemTy, 64);
9352           break;
9353         case llvm::Type::FP128TyID:
9354           addFloat(ElemOffset, ElemTy, 128);
9355           break;
9356         case llvm::Type::PointerTyID:
9357           if (ElemOffset % 64 == 0) {
9358             pad(ElemOffset);
9359             Elems.push_back(ElemTy);
9360             Size += 64;
9361           }
9362           break;
9363         default:
9364           break;
9365         }
9366       }
9367     }
9368 
9369     // Check if Ty is a usable substitute for the coercion type.
9370     bool isUsableType(llvm::StructType *Ty) const {
9371       return llvm::makeArrayRef(Elems) == Ty->elements();
9372     }
9373 
9374     // Get the coercion type as a literal struct type.
9375     llvm::Type *getType() const {
9376       if (Elems.size() == 1)
9377         return Elems.front();
9378       else
9379         return llvm::StructType::get(Context, Elems);
9380     }
9381   };
9382 };
9383 } // end anonymous namespace
9384 
9385 ABIArgInfo
9386 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9387   if (Ty->isVoidType())
9388     return ABIArgInfo::getIgnore();
9389 
9390   uint64_t Size = getContext().getTypeSize(Ty);
9391 
9392   // Anything too big to fit in registers is passed with an explicit indirect
9393   // pointer / sret pointer.
9394   if (Size > SizeLimit)
9395     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9396 
9397   // Treat an enum type as its underlying type.
9398   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9399     Ty = EnumTy->getDecl()->getIntegerType();
9400 
9401   // Integer types smaller than a register are extended.
9402   if (Size < 64 && Ty->isIntegerType())
9403     return ABIArgInfo::getExtend(Ty);
9404 
9405   if (const auto *EIT = Ty->getAs<ExtIntType>())
9406     if (EIT->getNumBits() < 64)
9407       return ABIArgInfo::getExtend(Ty);
9408 
9409   // Other non-aggregates go in registers.
9410   if (!isAggregateTypeForABI(Ty))
9411     return ABIArgInfo::getDirect();
9412 
9413   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9414   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9415   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9416     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9417 
9418   // This is a small aggregate type that should be passed in registers.
9419   // Build a coercion type from the LLVM struct type.
9420   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9421   if (!StrTy)
9422     return ABIArgInfo::getDirect();
9423 
9424   CoerceBuilder CB(getVMContext(), getDataLayout());
9425   CB.addStruct(0, StrTy);
9426   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9427 
9428   // Try to use the original type for coercion.
9429   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9430 
9431   if (CB.InReg)
9432     return ABIArgInfo::getDirectInReg(CoerceTy);
9433   else
9434     return ABIArgInfo::getDirect(CoerceTy);
9435 }
9436 
9437 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9438                                   QualType Ty) const {
9439   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9440   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9441   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9442     AI.setCoerceToType(ArgTy);
9443 
9444   CharUnits SlotSize = CharUnits::fromQuantity(8);
9445 
9446   CGBuilderTy &Builder = CGF.Builder;
9447   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9448   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9449 
9450   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9451 
9452   Address ArgAddr = Address::invalid();
9453   CharUnits Stride;
9454   switch (AI.getKind()) {
9455   case ABIArgInfo::Expand:
9456   case ABIArgInfo::CoerceAndExpand:
9457   case ABIArgInfo::InAlloca:
9458     llvm_unreachable("Unsupported ABI kind for va_arg");
9459 
9460   case ABIArgInfo::Extend: {
9461     Stride = SlotSize;
9462     CharUnits Offset = SlotSize - TypeInfo.Width;
9463     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9464     break;
9465   }
9466 
9467   case ABIArgInfo::Direct: {
9468     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9469     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9470     ArgAddr = Addr;
9471     break;
9472   }
9473 
9474   case ABIArgInfo::Indirect:
9475   case ABIArgInfo::IndirectAliased:
9476     Stride = SlotSize;
9477     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9478     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9479                       TypeInfo.Align);
9480     break;
9481 
9482   case ABIArgInfo::Ignore:
9483     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9484   }
9485 
9486   // Update VAList.
9487   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9488   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9489 
9490   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9491 }
9492 
9493 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9494   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9495   for (auto &I : FI.arguments())
9496     I.info = classifyType(I.type, 16 * 8);
9497 }
9498 
9499 namespace {
9500 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9501 public:
9502   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9503       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9504 
9505   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9506     return 14;
9507   }
9508 
9509   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9510                                llvm::Value *Address) const override;
9511 };
9512 } // end anonymous namespace
9513 
9514 bool
9515 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9516                                                 llvm::Value *Address) const {
9517   // This is calculated from the LLVM and GCC tables and verified
9518   // against gcc output.  AFAIK all ABIs use the same encoding.
9519 
9520   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9521 
9522   llvm::IntegerType *i8 = CGF.Int8Ty;
9523   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9524   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9525 
9526   // 0-31: the 8-byte general-purpose registers
9527   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9528 
9529   // 32-63: f0-31, the 4-byte floating-point registers
9530   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9531 
9532   //   Y   = 64
9533   //   PSR = 65
9534   //   WIM = 66
9535   //   TBR = 67
9536   //   PC  = 68
9537   //   NPC = 69
9538   //   FSR = 70
9539   //   CSR = 71
9540   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9541 
9542   // 72-87: d0-15, the 8-byte floating-point registers
9543   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9544 
9545   return false;
9546 }
9547 
9548 // ARC ABI implementation.
9549 namespace {
9550 
9551 class ARCABIInfo : public DefaultABIInfo {
9552 public:
9553   using DefaultABIInfo::DefaultABIInfo;
9554 
9555 private:
9556   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9557                     QualType Ty) const override;
9558 
9559   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9560     if (!State.FreeRegs)
9561       return;
9562     if (Info.isIndirect() && Info.getInReg())
9563       State.FreeRegs--;
9564     else if (Info.isDirect() && Info.getInReg()) {
9565       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9566       if (sz < State.FreeRegs)
9567         State.FreeRegs -= sz;
9568       else
9569         State.FreeRegs = 0;
9570     }
9571   }
9572 
9573   void computeInfo(CGFunctionInfo &FI) const override {
9574     CCState State(FI);
9575     // ARC uses 8 registers to pass arguments.
9576     State.FreeRegs = 8;
9577 
9578     if (!getCXXABI().classifyReturnType(FI))
9579       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9580     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9581     for (auto &I : FI.arguments()) {
9582       I.info = classifyArgumentType(I.type, State.FreeRegs);
9583       updateState(I.info, I.type, State);
9584     }
9585   }
9586 
9587   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9588   ABIArgInfo getIndirectByValue(QualType Ty) const;
9589   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9590   ABIArgInfo classifyReturnType(QualType RetTy) const;
9591 };
9592 
9593 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9594 public:
9595   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9596       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9597 };
9598 
9599 
9600 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9601   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9602                        getNaturalAlignIndirect(Ty, false);
9603 }
9604 
9605 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9606   // Compute the byval alignment.
9607   const unsigned MinABIStackAlignInBytes = 4;
9608   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9609   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9610                                  TypeAlign > MinABIStackAlignInBytes);
9611 }
9612 
9613 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9614                               QualType Ty) const {
9615   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9616                           getContext().getTypeInfoInChars(Ty),
9617                           CharUnits::fromQuantity(4), true);
9618 }
9619 
9620 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9621                                             uint8_t FreeRegs) const {
9622   // Handle the generic C++ ABI.
9623   const RecordType *RT = Ty->getAs<RecordType>();
9624   if (RT) {
9625     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9626     if (RAA == CGCXXABI::RAA_Indirect)
9627       return getIndirectByRef(Ty, FreeRegs > 0);
9628 
9629     if (RAA == CGCXXABI::RAA_DirectInMemory)
9630       return getIndirectByValue(Ty);
9631   }
9632 
9633   // Treat an enum type as its underlying type.
9634   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9635     Ty = EnumTy->getDecl()->getIntegerType();
9636 
9637   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9638 
9639   if (isAggregateTypeForABI(Ty)) {
9640     // Structures with flexible arrays are always indirect.
9641     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9642       return getIndirectByValue(Ty);
9643 
9644     // Ignore empty structs/unions.
9645     if (isEmptyRecord(getContext(), Ty, true))
9646       return ABIArgInfo::getIgnore();
9647 
9648     llvm::LLVMContext &LLVMContext = getVMContext();
9649 
9650     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9651     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9652     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9653 
9654     return FreeRegs >= SizeInRegs ?
9655         ABIArgInfo::getDirectInReg(Result) :
9656         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9657   }
9658 
9659   if (const auto *EIT = Ty->getAs<ExtIntType>())
9660     if (EIT->getNumBits() > 64)
9661       return getIndirectByValue(Ty);
9662 
9663   return isPromotableIntegerTypeForABI(Ty)
9664              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9665                                        : ABIArgInfo::getExtend(Ty))
9666              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9667                                        : ABIArgInfo::getDirect());
9668 }
9669 
9670 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9671   if (RetTy->isAnyComplexType())
9672     return ABIArgInfo::getDirectInReg();
9673 
9674   // Arguments of size > 4 registers are indirect.
9675   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9676   if (RetSize > 4)
9677     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9678 
9679   return DefaultABIInfo::classifyReturnType(RetTy);
9680 }
9681 
9682 } // End anonymous namespace.
9683 
9684 //===----------------------------------------------------------------------===//
9685 // XCore ABI Implementation
9686 //===----------------------------------------------------------------------===//
9687 
9688 namespace {
9689 
9690 /// A SmallStringEnc instance is used to build up the TypeString by passing
9691 /// it by reference between functions that append to it.
9692 typedef llvm::SmallString<128> SmallStringEnc;
9693 
9694 /// TypeStringCache caches the meta encodings of Types.
9695 ///
9696 /// The reason for caching TypeStrings is two fold:
9697 ///   1. To cache a type's encoding for later uses;
9698 ///   2. As a means to break recursive member type inclusion.
9699 ///
9700 /// A cache Entry can have a Status of:
9701 ///   NonRecursive:   The type encoding is not recursive;
9702 ///   Recursive:      The type encoding is recursive;
9703 ///   Incomplete:     An incomplete TypeString;
9704 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9705 ///                   Recursive type encoding.
9706 ///
9707 /// A NonRecursive entry will have all of its sub-members expanded as fully
9708 /// as possible. Whilst it may contain types which are recursive, the type
9709 /// itself is not recursive and thus its encoding may be safely used whenever
9710 /// the type is encountered.
9711 ///
9712 /// A Recursive entry will have all of its sub-members expanded as fully as
9713 /// possible. The type itself is recursive and it may contain other types which
9714 /// are recursive. The Recursive encoding must not be used during the expansion
9715 /// of a recursive type's recursive branch. For simplicity the code uses
9716 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9717 ///
9718 /// An Incomplete entry is always a RecordType and only encodes its
9719 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9720 /// are placed into the cache during type expansion as a means to identify and
9721 /// handle recursive inclusion of types as sub-members. If there is recursion
9722 /// the entry becomes IncompleteUsed.
9723 ///
9724 /// During the expansion of a RecordType's members:
9725 ///
9726 ///   If the cache contains a NonRecursive encoding for the member type, the
9727 ///   cached encoding is used;
9728 ///
9729 ///   If the cache contains a Recursive encoding for the member type, the
9730 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9731 ///
9732 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9733 ///   cache to break potential recursive inclusion of itself as a sub-member;
9734 ///
9735 ///   Once a member RecordType has been expanded, its temporary incomplete
9736 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9737 ///   it is swapped back in;
9738 ///
9739 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9740 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9741 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9742 ///
9743 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9744 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9745 ///   Else the member is part of a recursive type and thus the recursion has
9746 ///   been exited too soon for the encoding to be correct for the member.
9747 ///
9748 class TypeStringCache {
9749   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9750   struct Entry {
9751     std::string Str;     // The encoded TypeString for the type.
9752     enum Status State;   // Information about the encoding in 'Str'.
9753     std::string Swapped; // A temporary place holder for a Recursive encoding
9754                          // during the expansion of RecordType's members.
9755   };
9756   std::map<const IdentifierInfo *, struct Entry> Map;
9757   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9758   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9759 public:
9760   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9761   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9762   bool removeIncomplete(const IdentifierInfo *ID);
9763   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9764                      bool IsRecursive);
9765   StringRef lookupStr(const IdentifierInfo *ID);
9766 };
9767 
9768 /// TypeString encodings for enum & union fields must be order.
9769 /// FieldEncoding is a helper for this ordering process.
9770 class FieldEncoding {
9771   bool HasName;
9772   std::string Enc;
9773 public:
9774   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9775   StringRef str() { return Enc; }
9776   bool operator<(const FieldEncoding &rhs) const {
9777     if (HasName != rhs.HasName) return HasName;
9778     return Enc < rhs.Enc;
9779   }
9780 };
9781 
9782 class XCoreABIInfo : public DefaultABIInfo {
9783 public:
9784   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9785   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9786                     QualType Ty) const override;
9787 };
9788 
9789 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9790   mutable TypeStringCache TSC;
9791   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9792                     const CodeGen::CodeGenModule &M) const;
9793 
9794 public:
9795   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9796       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9797   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9798                           const llvm::MapVector<GlobalDecl, StringRef>
9799                               &MangledDeclNames) const override;
9800 };
9801 
9802 } // End anonymous namespace.
9803 
9804 // TODO: this implementation is likely now redundant with the default
9805 // EmitVAArg.
9806 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9807                                 QualType Ty) const {
9808   CGBuilderTy &Builder = CGF.Builder;
9809 
9810   // Get the VAList.
9811   CharUnits SlotSize = CharUnits::fromQuantity(4);
9812   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9813 
9814   // Handle the argument.
9815   ABIArgInfo AI = classifyArgumentType(Ty);
9816   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9817   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9818   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9819     AI.setCoerceToType(ArgTy);
9820   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9821 
9822   Address Val = Address::invalid();
9823   CharUnits ArgSize = CharUnits::Zero();
9824   switch (AI.getKind()) {
9825   case ABIArgInfo::Expand:
9826   case ABIArgInfo::CoerceAndExpand:
9827   case ABIArgInfo::InAlloca:
9828     llvm_unreachable("Unsupported ABI kind for va_arg");
9829   case ABIArgInfo::Ignore:
9830     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9831     ArgSize = CharUnits::Zero();
9832     break;
9833   case ABIArgInfo::Extend:
9834   case ABIArgInfo::Direct:
9835     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9836     ArgSize = CharUnits::fromQuantity(
9837                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9838     ArgSize = ArgSize.alignTo(SlotSize);
9839     break;
9840   case ABIArgInfo::Indirect:
9841   case ABIArgInfo::IndirectAliased:
9842     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9843     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9844     ArgSize = SlotSize;
9845     break;
9846   }
9847 
9848   // Increment the VAList.
9849   if (!ArgSize.isZero()) {
9850     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9851     Builder.CreateStore(APN.getPointer(), VAListAddr);
9852   }
9853 
9854   return Val;
9855 }
9856 
9857 /// During the expansion of a RecordType, an incomplete TypeString is placed
9858 /// into the cache as a means to identify and break recursion.
9859 /// If there is a Recursive encoding in the cache, it is swapped out and will
9860 /// be reinserted by removeIncomplete().
9861 /// All other types of encoding should have been used rather than arriving here.
9862 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9863                                     std::string StubEnc) {
9864   if (!ID)
9865     return;
9866   Entry &E = Map[ID];
9867   assert( (E.Str.empty() || E.State == Recursive) &&
9868          "Incorrectly use of addIncomplete");
9869   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9870   E.Swapped.swap(E.Str); // swap out the Recursive
9871   E.Str.swap(StubEnc);
9872   E.State = Incomplete;
9873   ++IncompleteCount;
9874 }
9875 
9876 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9877 /// must be removed from the cache.
9878 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9879 /// Returns true if the RecordType was defined recursively.
9880 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9881   if (!ID)
9882     return false;
9883   auto I = Map.find(ID);
9884   assert(I != Map.end() && "Entry not present");
9885   Entry &E = I->second;
9886   assert( (E.State == Incomplete ||
9887            E.State == IncompleteUsed) &&
9888          "Entry must be an incomplete type");
9889   bool IsRecursive = false;
9890   if (E.State == IncompleteUsed) {
9891     // We made use of our Incomplete encoding, thus we are recursive.
9892     IsRecursive = true;
9893     --IncompleteUsedCount;
9894   }
9895   if (E.Swapped.empty())
9896     Map.erase(I);
9897   else {
9898     // Swap the Recursive back.
9899     E.Swapped.swap(E.Str);
9900     E.Swapped.clear();
9901     E.State = Recursive;
9902   }
9903   --IncompleteCount;
9904   return IsRecursive;
9905 }
9906 
9907 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9908 /// Recursive (viz: all sub-members were expanded as fully as possible).
9909 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9910                                     bool IsRecursive) {
9911   if (!ID || IncompleteUsedCount)
9912     return; // No key or it is is an incomplete sub-type so don't add.
9913   Entry &E = Map[ID];
9914   if (IsRecursive && !E.Str.empty()) {
9915     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9916            "This is not the same Recursive entry");
9917     // The parent container was not recursive after all, so we could have used
9918     // this Recursive sub-member entry after all, but we assumed the worse when
9919     // we started viz: IncompleteCount!=0.
9920     return;
9921   }
9922   assert(E.Str.empty() && "Entry already present");
9923   E.Str = Str.str();
9924   E.State = IsRecursive? Recursive : NonRecursive;
9925 }
9926 
9927 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9928 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9929 /// encoding is Recursive, return an empty StringRef.
9930 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9931   if (!ID)
9932     return StringRef();   // We have no key.
9933   auto I = Map.find(ID);
9934   if (I == Map.end())
9935     return StringRef();   // We have no encoding.
9936   Entry &E = I->second;
9937   if (E.State == Recursive && IncompleteCount)
9938     return StringRef();   // We don't use Recursive encodings for member types.
9939 
9940   if (E.State == Incomplete) {
9941     // The incomplete type is being used to break out of recursion.
9942     E.State = IncompleteUsed;
9943     ++IncompleteUsedCount;
9944   }
9945   return E.Str;
9946 }
9947 
9948 /// The XCore ABI includes a type information section that communicates symbol
9949 /// type information to the linker. The linker uses this information to verify
9950 /// safety/correctness of things such as array bound and pointers et al.
9951 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9952 /// This type information (TypeString) is emitted into meta data for all global
9953 /// symbols: definitions, declarations, functions & variables.
9954 ///
9955 /// The TypeString carries type, qualifier, name, size & value details.
9956 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9957 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9958 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9959 ///
9960 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9961                           const CodeGen::CodeGenModule &CGM,
9962                           TypeStringCache &TSC);
9963 
9964 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9965 void XCoreTargetCodeGenInfo::emitTargetMD(
9966     const Decl *D, llvm::GlobalValue *GV,
9967     const CodeGen::CodeGenModule &CGM) const {
9968   SmallStringEnc Enc;
9969   if (getTypeString(Enc, D, CGM, TSC)) {
9970     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9971     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9972                                 llvm::MDString::get(Ctx, Enc.str())};
9973     llvm::NamedMDNode *MD =
9974       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9975     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9976   }
9977 }
9978 
9979 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9980     CodeGen::CodeGenModule &CGM,
9981     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9982   // Warning, new MangledDeclNames may be appended within this loop.
9983   // We rely on MapVector insertions adding new elements to the end
9984   // of the container.
9985   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9986     auto Val = *(MangledDeclNames.begin() + I);
9987     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9988     if (GV) {
9989       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9990       emitTargetMD(D, GV, CGM);
9991     }
9992   }
9993 }
9994 //===----------------------------------------------------------------------===//
9995 // SPIR ABI Implementation
9996 //===----------------------------------------------------------------------===//
9997 
9998 namespace {
9999 class SPIRABIInfo : public DefaultABIInfo {
10000 public:
10001   SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10002 
10003 private:
10004   void setCCs();
10005 };
10006 } // end anonymous namespace
10007 namespace {
10008 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10009 public:
10010   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10011       : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
10012   unsigned getOpenCLKernelCallingConv() const override;
10013 };
10014 
10015 } // End anonymous namespace.
10016 void SPIRABIInfo::setCCs() {
10017   assert(getRuntimeCC() == llvm::CallingConv::C);
10018   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10019 }
10020 
10021 namespace clang {
10022 namespace CodeGen {
10023 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10024   DefaultABIInfo SPIRABI(CGM.getTypes());
10025   SPIRABI.computeInfo(FI);
10026 }
10027 }
10028 }
10029 
10030 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10031   return llvm::CallingConv::SPIR_KERNEL;
10032 }
10033 
10034 static bool appendType(SmallStringEnc &Enc, QualType QType,
10035                        const CodeGen::CodeGenModule &CGM,
10036                        TypeStringCache &TSC);
10037 
10038 /// Helper function for appendRecordType().
10039 /// Builds a SmallVector containing the encoded field types in declaration
10040 /// order.
10041 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10042                              const RecordDecl *RD,
10043                              const CodeGen::CodeGenModule &CGM,
10044                              TypeStringCache &TSC) {
10045   for (const auto *Field : RD->fields()) {
10046     SmallStringEnc Enc;
10047     Enc += "m(";
10048     Enc += Field->getName();
10049     Enc += "){";
10050     if (Field->isBitField()) {
10051       Enc += "b(";
10052       llvm::raw_svector_ostream OS(Enc);
10053       OS << Field->getBitWidthValue(CGM.getContext());
10054       Enc += ':';
10055     }
10056     if (!appendType(Enc, Field->getType(), CGM, TSC))
10057       return false;
10058     if (Field->isBitField())
10059       Enc += ')';
10060     Enc += '}';
10061     FE.emplace_back(!Field->getName().empty(), Enc);
10062   }
10063   return true;
10064 }
10065 
10066 /// Appends structure and union types to Enc and adds encoding to cache.
10067 /// Recursively calls appendType (via extractFieldType) for each field.
10068 /// Union types have their fields ordered according to the ABI.
10069 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10070                              const CodeGen::CodeGenModule &CGM,
10071                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10072   // Append the cached TypeString if we have one.
10073   StringRef TypeString = TSC.lookupStr(ID);
10074   if (!TypeString.empty()) {
10075     Enc += TypeString;
10076     return true;
10077   }
10078 
10079   // Start to emit an incomplete TypeString.
10080   size_t Start = Enc.size();
10081   Enc += (RT->isUnionType()? 'u' : 's');
10082   Enc += '(';
10083   if (ID)
10084     Enc += ID->getName();
10085   Enc += "){";
10086 
10087   // We collect all encoded fields and order as necessary.
10088   bool IsRecursive = false;
10089   const RecordDecl *RD = RT->getDecl()->getDefinition();
10090   if (RD && !RD->field_empty()) {
10091     // An incomplete TypeString stub is placed in the cache for this RecordType
10092     // so that recursive calls to this RecordType will use it whilst building a
10093     // complete TypeString for this RecordType.
10094     SmallVector<FieldEncoding, 16> FE;
10095     std::string StubEnc(Enc.substr(Start).str());
10096     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10097     TSC.addIncomplete(ID, std::move(StubEnc));
10098     if (!extractFieldType(FE, RD, CGM, TSC)) {
10099       (void) TSC.removeIncomplete(ID);
10100       return false;
10101     }
10102     IsRecursive = TSC.removeIncomplete(ID);
10103     // The ABI requires unions to be sorted but not structures.
10104     // See FieldEncoding::operator< for sort algorithm.
10105     if (RT->isUnionType())
10106       llvm::sort(FE);
10107     // We can now complete the TypeString.
10108     unsigned E = FE.size();
10109     for (unsigned I = 0; I != E; ++I) {
10110       if (I)
10111         Enc += ',';
10112       Enc += FE[I].str();
10113     }
10114   }
10115   Enc += '}';
10116   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10117   return true;
10118 }
10119 
10120 /// Appends enum types to Enc and adds the encoding to the cache.
10121 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10122                            TypeStringCache &TSC,
10123                            const IdentifierInfo *ID) {
10124   // Append the cached TypeString if we have one.
10125   StringRef TypeString = TSC.lookupStr(ID);
10126   if (!TypeString.empty()) {
10127     Enc += TypeString;
10128     return true;
10129   }
10130 
10131   size_t Start = Enc.size();
10132   Enc += "e(";
10133   if (ID)
10134     Enc += ID->getName();
10135   Enc += "){";
10136 
10137   // We collect all encoded enumerations and order them alphanumerically.
10138   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10139     SmallVector<FieldEncoding, 16> FE;
10140     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10141          ++I) {
10142       SmallStringEnc EnumEnc;
10143       EnumEnc += "m(";
10144       EnumEnc += I->getName();
10145       EnumEnc += "){";
10146       I->getInitVal().toString(EnumEnc);
10147       EnumEnc += '}';
10148       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10149     }
10150     llvm::sort(FE);
10151     unsigned E = FE.size();
10152     for (unsigned I = 0; I != E; ++I) {
10153       if (I)
10154         Enc += ',';
10155       Enc += FE[I].str();
10156     }
10157   }
10158   Enc += '}';
10159   TSC.addIfComplete(ID, Enc.substr(Start), false);
10160   return true;
10161 }
10162 
10163 /// Appends type's qualifier to Enc.
10164 /// This is done prior to appending the type's encoding.
10165 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10166   // Qualifiers are emitted in alphabetical order.
10167   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10168   int Lookup = 0;
10169   if (QT.isConstQualified())
10170     Lookup += 1<<0;
10171   if (QT.isRestrictQualified())
10172     Lookup += 1<<1;
10173   if (QT.isVolatileQualified())
10174     Lookup += 1<<2;
10175   Enc += Table[Lookup];
10176 }
10177 
10178 /// Appends built-in types to Enc.
10179 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10180   const char *EncType;
10181   switch (BT->getKind()) {
10182     case BuiltinType::Void:
10183       EncType = "0";
10184       break;
10185     case BuiltinType::Bool:
10186       EncType = "b";
10187       break;
10188     case BuiltinType::Char_U:
10189       EncType = "uc";
10190       break;
10191     case BuiltinType::UChar:
10192       EncType = "uc";
10193       break;
10194     case BuiltinType::SChar:
10195       EncType = "sc";
10196       break;
10197     case BuiltinType::UShort:
10198       EncType = "us";
10199       break;
10200     case BuiltinType::Short:
10201       EncType = "ss";
10202       break;
10203     case BuiltinType::UInt:
10204       EncType = "ui";
10205       break;
10206     case BuiltinType::Int:
10207       EncType = "si";
10208       break;
10209     case BuiltinType::ULong:
10210       EncType = "ul";
10211       break;
10212     case BuiltinType::Long:
10213       EncType = "sl";
10214       break;
10215     case BuiltinType::ULongLong:
10216       EncType = "ull";
10217       break;
10218     case BuiltinType::LongLong:
10219       EncType = "sll";
10220       break;
10221     case BuiltinType::Float:
10222       EncType = "ft";
10223       break;
10224     case BuiltinType::Double:
10225       EncType = "d";
10226       break;
10227     case BuiltinType::LongDouble:
10228       EncType = "ld";
10229       break;
10230     default:
10231       return false;
10232   }
10233   Enc += EncType;
10234   return true;
10235 }
10236 
10237 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10238 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10239                               const CodeGen::CodeGenModule &CGM,
10240                               TypeStringCache &TSC) {
10241   Enc += "p(";
10242   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10243     return false;
10244   Enc += ')';
10245   return true;
10246 }
10247 
10248 /// Appends array encoding to Enc before calling appendType for the element.
10249 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10250                             const ArrayType *AT,
10251                             const CodeGen::CodeGenModule &CGM,
10252                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10253   if (AT->getSizeModifier() != ArrayType::Normal)
10254     return false;
10255   Enc += "a(";
10256   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10257     CAT->getSize().toStringUnsigned(Enc);
10258   else
10259     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10260   Enc += ':';
10261   // The Qualifiers should be attached to the type rather than the array.
10262   appendQualifier(Enc, QT);
10263   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10264     return false;
10265   Enc += ')';
10266   return true;
10267 }
10268 
10269 /// Appends a function encoding to Enc, calling appendType for the return type
10270 /// and the arguments.
10271 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10272                              const CodeGen::CodeGenModule &CGM,
10273                              TypeStringCache &TSC) {
10274   Enc += "f{";
10275   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10276     return false;
10277   Enc += "}(";
10278   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10279     // N.B. we are only interested in the adjusted param types.
10280     auto I = FPT->param_type_begin();
10281     auto E = FPT->param_type_end();
10282     if (I != E) {
10283       do {
10284         if (!appendType(Enc, *I, CGM, TSC))
10285           return false;
10286         ++I;
10287         if (I != E)
10288           Enc += ',';
10289       } while (I != E);
10290       if (FPT->isVariadic())
10291         Enc += ",va";
10292     } else {
10293       if (FPT->isVariadic())
10294         Enc += "va";
10295       else
10296         Enc += '0';
10297     }
10298   }
10299   Enc += ')';
10300   return true;
10301 }
10302 
10303 /// Handles the type's qualifier before dispatching a call to handle specific
10304 /// type encodings.
10305 static bool appendType(SmallStringEnc &Enc, QualType QType,
10306                        const CodeGen::CodeGenModule &CGM,
10307                        TypeStringCache &TSC) {
10308 
10309   QualType QT = QType.getCanonicalType();
10310 
10311   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10312     // The Qualifiers should be attached to the type rather than the array.
10313     // Thus we don't call appendQualifier() here.
10314     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10315 
10316   appendQualifier(Enc, QT);
10317 
10318   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10319     return appendBuiltinType(Enc, BT);
10320 
10321   if (const PointerType *PT = QT->getAs<PointerType>())
10322     return appendPointerType(Enc, PT, CGM, TSC);
10323 
10324   if (const EnumType *ET = QT->getAs<EnumType>())
10325     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10326 
10327   if (const RecordType *RT = QT->getAsStructureType())
10328     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10329 
10330   if (const RecordType *RT = QT->getAsUnionType())
10331     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10332 
10333   if (const FunctionType *FT = QT->getAs<FunctionType>())
10334     return appendFunctionType(Enc, FT, CGM, TSC);
10335 
10336   return false;
10337 }
10338 
10339 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10340                           const CodeGen::CodeGenModule &CGM,
10341                           TypeStringCache &TSC) {
10342   if (!D)
10343     return false;
10344 
10345   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10346     if (FD->getLanguageLinkage() != CLanguageLinkage)
10347       return false;
10348     return appendType(Enc, FD->getType(), CGM, TSC);
10349   }
10350 
10351   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10352     if (VD->getLanguageLinkage() != CLanguageLinkage)
10353       return false;
10354     QualType QT = VD->getType().getCanonicalType();
10355     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10356       // Global ArrayTypes are given a size of '*' if the size is unknown.
10357       // The Qualifiers should be attached to the type rather than the array.
10358       // Thus we don't call appendQualifier() here.
10359       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10360     }
10361     return appendType(Enc, QT, CGM, TSC);
10362   }
10363   return false;
10364 }
10365 
10366 //===----------------------------------------------------------------------===//
10367 // RISCV ABI Implementation
10368 //===----------------------------------------------------------------------===//
10369 
10370 namespace {
10371 class RISCVABIInfo : public DefaultABIInfo {
10372 private:
10373   // Size of the integer ('x') registers in bits.
10374   unsigned XLen;
10375   // Size of the floating point ('f') registers in bits. Note that the target
10376   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10377   // with soft float ABI has FLen==0).
10378   unsigned FLen;
10379   static const int NumArgGPRs = 8;
10380   static const int NumArgFPRs = 8;
10381   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10382                                       llvm::Type *&Field1Ty,
10383                                       CharUnits &Field1Off,
10384                                       llvm::Type *&Field2Ty,
10385                                       CharUnits &Field2Off) const;
10386 
10387 public:
10388   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10389       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10390 
10391   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10392   // non-virtual, but computeInfo is virtual, so we overload it.
10393   void computeInfo(CGFunctionInfo &FI) const override;
10394 
10395   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10396                                   int &ArgFPRsLeft) const;
10397   ABIArgInfo classifyReturnType(QualType RetTy) const;
10398 
10399   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10400                     QualType Ty) const override;
10401 
10402   ABIArgInfo extendType(QualType Ty) const;
10403 
10404   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10405                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10406                                 CharUnits &Field2Off, int &NeededArgGPRs,
10407                                 int &NeededArgFPRs) const;
10408   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10409                                                CharUnits Field1Off,
10410                                                llvm::Type *Field2Ty,
10411                                                CharUnits Field2Off) const;
10412 };
10413 } // end anonymous namespace
10414 
10415 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10416   QualType RetTy = FI.getReturnType();
10417   if (!getCXXABI().classifyReturnType(FI))
10418     FI.getReturnInfo() = classifyReturnType(RetTy);
10419 
10420   // IsRetIndirect is true if classifyArgumentType indicated the value should
10421   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10422   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10423   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10424   // list and pass indirectly on RV32.
10425   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10426   if (!IsRetIndirect && RetTy->isScalarType() &&
10427       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10428     if (RetTy->isComplexType() && FLen) {
10429       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10430       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10431     } else {
10432       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10433       IsRetIndirect = true;
10434     }
10435   }
10436 
10437   // We must track the number of GPRs used in order to conform to the RISC-V
10438   // ABI, as integer scalars passed in registers should have signext/zeroext
10439   // when promoted, but are anyext if passed on the stack. As GPR usage is
10440   // different for variadic arguments, we must also track whether we are
10441   // examining a vararg or not.
10442   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10443   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10444   int NumFixedArgs = FI.getNumRequiredArgs();
10445 
10446   int ArgNum = 0;
10447   for (auto &ArgInfo : FI.arguments()) {
10448     bool IsFixed = ArgNum < NumFixedArgs;
10449     ArgInfo.info =
10450         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10451     ArgNum++;
10452   }
10453 }
10454 
10455 // Returns true if the struct is a potential candidate for the floating point
10456 // calling convention. If this function returns true, the caller is
10457 // responsible for checking that if there is only a single field then that
10458 // field is a float.
10459 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10460                                                   llvm::Type *&Field1Ty,
10461                                                   CharUnits &Field1Off,
10462                                                   llvm::Type *&Field2Ty,
10463                                                   CharUnits &Field2Off) const {
10464   bool IsInt = Ty->isIntegralOrEnumerationType();
10465   bool IsFloat = Ty->isRealFloatingType();
10466 
10467   if (IsInt || IsFloat) {
10468     uint64_t Size = getContext().getTypeSize(Ty);
10469     if (IsInt && Size > XLen)
10470       return false;
10471     // Can't be eligible if larger than the FP registers. Half precision isn't
10472     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10473     // default to the integer ABI in that case.
10474     if (IsFloat && (Size > FLen || Size < 32))
10475       return false;
10476     // Can't be eligible if an integer type was already found (int+int pairs
10477     // are not eligible).
10478     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10479       return false;
10480     if (!Field1Ty) {
10481       Field1Ty = CGT.ConvertType(Ty);
10482       Field1Off = CurOff;
10483       return true;
10484     }
10485     if (!Field2Ty) {
10486       Field2Ty = CGT.ConvertType(Ty);
10487       Field2Off = CurOff;
10488       return true;
10489     }
10490     return false;
10491   }
10492 
10493   if (auto CTy = Ty->getAs<ComplexType>()) {
10494     if (Field1Ty)
10495       return false;
10496     QualType EltTy = CTy->getElementType();
10497     if (getContext().getTypeSize(EltTy) > FLen)
10498       return false;
10499     Field1Ty = CGT.ConvertType(EltTy);
10500     Field1Off = CurOff;
10501     Field2Ty = Field1Ty;
10502     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10503     return true;
10504   }
10505 
10506   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10507     uint64_t ArraySize = ATy->getSize().getZExtValue();
10508     QualType EltTy = ATy->getElementType();
10509     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10510     for (uint64_t i = 0; i < ArraySize; ++i) {
10511       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10512                                                 Field1Off, Field2Ty, Field2Off);
10513       if (!Ret)
10514         return false;
10515       CurOff += EltSize;
10516     }
10517     return true;
10518   }
10519 
10520   if (const auto *RTy = Ty->getAs<RecordType>()) {
10521     // Structures with either a non-trivial destructor or a non-trivial
10522     // copy constructor are not eligible for the FP calling convention.
10523     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10524       return false;
10525     if (isEmptyRecord(getContext(), Ty, true))
10526       return true;
10527     const RecordDecl *RD = RTy->getDecl();
10528     // Unions aren't eligible unless they're empty (which is caught above).
10529     if (RD->isUnion())
10530       return false;
10531     int ZeroWidthBitFieldCount = 0;
10532     for (const FieldDecl *FD : RD->fields()) {
10533       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10534       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10535       QualType QTy = FD->getType();
10536       if (FD->isBitField()) {
10537         unsigned BitWidth = FD->getBitWidthValue(getContext());
10538         // Allow a bitfield with a type greater than XLen as long as the
10539         // bitwidth is XLen or less.
10540         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10541           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10542         if (BitWidth == 0) {
10543           ZeroWidthBitFieldCount++;
10544           continue;
10545         }
10546       }
10547 
10548       bool Ret = detectFPCCEligibleStructHelper(
10549           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10550           Field1Ty, Field1Off, Field2Ty, Field2Off);
10551       if (!Ret)
10552         return false;
10553 
10554       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10555       // or int+fp structs, but are ignored for a struct with an fp field and
10556       // any number of zero-width bitfields.
10557       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10558         return false;
10559     }
10560     return Field1Ty != nullptr;
10561   }
10562 
10563   return false;
10564 }
10565 
10566 // Determine if a struct is eligible for passing according to the floating
10567 // point calling convention (i.e., when flattened it contains a single fp
10568 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10569 // NeededArgGPRs are incremented appropriately.
10570 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10571                                             CharUnits &Field1Off,
10572                                             llvm::Type *&Field2Ty,
10573                                             CharUnits &Field2Off,
10574                                             int &NeededArgGPRs,
10575                                             int &NeededArgFPRs) const {
10576   Field1Ty = nullptr;
10577   Field2Ty = nullptr;
10578   NeededArgGPRs = 0;
10579   NeededArgFPRs = 0;
10580   bool IsCandidate = detectFPCCEligibleStructHelper(
10581       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10582   // Not really a candidate if we have a single int but no float.
10583   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10584     return false;
10585   if (!IsCandidate)
10586     return false;
10587   if (Field1Ty && Field1Ty->isFloatingPointTy())
10588     NeededArgFPRs++;
10589   else if (Field1Ty)
10590     NeededArgGPRs++;
10591   if (Field2Ty && Field2Ty->isFloatingPointTy())
10592     NeededArgFPRs++;
10593   else if (Field2Ty)
10594     NeededArgGPRs++;
10595   return true;
10596 }
10597 
10598 // Call getCoerceAndExpand for the two-element flattened struct described by
10599 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10600 // appropriate coerceToType and unpaddedCoerceToType.
10601 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10602     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10603     CharUnits Field2Off) const {
10604   SmallVector<llvm::Type *, 3> CoerceElts;
10605   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10606   if (!Field1Off.isZero())
10607     CoerceElts.push_back(llvm::ArrayType::get(
10608         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10609 
10610   CoerceElts.push_back(Field1Ty);
10611   UnpaddedCoerceElts.push_back(Field1Ty);
10612 
10613   if (!Field2Ty) {
10614     return ABIArgInfo::getCoerceAndExpand(
10615         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10616         UnpaddedCoerceElts[0]);
10617   }
10618 
10619   CharUnits Field2Align =
10620       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10621   CharUnits Field1End = Field1Off +
10622       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10623   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10624 
10625   CharUnits Padding = CharUnits::Zero();
10626   if (Field2Off > Field2OffNoPadNoPack)
10627     Padding = Field2Off - Field2OffNoPadNoPack;
10628   else if (Field2Off != Field2Align && Field2Off > Field1End)
10629     Padding = Field2Off - Field1End;
10630 
10631   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10632 
10633   if (!Padding.isZero())
10634     CoerceElts.push_back(llvm::ArrayType::get(
10635         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10636 
10637   CoerceElts.push_back(Field2Ty);
10638   UnpaddedCoerceElts.push_back(Field2Ty);
10639 
10640   auto CoerceToType =
10641       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10642   auto UnpaddedCoerceToType =
10643       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10644 
10645   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10646 }
10647 
10648 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10649                                               int &ArgGPRsLeft,
10650                                               int &ArgFPRsLeft) const {
10651   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10652   Ty = useFirstFieldIfTransparentUnion(Ty);
10653 
10654   // Structures with either a non-trivial destructor or a non-trivial
10655   // copy constructor are always passed indirectly.
10656   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10657     if (ArgGPRsLeft)
10658       ArgGPRsLeft -= 1;
10659     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10660                                            CGCXXABI::RAA_DirectInMemory);
10661   }
10662 
10663   // Ignore empty structs/unions.
10664   if (isEmptyRecord(getContext(), Ty, true))
10665     return ABIArgInfo::getIgnore();
10666 
10667   uint64_t Size = getContext().getTypeSize(Ty);
10668 
10669   // Pass floating point values via FPRs if possible.
10670   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10671       FLen >= Size && ArgFPRsLeft) {
10672     ArgFPRsLeft--;
10673     return ABIArgInfo::getDirect();
10674   }
10675 
10676   // Complex types for the hard float ABI must be passed direct rather than
10677   // using CoerceAndExpand.
10678   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10679     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10680     if (getContext().getTypeSize(EltTy) <= FLen) {
10681       ArgFPRsLeft -= 2;
10682       return ABIArgInfo::getDirect();
10683     }
10684   }
10685 
10686   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10687     llvm::Type *Field1Ty = nullptr;
10688     llvm::Type *Field2Ty = nullptr;
10689     CharUnits Field1Off = CharUnits::Zero();
10690     CharUnits Field2Off = CharUnits::Zero();
10691     int NeededArgGPRs;
10692     int NeededArgFPRs;
10693     bool IsCandidate =
10694         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10695                                  NeededArgGPRs, NeededArgFPRs);
10696     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10697         NeededArgFPRs <= ArgFPRsLeft) {
10698       ArgGPRsLeft -= NeededArgGPRs;
10699       ArgFPRsLeft -= NeededArgFPRs;
10700       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10701                                                Field2Off);
10702     }
10703   }
10704 
10705   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10706   bool MustUseStack = false;
10707   // Determine the number of GPRs needed to pass the current argument
10708   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10709   // register pairs, so may consume 3 registers.
10710   int NeededArgGPRs = 1;
10711   if (!IsFixed && NeededAlign == 2 * XLen)
10712     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10713   else if (Size > XLen && Size <= 2 * XLen)
10714     NeededArgGPRs = 2;
10715 
10716   if (NeededArgGPRs > ArgGPRsLeft) {
10717     MustUseStack = true;
10718     NeededArgGPRs = ArgGPRsLeft;
10719   }
10720 
10721   ArgGPRsLeft -= NeededArgGPRs;
10722 
10723   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10724     // Treat an enum type as its underlying type.
10725     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10726       Ty = EnumTy->getDecl()->getIntegerType();
10727 
10728     // All integral types are promoted to XLen width, unless passed on the
10729     // stack.
10730     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10731       return extendType(Ty);
10732     }
10733 
10734     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10735       if (EIT->getNumBits() < XLen && !MustUseStack)
10736         return extendType(Ty);
10737       if (EIT->getNumBits() > 128 ||
10738           (!getContext().getTargetInfo().hasInt128Type() &&
10739            EIT->getNumBits() > 64))
10740         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10741     }
10742 
10743     return ABIArgInfo::getDirect();
10744   }
10745 
10746   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10747   // so coerce to integers.
10748   if (Size <= 2 * XLen) {
10749     unsigned Alignment = getContext().getTypeAlign(Ty);
10750 
10751     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10752     // required, and a 2-element XLen array if only XLen alignment is required.
10753     if (Size <= XLen) {
10754       return ABIArgInfo::getDirect(
10755           llvm::IntegerType::get(getVMContext(), XLen));
10756     } else if (Alignment == 2 * XLen) {
10757       return ABIArgInfo::getDirect(
10758           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10759     } else {
10760       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10761           llvm::IntegerType::get(getVMContext(), XLen), 2));
10762     }
10763   }
10764   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10765 }
10766 
10767 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10768   if (RetTy->isVoidType())
10769     return ABIArgInfo::getIgnore();
10770 
10771   int ArgGPRsLeft = 2;
10772   int ArgFPRsLeft = FLen ? 2 : 0;
10773 
10774   // The rules for return and argument types are the same, so defer to
10775   // classifyArgumentType.
10776   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10777                               ArgFPRsLeft);
10778 }
10779 
10780 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10781                                 QualType Ty) const {
10782   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10783 
10784   // Empty records are ignored for parameter passing purposes.
10785   if (isEmptyRecord(getContext(), Ty, true)) {
10786     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10787     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10788     return Addr;
10789   }
10790 
10791   auto TInfo = getContext().getTypeInfoInChars(Ty);
10792 
10793   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10794   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10795 
10796   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10797                           SlotSize, /*AllowHigherAlign=*/true);
10798 }
10799 
10800 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10801   int TySize = getContext().getTypeSize(Ty);
10802   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10803   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10804     return ABIArgInfo::getSignExtend(Ty);
10805   return ABIArgInfo::getExtend(Ty);
10806 }
10807 
10808 namespace {
10809 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10810 public:
10811   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10812                          unsigned FLen)
10813       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10814 
10815   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10816                            CodeGen::CodeGenModule &CGM) const override {
10817     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10818     if (!FD) return;
10819 
10820     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10821     if (!Attr)
10822       return;
10823 
10824     const char *Kind;
10825     switch (Attr->getInterrupt()) {
10826     case RISCVInterruptAttr::user: Kind = "user"; break;
10827     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10828     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10829     }
10830 
10831     auto *Fn = cast<llvm::Function>(GV);
10832 
10833     Fn->addFnAttr("interrupt", Kind);
10834   }
10835 };
10836 } // namespace
10837 
10838 //===----------------------------------------------------------------------===//
10839 // VE ABI Implementation.
10840 //
10841 namespace {
10842 class VEABIInfo : public DefaultABIInfo {
10843 public:
10844   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10845 
10846 private:
10847   ABIArgInfo classifyReturnType(QualType RetTy) const;
10848   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10849   void computeInfo(CGFunctionInfo &FI) const override;
10850 };
10851 } // end anonymous namespace
10852 
10853 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10854   if (Ty->isAnyComplexType())
10855     return ABIArgInfo::getDirect();
10856   uint64_t Size = getContext().getTypeSize(Ty);
10857   if (Size < 64 && Ty->isIntegerType())
10858     return ABIArgInfo::getExtend(Ty);
10859   return DefaultABIInfo::classifyReturnType(Ty);
10860 }
10861 
10862 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10863   if (Ty->isAnyComplexType())
10864     return ABIArgInfo::getDirect();
10865   uint64_t Size = getContext().getTypeSize(Ty);
10866   if (Size < 64 && Ty->isIntegerType())
10867     return ABIArgInfo::getExtend(Ty);
10868   return DefaultABIInfo::classifyArgumentType(Ty);
10869 }
10870 
10871 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10872   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10873   for (auto &Arg : FI.arguments())
10874     Arg.info = classifyArgumentType(Arg.type);
10875 }
10876 
10877 namespace {
10878 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10879 public:
10880   VETargetCodeGenInfo(CodeGenTypes &CGT)
10881       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10882   // VE ABI requires the arguments of variadic and prototype-less functions
10883   // are passed in both registers and memory.
10884   bool isNoProtoCallVariadic(const CallArgList &args,
10885                              const FunctionNoProtoType *fnType) const override {
10886     return true;
10887   }
10888 };
10889 } // end anonymous namespace
10890 
10891 //===----------------------------------------------------------------------===//
10892 // Driver code
10893 //===----------------------------------------------------------------------===//
10894 
10895 bool CodeGenModule::supportsCOMDAT() const {
10896   return getTriple().supportsCOMDAT();
10897 }
10898 
10899 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10900   if (TheTargetCodeGenInfo)
10901     return *TheTargetCodeGenInfo;
10902 
10903   // Helper to set the unique_ptr while still keeping the return value.
10904   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10905     this->TheTargetCodeGenInfo.reset(P);
10906     return *P;
10907   };
10908 
10909   const llvm::Triple &Triple = getTarget().getTriple();
10910   switch (Triple.getArch()) {
10911   default:
10912     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10913 
10914   case llvm::Triple::le32:
10915     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10916   case llvm::Triple::m68k:
10917     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
10918   case llvm::Triple::mips:
10919   case llvm::Triple::mipsel:
10920     if (Triple.getOS() == llvm::Triple::NaCl)
10921       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10922     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10923 
10924   case llvm::Triple::mips64:
10925   case llvm::Triple::mips64el:
10926     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10927 
10928   case llvm::Triple::avr:
10929     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10930 
10931   case llvm::Triple::aarch64:
10932   case llvm::Triple::aarch64_32:
10933   case llvm::Triple::aarch64_be: {
10934     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10935     if (getTarget().getABI() == "darwinpcs")
10936       Kind = AArch64ABIInfo::DarwinPCS;
10937     else if (Triple.isOSWindows())
10938       return SetCGInfo(
10939           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10940 
10941     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10942   }
10943 
10944   case llvm::Triple::wasm32:
10945   case llvm::Triple::wasm64: {
10946     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10947     if (getTarget().getABI() == "experimental-mv")
10948       Kind = WebAssemblyABIInfo::ExperimentalMV;
10949     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10950   }
10951 
10952   case llvm::Triple::arm:
10953   case llvm::Triple::armeb:
10954   case llvm::Triple::thumb:
10955   case llvm::Triple::thumbeb: {
10956     if (Triple.getOS() == llvm::Triple::Win32) {
10957       return SetCGInfo(
10958           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10959     }
10960 
10961     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10962     StringRef ABIStr = getTarget().getABI();
10963     if (ABIStr == "apcs-gnu")
10964       Kind = ARMABIInfo::APCS;
10965     else if (ABIStr == "aapcs16")
10966       Kind = ARMABIInfo::AAPCS16_VFP;
10967     else if (CodeGenOpts.FloatABI == "hard" ||
10968              (CodeGenOpts.FloatABI != "soft" &&
10969               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10970                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10971                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10972       Kind = ARMABIInfo::AAPCS_VFP;
10973 
10974     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10975   }
10976 
10977   case llvm::Triple::ppc: {
10978     if (Triple.isOSAIX())
10979       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10980 
10981     bool IsSoftFloat =
10982         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10983     bool RetSmallStructInRegABI =
10984         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10985     return SetCGInfo(
10986         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10987   }
10988   case llvm::Triple::ppcle: {
10989     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10990     bool RetSmallStructInRegABI =
10991         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10992     return SetCGInfo(
10993         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10994   }
10995   case llvm::Triple::ppc64:
10996     if (Triple.isOSAIX())
10997       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10998 
10999     if (Triple.isOSBinFormatELF()) {
11000       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11001       if (getTarget().getABI() == "elfv2")
11002         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11003       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11004 
11005       return SetCGInfo(
11006           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11007     }
11008     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11009   case llvm::Triple::ppc64le: {
11010     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11011     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11012     if (getTarget().getABI() == "elfv1")
11013       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11014     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11015 
11016     return SetCGInfo(
11017         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11018   }
11019 
11020   case llvm::Triple::nvptx:
11021   case llvm::Triple::nvptx64:
11022     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11023 
11024   case llvm::Triple::msp430:
11025     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11026 
11027   case llvm::Triple::riscv32:
11028   case llvm::Triple::riscv64: {
11029     StringRef ABIStr = getTarget().getABI();
11030     unsigned XLen = getTarget().getPointerWidth(0);
11031     unsigned ABIFLen = 0;
11032     if (ABIStr.endswith("f"))
11033       ABIFLen = 32;
11034     else if (ABIStr.endswith("d"))
11035       ABIFLen = 64;
11036     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11037   }
11038 
11039   case llvm::Triple::systemz: {
11040     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11041     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11042     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11043   }
11044 
11045   case llvm::Triple::tce:
11046   case llvm::Triple::tcele:
11047     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11048 
11049   case llvm::Triple::x86: {
11050     bool IsDarwinVectorABI = Triple.isOSDarwin();
11051     bool RetSmallStructInRegABI =
11052         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11053     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11054 
11055     if (Triple.getOS() == llvm::Triple::Win32) {
11056       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11057           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11058           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11059     } else {
11060       return SetCGInfo(new X86_32TargetCodeGenInfo(
11061           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11062           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11063           CodeGenOpts.FloatABI == "soft"));
11064     }
11065   }
11066 
11067   case llvm::Triple::x86_64: {
11068     StringRef ABI = getTarget().getABI();
11069     X86AVXABILevel AVXLevel =
11070         (ABI == "avx512"
11071              ? X86AVXABILevel::AVX512
11072              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11073 
11074     switch (Triple.getOS()) {
11075     case llvm::Triple::Win32:
11076       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11077     default:
11078       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11079     }
11080   }
11081   case llvm::Triple::hexagon:
11082     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11083   case llvm::Triple::lanai:
11084     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11085   case llvm::Triple::r600:
11086     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11087   case llvm::Triple::amdgcn:
11088     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11089   case llvm::Triple::sparc:
11090     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11091   case llvm::Triple::sparcv9:
11092     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11093   case llvm::Triple::xcore:
11094     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11095   case llvm::Triple::arc:
11096     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11097   case llvm::Triple::spir:
11098   case llvm::Triple::spir64:
11099     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11100   case llvm::Triple::ve:
11101     return SetCGInfo(new VETargetCodeGenInfo(Types));
11102   }
11103 }
11104 
11105 /// Create an OpenCL kernel for an enqueued block.
11106 ///
11107 /// The kernel has the same function type as the block invoke function. Its
11108 /// name is the name of the block invoke function postfixed with "_kernel".
11109 /// It simply calls the block invoke function then returns.
11110 llvm::Function *
11111 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11112                                              llvm::Function *Invoke,
11113                                              llvm::Value *BlockLiteral) const {
11114   auto *InvokeFT = Invoke->getFunctionType();
11115   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11116   for (auto &P : InvokeFT->params())
11117     ArgTys.push_back(P);
11118   auto &C = CGF.getLLVMContext();
11119   std::string Name = Invoke->getName().str() + "_kernel";
11120   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11121   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11122                                    &CGF.CGM.getModule());
11123   auto IP = CGF.Builder.saveIP();
11124   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11125   auto &Builder = CGF.Builder;
11126   Builder.SetInsertPoint(BB);
11127   llvm::SmallVector<llvm::Value *, 2> Args;
11128   for (auto &A : F->args())
11129     Args.push_back(&A);
11130   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11131   call->setCallingConv(Invoke->getCallingConv());
11132   Builder.CreateRetVoid();
11133   Builder.restoreIP(IP);
11134   return F;
11135 }
11136 
11137 /// Create an OpenCL kernel for an enqueued block.
11138 ///
11139 /// The type of the first argument (the block literal) is the struct type
11140 /// of the block literal instead of a pointer type. The first argument
11141 /// (block literal) is passed directly by value to the kernel. The kernel
11142 /// allocates the same type of struct on stack and stores the block literal
11143 /// to it and passes its pointer to the block invoke function. The kernel
11144 /// has "enqueued-block" function attribute and kernel argument metadata.
11145 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11146     CodeGenFunction &CGF, llvm::Function *Invoke,
11147     llvm::Value *BlockLiteral) const {
11148   auto &Builder = CGF.Builder;
11149   auto &C = CGF.getLLVMContext();
11150 
11151   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11152   auto *InvokeFT = Invoke->getFunctionType();
11153   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11154   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11155   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11156   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11157   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11158   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11159   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11160 
11161   ArgTys.push_back(BlockTy);
11162   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11163   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11164   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11165   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11166   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11167   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11168   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11169     ArgTys.push_back(InvokeFT->getParamType(I));
11170     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11171     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11172     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11173     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11174     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11175     ArgNames.push_back(
11176         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11177   }
11178   std::string Name = Invoke->getName().str() + "_kernel";
11179   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11180   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11181                                    &CGF.CGM.getModule());
11182   F->addFnAttr("enqueued-block");
11183   auto IP = CGF.Builder.saveIP();
11184   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11185   Builder.SetInsertPoint(BB);
11186   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11187   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11188   BlockPtr->setAlignment(BlockAlign);
11189   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11190   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11191   llvm::SmallVector<llvm::Value *, 2> Args;
11192   Args.push_back(Cast);
11193   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11194     Args.push_back(I);
11195   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11196   call->setCallingConv(Invoke->getCallingConv());
11197   Builder.CreateRetVoid();
11198   Builder.restoreIP(IP);
11199 
11200   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11201   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11202   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11203   F->setMetadata("kernel_arg_base_type",
11204                  llvm::MDNode::get(C, ArgBaseTypeNames));
11205   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11206   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11207     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11208 
11209   return F;
11210 }
11211