xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp (revision 53683b95ef66a12337999587cd98302b1b425920)
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<BitIntType>())
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 complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
396                                     QualType Ty, CharUnits SlotSize,
397                                     CharUnits EltSize, const ComplexType *CTy) {
398   Address Addr =
399       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
400                              SlotSize, SlotSize, /*AllowHigher*/ true);
401 
402   Address RealAddr = Addr;
403   Address ImagAddr = RealAddr;
404   if (CGF.CGM.getDataLayout().isBigEndian()) {
405     RealAddr =
406         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
407     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
408                                                       2 * SlotSize - EltSize);
409   } else {
410     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
411   }
412 
413   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
414   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
415   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
416   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
417   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
418 
419   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
420   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
421                          /*init*/ true);
422   return Temp;
423 }
424 
425 static Address emitMergePHI(CodeGenFunction &CGF,
426                             Address Addr1, llvm::BasicBlock *Block1,
427                             Address Addr2, llvm::BasicBlock *Block2,
428                             const llvm::Twine &Name = "") {
429   assert(Addr1.getType() == Addr2.getType());
430   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
431   PHI->addIncoming(Addr1.getPointer(), Block1);
432   PHI->addIncoming(Addr2.getPointer(), Block2);
433   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
434   return Address(PHI, Addr1.getElementType(), Align);
435 }
436 
437 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
438 
439 // If someone can figure out a general rule for this, that would be great.
440 // It's probably just doomed to be platform-dependent, though.
441 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
442   // Verified for:
443   //   x86-64     FreeBSD, Linux, Darwin
444   //   x86-32     FreeBSD, Linux, Darwin
445   //   PowerPC    Linux, Darwin
446   //   ARM        Darwin (*not* EABI)
447   //   AArch64    Linux
448   return 32;
449 }
450 
451 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
452                                      const FunctionNoProtoType *fnType) const {
453   // The following conventions are known to require this to be false:
454   //   x86_stdcall
455   //   MIPS
456   // For everything else, we just prefer false unless we opt out.
457   return false;
458 }
459 
460 void
461 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
462                                              llvm::SmallString<24> &Opt) const {
463   // This assumes the user is passing a library name like "rt" instead of a
464   // filename like "librt.a/so", and that they don't care whether it's static or
465   // dynamic.
466   Opt = "-l";
467   Opt += Lib;
468 }
469 
470 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
471   // OpenCL kernels are called via an explicit runtime API with arguments
472   // set with clSetKernelArg(), not as normal sub-functions.
473   // Return SPIR_KERNEL by default as the kernel calling convention to
474   // ensure the fingerprint is fixed such way that each OpenCL argument
475   // gets one matching argument in the produced kernel function argument
476   // list to enable feasible implementation of clSetKernelArg() with
477   // aggregates etc. In case we would use the default C calling conv here,
478   // clSetKernelArg() might break depending on the target-specific
479   // conventions; different targets might split structs passed as values
480   // to multiple function arguments etc.
481   return llvm::CallingConv::SPIR_KERNEL;
482 }
483 
484 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
485     llvm::PointerType *T, QualType QT) const {
486   return llvm::ConstantPointerNull::get(T);
487 }
488 
489 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
490                                                    const VarDecl *D) const {
491   assert(!CGM.getLangOpts().OpenCL &&
492          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
493          "Address space agnostic languages only");
494   return D ? D->getType().getAddressSpace() : LangAS::Default;
495 }
496 
497 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
498     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
499     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
500   // Since target may map different address spaces in AST to the same address
501   // space, an address space conversion may end up as a bitcast.
502   if (auto *C = dyn_cast<llvm::Constant>(Src))
503     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
504   // Try to preserve the source's name to make IR more readable.
505   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
506       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
507 }
508 
509 llvm::Constant *
510 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
511                                         LangAS SrcAddr, LangAS DestAddr,
512                                         llvm::Type *DestTy) const {
513   // Since target may map different address spaces in AST to the same address
514   // space, an address space conversion may end up as a bitcast.
515   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
516 }
517 
518 llvm::SyncScope::ID
519 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
520                                       SyncScope Scope,
521                                       llvm::AtomicOrdering Ordering,
522                                       llvm::LLVMContext &Ctx) const {
523   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
524 }
525 
526 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
527 
528 /// isEmptyField - Return true iff a the field is "empty", that is it
529 /// is an unnamed bit-field or an (array of) empty record(s).
530 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
531                          bool AllowArrays) {
532   if (FD->isUnnamedBitfield())
533     return true;
534 
535   QualType FT = FD->getType();
536 
537   // Constant arrays of empty records count as empty, strip them off.
538   // Constant arrays of zero length always count as empty.
539   bool WasArray = false;
540   if (AllowArrays)
541     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
542       if (AT->getSize() == 0)
543         return true;
544       FT = AT->getElementType();
545       // The [[no_unique_address]] special case below does not apply to
546       // arrays of C++ empty records, so we need to remember this fact.
547       WasArray = true;
548     }
549 
550   const RecordType *RT = FT->getAs<RecordType>();
551   if (!RT)
552     return false;
553 
554   // C++ record fields are never empty, at least in the Itanium ABI.
555   //
556   // FIXME: We should use a predicate for whether this behavior is true in the
557   // current ABI.
558   //
559   // The exception to the above rule are fields marked with the
560   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
561   // according to the Itanium ABI.  The exception applies only to records,
562   // not arrays of records, so we must also check whether we stripped off an
563   // array type above.
564   if (isa<CXXRecordDecl>(RT->getDecl()) &&
565       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
566     return false;
567 
568   return isEmptyRecord(Context, FT, AllowArrays);
569 }
570 
571 /// isEmptyRecord - Return true iff a structure contains only empty
572 /// fields. Note that a structure with a flexible array member is not
573 /// considered empty.
574 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
575   const RecordType *RT = T->getAs<RecordType>();
576   if (!RT)
577     return false;
578   const RecordDecl *RD = RT->getDecl();
579   if (RD->hasFlexibleArrayMember())
580     return false;
581 
582   // If this is a C++ record, check the bases first.
583   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
584     for (const auto &I : CXXRD->bases())
585       if (!isEmptyRecord(Context, I.getType(), true))
586         return false;
587 
588   for (const auto *I : RD->fields())
589     if (!isEmptyField(Context, I, AllowArrays))
590       return false;
591   return true;
592 }
593 
594 /// isSingleElementStruct - Determine if a structure is a "single
595 /// element struct", i.e. it has exactly one non-empty field or
596 /// exactly one field which is itself a single element
597 /// struct. Structures with flexible array members are never
598 /// considered single element structs.
599 ///
600 /// \return The field declaration for the single non-empty field, if
601 /// it exists.
602 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
603   const RecordType *RT = T->getAs<RecordType>();
604   if (!RT)
605     return nullptr;
606 
607   const RecordDecl *RD = RT->getDecl();
608   if (RD->hasFlexibleArrayMember())
609     return nullptr;
610 
611   const Type *Found = nullptr;
612 
613   // If this is a C++ record, check the bases first.
614   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
615     for (const auto &I : CXXRD->bases()) {
616       // Ignore empty records.
617       if (isEmptyRecord(Context, I.getType(), true))
618         continue;
619 
620       // If we already found an element then this isn't a single-element struct.
621       if (Found)
622         return nullptr;
623 
624       // If this is non-empty and not a single element struct, the composite
625       // cannot be a single element struct.
626       Found = isSingleElementStruct(I.getType(), Context);
627       if (!Found)
628         return nullptr;
629     }
630   }
631 
632   // Check for single element.
633   for (const auto *FD : RD->fields()) {
634     QualType FT = FD->getType();
635 
636     // Ignore empty fields.
637     if (isEmptyField(Context, FD, true))
638       continue;
639 
640     // If we already found an element then this isn't a single-element
641     // struct.
642     if (Found)
643       return nullptr;
644 
645     // Treat single element arrays as the element.
646     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
647       if (AT->getSize().getZExtValue() != 1)
648         break;
649       FT = AT->getElementType();
650     }
651 
652     if (!isAggregateTypeForABI(FT)) {
653       Found = FT.getTypePtr();
654     } else {
655       Found = isSingleElementStruct(FT, Context);
656       if (!Found)
657         return nullptr;
658     }
659   }
660 
661   // We don't consider a struct a single-element struct if it has
662   // padding beyond the element type.
663   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
664     return nullptr;
665 
666   return Found;
667 }
668 
669 namespace {
670 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
671                        const ABIArgInfo &AI) {
672   // This default implementation defers to the llvm backend's va_arg
673   // instruction. It can handle only passing arguments directly
674   // (typically only handled in the backend for primitive types), or
675   // aggregates passed indirectly by pointer (NOTE: if the "byval"
676   // flag has ABI impact in the callee, this implementation cannot
677   // work.)
678 
679   // Only a few cases are covered here at the moment -- those needed
680   // by the default abi.
681   llvm::Value *Val;
682 
683   if (AI.isIndirect()) {
684     assert(!AI.getPaddingType() &&
685            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
686     assert(
687         !AI.getIndirectRealign() &&
688         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
689 
690     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
691     CharUnits TyAlignForABI = TyInfo.Align;
692 
693     llvm::Type *BaseTy =
694         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
695     llvm::Value *Addr =
696         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
697     return Address(Addr, TyAlignForABI);
698   } else {
699     assert((AI.isDirect() || AI.isExtend()) &&
700            "Unexpected ArgInfo Kind in generic VAArg emitter!");
701 
702     assert(!AI.getInReg() &&
703            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
704     assert(!AI.getPaddingType() &&
705            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
706     assert(!AI.getDirectOffset() &&
707            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
708     assert(!AI.getCoerceToType() &&
709            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
710 
711     Address Temp = CGF.CreateMemTemp(Ty, "varet");
712     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
713     CGF.Builder.CreateStore(Val, Temp);
714     return Temp;
715   }
716 }
717 
718 /// DefaultABIInfo - The default implementation for ABI specific
719 /// details. This implementation provides information which results in
720 /// self-consistent and sensible LLVM IR generation, but does not
721 /// conform to any particular ABI.
722 class DefaultABIInfo : public ABIInfo {
723 public:
724   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
725 
726   ABIArgInfo classifyReturnType(QualType RetTy) const;
727   ABIArgInfo classifyArgumentType(QualType RetTy) const;
728 
729   void computeInfo(CGFunctionInfo &FI) const override {
730     if (!getCXXABI().classifyReturnType(FI))
731       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
732     for (auto &I : FI.arguments())
733       I.info = classifyArgumentType(I.type);
734   }
735 
736   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
737                     QualType Ty) const override {
738     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
739   }
740 };
741 
742 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
743 public:
744   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
745       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
746 };
747 
748 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
749   Ty = useFirstFieldIfTransparentUnion(Ty);
750 
751   if (isAggregateTypeForABI(Ty)) {
752     // Records with non-trivial destructors/copy-constructors should not be
753     // passed by value.
754     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
755       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
756 
757     return getNaturalAlignIndirect(Ty);
758   }
759 
760   // Treat an enum type as its underlying type.
761   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
762     Ty = EnumTy->getDecl()->getIntegerType();
763 
764   ASTContext &Context = getContext();
765   if (const auto *EIT = Ty->getAs<BitIntType>())
766     if (EIT->getNumBits() >
767         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
768                                 ? Context.Int128Ty
769                                 : Context.LongLongTy))
770       return getNaturalAlignIndirect(Ty);
771 
772   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
773                                             : ABIArgInfo::getDirect());
774 }
775 
776 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
777   if (RetTy->isVoidType())
778     return ABIArgInfo::getIgnore();
779 
780   if (isAggregateTypeForABI(RetTy))
781     return getNaturalAlignIndirect(RetTy);
782 
783   // Treat an enum type as its underlying type.
784   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
785     RetTy = EnumTy->getDecl()->getIntegerType();
786 
787   if (const auto *EIT = RetTy->getAs<BitIntType>())
788     if (EIT->getNumBits() >
789         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
790                                      ? getContext().Int128Ty
791                                      : getContext().LongLongTy))
792       return getNaturalAlignIndirect(RetTy);
793 
794   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
795                                                : ABIArgInfo::getDirect());
796 }
797 
798 //===----------------------------------------------------------------------===//
799 // WebAssembly ABI Implementation
800 //
801 // This is a very simple ABI that relies a lot on DefaultABIInfo.
802 //===----------------------------------------------------------------------===//
803 
804 class WebAssemblyABIInfo final : public SwiftABIInfo {
805 public:
806   enum ABIKind {
807     MVP = 0,
808     ExperimentalMV = 1,
809   };
810 
811 private:
812   DefaultABIInfo defaultInfo;
813   ABIKind Kind;
814 
815 public:
816   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
817       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
818 
819 private:
820   ABIArgInfo classifyReturnType(QualType RetTy) const;
821   ABIArgInfo classifyArgumentType(QualType Ty) const;
822 
823   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
824   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
825   // overload them.
826   void computeInfo(CGFunctionInfo &FI) const override {
827     if (!getCXXABI().classifyReturnType(FI))
828       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
829     for (auto &Arg : FI.arguments())
830       Arg.info = classifyArgumentType(Arg.type);
831   }
832 
833   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
834                     QualType Ty) const override;
835 
836   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
837                                     bool asReturnValue) const override {
838     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
839   }
840 
841   bool isSwiftErrorInRegister() const override {
842     return false;
843   }
844 };
845 
846 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
847 public:
848   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
849                                         WebAssemblyABIInfo::ABIKind K)
850       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
851 
852   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
853                            CodeGen::CodeGenModule &CGM) const override {
854     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
855     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
856       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
857         llvm::Function *Fn = cast<llvm::Function>(GV);
858         llvm::AttrBuilder B(GV->getContext());
859         B.addAttribute("wasm-import-module", Attr->getImportModule());
860         Fn->addFnAttrs(B);
861       }
862       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
863         llvm::Function *Fn = cast<llvm::Function>(GV);
864         llvm::AttrBuilder B(GV->getContext());
865         B.addAttribute("wasm-import-name", Attr->getImportName());
866         Fn->addFnAttrs(B);
867       }
868       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
869         llvm::Function *Fn = cast<llvm::Function>(GV);
870         llvm::AttrBuilder B(GV->getContext());
871         B.addAttribute("wasm-export-name", Attr->getExportName());
872         Fn->addFnAttrs(B);
873       }
874     }
875 
876     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
877       llvm::Function *Fn = cast<llvm::Function>(GV);
878       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
879         Fn->addFnAttr("no-prototype");
880     }
881   }
882 };
883 
884 /// Classify argument of given type \p Ty.
885 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
886   Ty = useFirstFieldIfTransparentUnion(Ty);
887 
888   if (isAggregateTypeForABI(Ty)) {
889     // Records with non-trivial destructors/copy-constructors should not be
890     // passed by value.
891     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
892       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
893     // Ignore empty structs/unions.
894     if (isEmptyRecord(getContext(), Ty, true))
895       return ABIArgInfo::getIgnore();
896     // Lower single-element structs to just pass a regular value. TODO: We
897     // could do reasonable-size multiple-element structs too, using getExpand(),
898     // though watch out for things like bitfields.
899     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
900       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
901     // For the experimental multivalue ABI, fully expand all other aggregates
902     if (Kind == ABIKind::ExperimentalMV) {
903       const RecordType *RT = Ty->getAs<RecordType>();
904       assert(RT);
905       bool HasBitField = false;
906       for (auto *Field : RT->getDecl()->fields()) {
907         if (Field->isBitField()) {
908           HasBitField = true;
909           break;
910         }
911       }
912       if (!HasBitField)
913         return ABIArgInfo::getExpand();
914     }
915   }
916 
917   // Otherwise just do the default thing.
918   return defaultInfo.classifyArgumentType(Ty);
919 }
920 
921 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
922   if (isAggregateTypeForABI(RetTy)) {
923     // Records with non-trivial destructors/copy-constructors should not be
924     // returned by value.
925     if (!getRecordArgABI(RetTy, getCXXABI())) {
926       // Ignore empty structs/unions.
927       if (isEmptyRecord(getContext(), RetTy, true))
928         return ABIArgInfo::getIgnore();
929       // Lower single-element structs to just return a regular value. TODO: We
930       // could do reasonable-size multiple-element structs too, using
931       // ABIArgInfo::getDirect().
932       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
933         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
934       // For the experimental multivalue ABI, return all other aggregates
935       if (Kind == ABIKind::ExperimentalMV)
936         return ABIArgInfo::getDirect();
937     }
938   }
939 
940   // Otherwise just do the default thing.
941   return defaultInfo.classifyReturnType(RetTy);
942 }
943 
944 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
945                                       QualType Ty) const {
946   bool IsIndirect = isAggregateTypeForABI(Ty) &&
947                     !isEmptyRecord(getContext(), Ty, true) &&
948                     !isSingleElementStruct(Ty, getContext());
949   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
950                           getContext().getTypeInfoInChars(Ty),
951                           CharUnits::fromQuantity(4),
952                           /*AllowHigherAlign=*/true);
953 }
954 
955 //===----------------------------------------------------------------------===//
956 // le32/PNaCl bitcode ABI Implementation
957 //
958 // This is a simplified version of the x86_32 ABI.  Arguments and return values
959 // are always passed on the stack.
960 //===----------------------------------------------------------------------===//
961 
962 class PNaClABIInfo : public ABIInfo {
963  public:
964   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
965 
966   ABIArgInfo classifyReturnType(QualType RetTy) const;
967   ABIArgInfo classifyArgumentType(QualType RetTy) const;
968 
969   void computeInfo(CGFunctionInfo &FI) const override;
970   Address EmitVAArg(CodeGenFunction &CGF,
971                     Address VAListAddr, QualType Ty) const override;
972 };
973 
974 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
975  public:
976    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
977        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
978 };
979 
980 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
981   if (!getCXXABI().classifyReturnType(FI))
982     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
983 
984   for (auto &I : FI.arguments())
985     I.info = classifyArgumentType(I.type);
986 }
987 
988 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
989                                 QualType Ty) const {
990   // The PNaCL ABI is a bit odd, in that varargs don't use normal
991   // function classification. Structs get passed directly for varargs
992   // functions, through a rewriting transform in
993   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
994   // this target to actually support a va_arg instructions with an
995   // aggregate type, unlike other targets.
996   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
997 }
998 
999 /// Classify argument of given type \p Ty.
1000 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1001   if (isAggregateTypeForABI(Ty)) {
1002     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1003       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1004     return getNaturalAlignIndirect(Ty);
1005   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1006     // Treat an enum type as its underlying type.
1007     Ty = EnumTy->getDecl()->getIntegerType();
1008   } else if (Ty->isFloatingType()) {
1009     // Floating-point types don't go inreg.
1010     return ABIArgInfo::getDirect();
1011   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1012     // Treat bit-precise integers as integers if <= 64, otherwise pass
1013     // indirectly.
1014     if (EIT->getNumBits() > 64)
1015       return getNaturalAlignIndirect(Ty);
1016     return ABIArgInfo::getDirect();
1017   }
1018 
1019   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1020                                             : ABIArgInfo::getDirect());
1021 }
1022 
1023 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1024   if (RetTy->isVoidType())
1025     return ABIArgInfo::getIgnore();
1026 
1027   // In the PNaCl ABI we always return records/structures on the stack.
1028   if (isAggregateTypeForABI(RetTy))
1029     return getNaturalAlignIndirect(RetTy);
1030 
1031   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1032   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1033     if (EIT->getNumBits() > 64)
1034       return getNaturalAlignIndirect(RetTy);
1035     return ABIArgInfo::getDirect();
1036   }
1037 
1038   // Treat an enum type as its underlying type.
1039   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1040     RetTy = EnumTy->getDecl()->getIntegerType();
1041 
1042   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1043                                                : ABIArgInfo::getDirect());
1044 }
1045 
1046 /// IsX86_MMXType - Return true if this is an MMX type.
1047 bool IsX86_MMXType(llvm::Type *IRType) {
1048   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1049   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1050     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1051     IRType->getScalarSizeInBits() != 64;
1052 }
1053 
1054 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1055                                           StringRef Constraint,
1056                                           llvm::Type* Ty) {
1057   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1058                      .Cases("y", "&y", "^Ym", true)
1059                      .Default(false);
1060   if (IsMMXCons && Ty->isVectorTy()) {
1061     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1062         64) {
1063       // Invalid MMX constraint
1064       return nullptr;
1065     }
1066 
1067     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1068   }
1069 
1070   // No operation needed
1071   return Ty;
1072 }
1073 
1074 /// Returns true if this type can be passed in SSE registers with the
1075 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1076 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1077   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1078     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1079       if (BT->getKind() == BuiltinType::LongDouble) {
1080         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1081             &llvm::APFloat::x87DoubleExtended())
1082           return false;
1083       }
1084       return true;
1085     }
1086   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1087     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1088     // registers specially.
1089     unsigned VecSize = Context.getTypeSize(VT);
1090     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1091       return true;
1092   }
1093   return false;
1094 }
1095 
1096 /// Returns true if this aggregate is small enough to be passed in SSE registers
1097 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1098 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1099   return NumMembers <= 4;
1100 }
1101 
1102 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1103 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1104   auto AI = ABIArgInfo::getDirect(T);
1105   AI.setInReg(true);
1106   AI.setCanBeFlattened(false);
1107   return AI;
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // X86-32 ABI Implementation
1112 //===----------------------------------------------------------------------===//
1113 
1114 /// Similar to llvm::CCState, but for Clang.
1115 struct CCState {
1116   CCState(CGFunctionInfo &FI)
1117       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1118 
1119   llvm::SmallBitVector IsPreassigned;
1120   unsigned CC = CallingConv::CC_C;
1121   unsigned FreeRegs = 0;
1122   unsigned FreeSSERegs = 0;
1123 };
1124 
1125 /// X86_32ABIInfo - The X86-32 ABI information.
1126 class X86_32ABIInfo : public SwiftABIInfo {
1127   enum Class {
1128     Integer,
1129     Float
1130   };
1131 
1132   static const unsigned MinABIStackAlignInBytes = 4;
1133 
1134   bool IsDarwinVectorABI;
1135   bool IsRetSmallStructInRegABI;
1136   bool IsWin32StructABI;
1137   bool IsSoftFloatABI;
1138   bool IsMCUABI;
1139   bool IsLinuxABI;
1140   unsigned DefaultNumRegisterParameters;
1141 
1142   static bool isRegisterSize(unsigned Size) {
1143     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1144   }
1145 
1146   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1147     // FIXME: Assumes vectorcall is in use.
1148     return isX86VectorTypeForVectorCall(getContext(), Ty);
1149   }
1150 
1151   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1152                                          uint64_t NumMembers) const override {
1153     // FIXME: Assumes vectorcall is in use.
1154     return isX86VectorCallAggregateSmallEnough(NumMembers);
1155   }
1156 
1157   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1158 
1159   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1160   /// such that the argument will be passed in memory.
1161   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1162 
1163   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1164 
1165   /// Return the alignment to use for the given type on the stack.
1166   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1167 
1168   Class classify(QualType Ty) const;
1169   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1170   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1171 
1172   /// Updates the number of available free registers, returns
1173   /// true if any registers were allocated.
1174   bool updateFreeRegs(QualType Ty, CCState &State) const;
1175 
1176   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1177                                 bool &NeedsPadding) const;
1178   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1179 
1180   bool canExpandIndirectArgument(QualType Ty) const;
1181 
1182   /// Rewrite the function info so that all memory arguments use
1183   /// inalloca.
1184   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1185 
1186   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1187                            CharUnits &StackOffset, ABIArgInfo &Info,
1188                            QualType Type) const;
1189   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1190 
1191 public:
1192 
1193   void computeInfo(CGFunctionInfo &FI) const override;
1194   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1195                     QualType Ty) const override;
1196 
1197   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1198                 bool RetSmallStructInRegABI, bool Win32StructABI,
1199                 unsigned NumRegisterParameters, bool SoftFloatABI)
1200     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1201       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1202       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1203       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1204       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1205                  CGT.getTarget().getTriple().isOSCygMing()),
1206       DefaultNumRegisterParameters(NumRegisterParameters) {}
1207 
1208   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1209                                     bool asReturnValue) const override {
1210     // LLVM's x86-32 lowering currently only assigns up to three
1211     // integer registers and three fp registers.  Oddly, it'll use up to
1212     // four vector registers for vectors, but those can overlap with the
1213     // scalar registers.
1214     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1215   }
1216 
1217   bool isSwiftErrorInRegister() const override {
1218     // x86-32 lowering does not support passing swifterror in a register.
1219     return false;
1220   }
1221 };
1222 
1223 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1224 public:
1225   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1226                           bool RetSmallStructInRegABI, bool Win32StructABI,
1227                           unsigned NumRegisterParameters, bool SoftFloatABI)
1228       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1229             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1230             NumRegisterParameters, SoftFloatABI)) {}
1231 
1232   static bool isStructReturnInRegABI(
1233       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1234 
1235   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1236                            CodeGen::CodeGenModule &CGM) const override;
1237 
1238   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1239     // Darwin uses different dwarf register numbers for EH.
1240     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1241     return 4;
1242   }
1243 
1244   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1245                                llvm::Value *Address) const override;
1246 
1247   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1248                                   StringRef Constraint,
1249                                   llvm::Type* Ty) const override {
1250     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1251   }
1252 
1253   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1254                                 std::string &Constraints,
1255                                 std::vector<llvm::Type *> &ResultRegTypes,
1256                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1257                                 std::vector<LValue> &ResultRegDests,
1258                                 std::string &AsmString,
1259                                 unsigned NumOutputs) const override;
1260 
1261   llvm::Constant *
1262   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1263     unsigned Sig = (0xeb << 0) |  // jmp rel8
1264                    (0x06 << 8) |  //           .+0x08
1265                    ('v' << 16) |
1266                    ('2' << 24);
1267     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1268   }
1269 
1270   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1271     return "movl\t%ebp, %ebp"
1272            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1273   }
1274 };
1275 
1276 }
1277 
1278 /// Rewrite input constraint references after adding some output constraints.
1279 /// In the case where there is one output and one input and we add one output,
1280 /// we need to replace all operand references greater than or equal to 1:
1281 ///     mov $0, $1
1282 ///     mov eax, $1
1283 /// The result will be:
1284 ///     mov $0, $2
1285 ///     mov eax, $2
1286 static void rewriteInputConstraintReferences(unsigned FirstIn,
1287                                              unsigned NumNewOuts,
1288                                              std::string &AsmString) {
1289   std::string Buf;
1290   llvm::raw_string_ostream OS(Buf);
1291   size_t Pos = 0;
1292   while (Pos < AsmString.size()) {
1293     size_t DollarStart = AsmString.find('$', Pos);
1294     if (DollarStart == std::string::npos)
1295       DollarStart = AsmString.size();
1296     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1297     if (DollarEnd == std::string::npos)
1298       DollarEnd = AsmString.size();
1299     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1300     Pos = DollarEnd;
1301     size_t NumDollars = DollarEnd - DollarStart;
1302     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1303       // We have an operand reference.
1304       size_t DigitStart = Pos;
1305       if (AsmString[DigitStart] == '{') {
1306         OS << '{';
1307         ++DigitStart;
1308       }
1309       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1310       if (DigitEnd == std::string::npos)
1311         DigitEnd = AsmString.size();
1312       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1313       unsigned OperandIndex;
1314       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1315         if (OperandIndex >= FirstIn)
1316           OperandIndex += NumNewOuts;
1317         OS << OperandIndex;
1318       } else {
1319         OS << OperandStr;
1320       }
1321       Pos = DigitEnd;
1322     }
1323   }
1324   AsmString = std::move(OS.str());
1325 }
1326 
1327 /// Add output constraints for EAX:EDX because they are return registers.
1328 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1329     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1330     std::vector<llvm::Type *> &ResultRegTypes,
1331     std::vector<llvm::Type *> &ResultTruncRegTypes,
1332     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1333     unsigned NumOutputs) const {
1334   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1335 
1336   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1337   // larger.
1338   if (!Constraints.empty())
1339     Constraints += ',';
1340   if (RetWidth <= 32) {
1341     Constraints += "={eax}";
1342     ResultRegTypes.push_back(CGF.Int32Ty);
1343   } else {
1344     // Use the 'A' constraint for EAX:EDX.
1345     Constraints += "=A";
1346     ResultRegTypes.push_back(CGF.Int64Ty);
1347   }
1348 
1349   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1350   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1351   ResultTruncRegTypes.push_back(CoerceTy);
1352 
1353   // Coerce the integer by bitcasting the return slot pointer.
1354   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1355                                                   CoerceTy->getPointerTo()));
1356   ResultRegDests.push_back(ReturnSlot);
1357 
1358   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1359 }
1360 
1361 /// shouldReturnTypeInRegister - Determine if the given type should be
1362 /// returned in a register (for the Darwin and MCU ABI).
1363 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1364                                                ASTContext &Context) const {
1365   uint64_t Size = Context.getTypeSize(Ty);
1366 
1367   // For i386, type must be register sized.
1368   // For the MCU ABI, it only needs to be <= 8-byte
1369   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1370    return false;
1371 
1372   if (Ty->isVectorType()) {
1373     // 64- and 128- bit vectors inside structures are not returned in
1374     // registers.
1375     if (Size == 64 || Size == 128)
1376       return false;
1377 
1378     return true;
1379   }
1380 
1381   // If this is a builtin, pointer, enum, complex type, member pointer, or
1382   // member function pointer it is ok.
1383   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1384       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1385       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1386     return true;
1387 
1388   // Arrays are treated like records.
1389   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1390     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1391 
1392   // Otherwise, it must be a record type.
1393   const RecordType *RT = Ty->getAs<RecordType>();
1394   if (!RT) return false;
1395 
1396   // FIXME: Traverse bases here too.
1397 
1398   // Structure types are passed in register if all fields would be
1399   // passed in a register.
1400   for (const auto *FD : RT->getDecl()->fields()) {
1401     // Empty fields are ignored.
1402     if (isEmptyField(Context, FD, true))
1403       continue;
1404 
1405     // Check fields recursively.
1406     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1407       return false;
1408   }
1409   return true;
1410 }
1411 
1412 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1413   // Treat complex types as the element type.
1414   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1415     Ty = CTy->getElementType();
1416 
1417   // Check for a type which we know has a simple scalar argument-passing
1418   // convention without any padding.  (We're specifically looking for 32
1419   // and 64-bit integer and integer-equivalents, float, and double.)
1420   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1421       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1422     return false;
1423 
1424   uint64_t Size = Context.getTypeSize(Ty);
1425   return Size == 32 || Size == 64;
1426 }
1427 
1428 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1429                           uint64_t &Size) {
1430   for (const auto *FD : RD->fields()) {
1431     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1432     // argument is smaller than 32-bits, expanding the struct will create
1433     // alignment padding.
1434     if (!is32Or64BitBasicType(FD->getType(), Context))
1435       return false;
1436 
1437     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1438     // how to expand them yet, and the predicate for telling if a bitfield still
1439     // counts as "basic" is more complicated than what we were doing previously.
1440     if (FD->isBitField())
1441       return false;
1442 
1443     Size += Context.getTypeSize(FD->getType());
1444   }
1445   return true;
1446 }
1447 
1448 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1449                                  uint64_t &Size) {
1450   // Don't do this if there are any non-empty bases.
1451   for (const CXXBaseSpecifier &Base : RD->bases()) {
1452     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1453                               Size))
1454       return false;
1455   }
1456   if (!addFieldSizes(Context, RD, Size))
1457     return false;
1458   return true;
1459 }
1460 
1461 /// Test whether an argument type which is to be passed indirectly (on the
1462 /// stack) would have the equivalent layout if it was expanded into separate
1463 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1464 /// optimizations.
1465 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1466   // We can only expand structure types.
1467   const RecordType *RT = Ty->getAs<RecordType>();
1468   if (!RT)
1469     return false;
1470   const RecordDecl *RD = RT->getDecl();
1471   uint64_t Size = 0;
1472   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1473     if (!IsWin32StructABI) {
1474       // On non-Windows, we have to conservatively match our old bitcode
1475       // prototypes in order to be ABI-compatible at the bitcode level.
1476       if (!CXXRD->isCLike())
1477         return false;
1478     } else {
1479       // Don't do this for dynamic classes.
1480       if (CXXRD->isDynamicClass())
1481         return false;
1482     }
1483     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1484       return false;
1485   } else {
1486     if (!addFieldSizes(getContext(), RD, Size))
1487       return false;
1488   }
1489 
1490   // We can do this if there was no alignment padding.
1491   return Size == getContext().getTypeSize(Ty);
1492 }
1493 
1494 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1495   // If the return value is indirect, then the hidden argument is consuming one
1496   // integer register.
1497   if (State.FreeRegs) {
1498     --State.FreeRegs;
1499     if (!IsMCUABI)
1500       return getNaturalAlignIndirectInReg(RetTy);
1501   }
1502   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1503 }
1504 
1505 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1506                                              CCState &State) const {
1507   if (RetTy->isVoidType())
1508     return ABIArgInfo::getIgnore();
1509 
1510   const Type *Base = nullptr;
1511   uint64_t NumElts = 0;
1512   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1513        State.CC == llvm::CallingConv::X86_RegCall) &&
1514       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1515     // The LLVM struct type for such an aggregate should lower properly.
1516     return ABIArgInfo::getDirect();
1517   }
1518 
1519   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1520     // On Darwin, some vectors are returned in registers.
1521     if (IsDarwinVectorABI) {
1522       uint64_t Size = getContext().getTypeSize(RetTy);
1523 
1524       // 128-bit vectors are a special case; they are returned in
1525       // registers and we need to make sure to pick a type the LLVM
1526       // backend will like.
1527       if (Size == 128)
1528         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1529             llvm::Type::getInt64Ty(getVMContext()), 2));
1530 
1531       // Always return in register if it fits in a general purpose
1532       // register, or if it is 64 bits and has a single element.
1533       if ((Size == 8 || Size == 16 || Size == 32) ||
1534           (Size == 64 && VT->getNumElements() == 1))
1535         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1536                                                             Size));
1537 
1538       return getIndirectReturnResult(RetTy, State);
1539     }
1540 
1541     return ABIArgInfo::getDirect();
1542   }
1543 
1544   if (isAggregateTypeForABI(RetTy)) {
1545     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1546       // Structures with flexible arrays are always indirect.
1547       if (RT->getDecl()->hasFlexibleArrayMember())
1548         return getIndirectReturnResult(RetTy, State);
1549     }
1550 
1551     // If specified, structs and unions are always indirect.
1552     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1553       return getIndirectReturnResult(RetTy, State);
1554 
1555     // Ignore empty structs/unions.
1556     if (isEmptyRecord(getContext(), RetTy, true))
1557       return ABIArgInfo::getIgnore();
1558 
1559     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1560     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1561       QualType ET = getContext().getCanonicalType(CT->getElementType());
1562       if (ET->isFloat16Type())
1563         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1564             llvm::Type::getHalfTy(getVMContext()), 2));
1565     }
1566 
1567     // Small structures which are register sized are generally returned
1568     // in a register.
1569     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1570       uint64_t Size = getContext().getTypeSize(RetTy);
1571 
1572       // As a special-case, if the struct is a "single-element" struct, and
1573       // the field is of type "float" or "double", return it in a
1574       // floating-point register. (MSVC does not apply this special case.)
1575       // We apply a similar transformation for pointer types to improve the
1576       // quality of the generated IR.
1577       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1578         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1579             || SeltTy->hasPointerRepresentation())
1580           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1581 
1582       // FIXME: We should be able to narrow this integer in cases with dead
1583       // padding.
1584       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1585     }
1586 
1587     return getIndirectReturnResult(RetTy, State);
1588   }
1589 
1590   // Treat an enum type as its underlying type.
1591   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1592     RetTy = EnumTy->getDecl()->getIntegerType();
1593 
1594   if (const auto *EIT = RetTy->getAs<BitIntType>())
1595     if (EIT->getNumBits() > 64)
1596       return getIndirectReturnResult(RetTy, State);
1597 
1598   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1599                                                : ABIArgInfo::getDirect());
1600 }
1601 
1602 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1603   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1604 }
1605 
1606 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1607   const RecordType *RT = Ty->getAs<RecordType>();
1608   if (!RT)
1609     return false;
1610   const RecordDecl *RD = RT->getDecl();
1611 
1612   // If this is a C++ record, check the bases first.
1613   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1614     for (const auto &I : CXXRD->bases())
1615       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1616         return false;
1617 
1618   for (const auto *i : RD->fields()) {
1619     QualType FT = i->getType();
1620 
1621     if (isSIMDVectorType(Context, FT))
1622       return true;
1623 
1624     if (isRecordWithSIMDVectorType(Context, FT))
1625       return true;
1626   }
1627 
1628   return false;
1629 }
1630 
1631 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1632                                                  unsigned Align) const {
1633   // Otherwise, if the alignment is less than or equal to the minimum ABI
1634   // alignment, just use the default; the backend will handle this.
1635   if (Align <= MinABIStackAlignInBytes)
1636     return 0; // Use default alignment.
1637 
1638   if (IsLinuxABI) {
1639     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1640     // want to spend any effort dealing with the ramifications of ABI breaks.
1641     //
1642     // If the vector type is __m128/__m256/__m512, return the default alignment.
1643     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1644       return Align;
1645   }
1646   // On non-Darwin, the stack type alignment is always 4.
1647   if (!IsDarwinVectorABI) {
1648     // Set explicit alignment, since we may need to realign the top.
1649     return MinABIStackAlignInBytes;
1650   }
1651 
1652   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1653   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1654                       isRecordWithSIMDVectorType(getContext(), Ty)))
1655     return 16;
1656 
1657   return MinABIStackAlignInBytes;
1658 }
1659 
1660 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1661                                             CCState &State) const {
1662   if (!ByVal) {
1663     if (State.FreeRegs) {
1664       --State.FreeRegs; // Non-byval indirects just use one pointer.
1665       if (!IsMCUABI)
1666         return getNaturalAlignIndirectInReg(Ty);
1667     }
1668     return getNaturalAlignIndirect(Ty, false);
1669   }
1670 
1671   // Compute the byval alignment.
1672   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1673   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1674   if (StackAlign == 0)
1675     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1676 
1677   // If the stack alignment is less than the type alignment, realign the
1678   // argument.
1679   bool Realign = TypeAlign > StackAlign;
1680   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1681                                  /*ByVal=*/true, Realign);
1682 }
1683 
1684 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1685   const Type *T = isSingleElementStruct(Ty, getContext());
1686   if (!T)
1687     T = Ty.getTypePtr();
1688 
1689   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1690     BuiltinType::Kind K = BT->getKind();
1691     if (K == BuiltinType::Float || K == BuiltinType::Double)
1692       return Float;
1693   }
1694   return Integer;
1695 }
1696 
1697 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1698   if (!IsSoftFloatABI) {
1699     Class C = classify(Ty);
1700     if (C == Float)
1701       return false;
1702   }
1703 
1704   unsigned Size = getContext().getTypeSize(Ty);
1705   unsigned SizeInRegs = (Size + 31) / 32;
1706 
1707   if (SizeInRegs == 0)
1708     return false;
1709 
1710   if (!IsMCUABI) {
1711     if (SizeInRegs > State.FreeRegs) {
1712       State.FreeRegs = 0;
1713       return false;
1714     }
1715   } else {
1716     // The MCU psABI allows passing parameters in-reg even if there are
1717     // earlier parameters that are passed on the stack. Also,
1718     // it does not allow passing >8-byte structs in-register,
1719     // even if there are 3 free registers available.
1720     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1721       return false;
1722   }
1723 
1724   State.FreeRegs -= SizeInRegs;
1725   return true;
1726 }
1727 
1728 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1729                                              bool &InReg,
1730                                              bool &NeedsPadding) const {
1731   // On Windows, aggregates other than HFAs are never passed in registers, and
1732   // they do not consume register slots. Homogenous floating-point aggregates
1733   // (HFAs) have already been dealt with at this point.
1734   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1735     return false;
1736 
1737   NeedsPadding = false;
1738   InReg = !IsMCUABI;
1739 
1740   if (!updateFreeRegs(Ty, State))
1741     return false;
1742 
1743   if (IsMCUABI)
1744     return true;
1745 
1746   if (State.CC == llvm::CallingConv::X86_FastCall ||
1747       State.CC == llvm::CallingConv::X86_VectorCall ||
1748       State.CC == llvm::CallingConv::X86_RegCall) {
1749     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1750       NeedsPadding = true;
1751 
1752     return false;
1753   }
1754 
1755   return true;
1756 }
1757 
1758 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1759   if (!updateFreeRegs(Ty, State))
1760     return false;
1761 
1762   if (IsMCUABI)
1763     return false;
1764 
1765   if (State.CC == llvm::CallingConv::X86_FastCall ||
1766       State.CC == llvm::CallingConv::X86_VectorCall ||
1767       State.CC == llvm::CallingConv::X86_RegCall) {
1768     if (getContext().getTypeSize(Ty) > 32)
1769       return false;
1770 
1771     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1772         Ty->isReferenceType());
1773   }
1774 
1775   return true;
1776 }
1777 
1778 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1779   // Vectorcall x86 works subtly different than in x64, so the format is
1780   // a bit different than the x64 version.  First, all vector types (not HVAs)
1781   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1782   // This differs from the x64 implementation, where the first 6 by INDEX get
1783   // registers.
1784   // In the second pass over the arguments, HVAs are passed in the remaining
1785   // vector registers if possible, or indirectly by address. The address will be
1786   // passed in ECX/EDX if available. Any other arguments are passed according to
1787   // the usual fastcall rules.
1788   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1789   for (int I = 0, E = Args.size(); I < E; ++I) {
1790     const Type *Base = nullptr;
1791     uint64_t NumElts = 0;
1792     const QualType &Ty = Args[I].type;
1793     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1794         isHomogeneousAggregate(Ty, Base, NumElts)) {
1795       if (State.FreeSSERegs >= NumElts) {
1796         State.FreeSSERegs -= NumElts;
1797         Args[I].info = ABIArgInfo::getDirectInReg();
1798         State.IsPreassigned.set(I);
1799       }
1800     }
1801   }
1802 }
1803 
1804 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1805                                                CCState &State) const {
1806   // FIXME: Set alignment on indirect arguments.
1807   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1808   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1809   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1810 
1811   Ty = useFirstFieldIfTransparentUnion(Ty);
1812   TypeInfo TI = getContext().getTypeInfo(Ty);
1813 
1814   // Check with the C++ ABI first.
1815   const RecordType *RT = Ty->getAs<RecordType>();
1816   if (RT) {
1817     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1818     if (RAA == CGCXXABI::RAA_Indirect) {
1819       return getIndirectResult(Ty, false, State);
1820     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1821       // The field index doesn't matter, we'll fix it up later.
1822       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1823     }
1824   }
1825 
1826   // Regcall uses the concept of a homogenous vector aggregate, similar
1827   // to other targets.
1828   const Type *Base = nullptr;
1829   uint64_t NumElts = 0;
1830   if ((IsRegCall || IsVectorCall) &&
1831       isHomogeneousAggregate(Ty, Base, NumElts)) {
1832     if (State.FreeSSERegs >= NumElts) {
1833       State.FreeSSERegs -= NumElts;
1834 
1835       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1836       // does.
1837       if (IsVectorCall)
1838         return getDirectX86Hva();
1839 
1840       if (Ty->isBuiltinType() || Ty->isVectorType())
1841         return ABIArgInfo::getDirect();
1842       return ABIArgInfo::getExpand();
1843     }
1844     return getIndirectResult(Ty, /*ByVal=*/false, State);
1845   }
1846 
1847   if (isAggregateTypeForABI(Ty)) {
1848     // Structures with flexible arrays are always indirect.
1849     // FIXME: This should not be byval!
1850     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1851       return getIndirectResult(Ty, true, State);
1852 
1853     // Ignore empty structs/unions on non-Windows.
1854     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1855       return ABIArgInfo::getIgnore();
1856 
1857     llvm::LLVMContext &LLVMContext = getVMContext();
1858     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1859     bool NeedsPadding = false;
1860     bool InReg;
1861     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1862       unsigned SizeInRegs = (TI.Width + 31) / 32;
1863       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1864       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1865       if (InReg)
1866         return ABIArgInfo::getDirectInReg(Result);
1867       else
1868         return ABIArgInfo::getDirect(Result);
1869     }
1870     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1871 
1872     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1873     // added in MSVC 2015.
1874     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1875       return getIndirectResult(Ty, /*ByVal=*/false, State);
1876 
1877     // Expand small (<= 128-bit) record types when we know that the stack layout
1878     // of those arguments will match the struct. This is important because the
1879     // LLVM backend isn't smart enough to remove byval, which inhibits many
1880     // optimizations.
1881     // Don't do this for the MCU if there are still free integer registers
1882     // (see X86_64 ABI for full explanation).
1883     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1884         canExpandIndirectArgument(Ty))
1885       return ABIArgInfo::getExpandWithPadding(
1886           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1887 
1888     return getIndirectResult(Ty, true, State);
1889   }
1890 
1891   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1892     // On Windows, vectors are passed directly if registers are available, or
1893     // indirectly if not. This avoids the need to align argument memory. Pass
1894     // user-defined vector types larger than 512 bits indirectly for simplicity.
1895     if (IsWin32StructABI) {
1896       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1897         --State.FreeSSERegs;
1898         return ABIArgInfo::getDirectInReg();
1899       }
1900       return getIndirectResult(Ty, /*ByVal=*/false, State);
1901     }
1902 
1903     // On Darwin, some vectors are passed in memory, we handle this by passing
1904     // it as an i8/i16/i32/i64.
1905     if (IsDarwinVectorABI) {
1906       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1907           (TI.Width == 64 && VT->getNumElements() == 1))
1908         return ABIArgInfo::getDirect(
1909             llvm::IntegerType::get(getVMContext(), TI.Width));
1910     }
1911 
1912     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1913       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1914 
1915     return ABIArgInfo::getDirect();
1916   }
1917 
1918 
1919   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1920     Ty = EnumTy->getDecl()->getIntegerType();
1921 
1922   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1923 
1924   if (isPromotableIntegerTypeForABI(Ty)) {
1925     if (InReg)
1926       return ABIArgInfo::getExtendInReg(Ty);
1927     return ABIArgInfo::getExtend(Ty);
1928   }
1929 
1930   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1931     if (EIT->getNumBits() <= 64) {
1932       if (InReg)
1933         return ABIArgInfo::getDirectInReg();
1934       return ABIArgInfo::getDirect();
1935     }
1936     return getIndirectResult(Ty, /*ByVal=*/false, State);
1937   }
1938 
1939   if (InReg)
1940     return ABIArgInfo::getDirectInReg();
1941   return ABIArgInfo::getDirect();
1942 }
1943 
1944 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1945   CCState State(FI);
1946   if (IsMCUABI)
1947     State.FreeRegs = 3;
1948   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1949     State.FreeRegs = 2;
1950     State.FreeSSERegs = 3;
1951   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1952     State.FreeRegs = 2;
1953     State.FreeSSERegs = 6;
1954   } else if (FI.getHasRegParm())
1955     State.FreeRegs = FI.getRegParm();
1956   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1957     State.FreeRegs = 5;
1958     State.FreeSSERegs = 8;
1959   } else if (IsWin32StructABI) {
1960     // Since MSVC 2015, the first three SSE vectors have been passed in
1961     // registers. The rest are passed indirectly.
1962     State.FreeRegs = DefaultNumRegisterParameters;
1963     State.FreeSSERegs = 3;
1964   } else
1965     State.FreeRegs = DefaultNumRegisterParameters;
1966 
1967   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1968     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1969   } else if (FI.getReturnInfo().isIndirect()) {
1970     // The C++ ABI is not aware of register usage, so we have to check if the
1971     // return value was sret and put it in a register ourselves if appropriate.
1972     if (State.FreeRegs) {
1973       --State.FreeRegs;  // The sret parameter consumes a register.
1974       if (!IsMCUABI)
1975         FI.getReturnInfo().setInReg(true);
1976     }
1977   }
1978 
1979   // The chain argument effectively gives us another free register.
1980   if (FI.isChainCall())
1981     ++State.FreeRegs;
1982 
1983   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1984   // arguments to XMM registers as available.
1985   if (State.CC == llvm::CallingConv::X86_VectorCall)
1986     runVectorCallFirstPass(FI, State);
1987 
1988   bool UsedInAlloca = false;
1989   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1990   for (int I = 0, E = Args.size(); I < E; ++I) {
1991     // Skip arguments that have already been assigned.
1992     if (State.IsPreassigned.test(I))
1993       continue;
1994 
1995     Args[I].info = classifyArgumentType(Args[I].type, State);
1996     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1997   }
1998 
1999   // If we needed to use inalloca for any argument, do a second pass and rewrite
2000   // all the memory arguments to use inalloca.
2001   if (UsedInAlloca)
2002     rewriteWithInAlloca(FI);
2003 }
2004 
2005 void
2006 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2007                                    CharUnits &StackOffset, ABIArgInfo &Info,
2008                                    QualType Type) const {
2009   // Arguments are always 4-byte-aligned.
2010   CharUnits WordSize = CharUnits::fromQuantity(4);
2011   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2012 
2013   // sret pointers and indirect things will require an extra pointer
2014   // indirection, unless they are byval. Most things are byval, and will not
2015   // require this indirection.
2016   bool IsIndirect = false;
2017   if (Info.isIndirect() && !Info.getIndirectByVal())
2018     IsIndirect = true;
2019   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2020   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2021   if (IsIndirect)
2022     LLTy = LLTy->getPointerTo(0);
2023   FrameFields.push_back(LLTy);
2024   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2025 
2026   // Insert padding bytes to respect alignment.
2027   CharUnits FieldEnd = StackOffset;
2028   StackOffset = FieldEnd.alignTo(WordSize);
2029   if (StackOffset != FieldEnd) {
2030     CharUnits NumBytes = StackOffset - FieldEnd;
2031     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2032     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2033     FrameFields.push_back(Ty);
2034   }
2035 }
2036 
2037 static bool isArgInAlloca(const ABIArgInfo &Info) {
2038   // Leave ignored and inreg arguments alone.
2039   switch (Info.getKind()) {
2040   case ABIArgInfo::InAlloca:
2041     return true;
2042   case ABIArgInfo::Ignore:
2043   case ABIArgInfo::IndirectAliased:
2044     return false;
2045   case ABIArgInfo::Indirect:
2046   case ABIArgInfo::Direct:
2047   case ABIArgInfo::Extend:
2048     return !Info.getInReg();
2049   case ABIArgInfo::Expand:
2050   case ABIArgInfo::CoerceAndExpand:
2051     // These are aggregate types which are never passed in registers when
2052     // inalloca is involved.
2053     return true;
2054   }
2055   llvm_unreachable("invalid enum");
2056 }
2057 
2058 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2059   assert(IsWin32StructABI && "inalloca only supported on win32");
2060 
2061   // Build a packed struct type for all of the arguments in memory.
2062   SmallVector<llvm::Type *, 6> FrameFields;
2063 
2064   // The stack alignment is always 4.
2065   CharUnits StackAlign = CharUnits::fromQuantity(4);
2066 
2067   CharUnits StackOffset;
2068   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2069 
2070   // Put 'this' into the struct before 'sret', if necessary.
2071   bool IsThisCall =
2072       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2073   ABIArgInfo &Ret = FI.getReturnInfo();
2074   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2075       isArgInAlloca(I->info)) {
2076     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2077     ++I;
2078   }
2079 
2080   // Put the sret parameter into the inalloca struct if it's in memory.
2081   if (Ret.isIndirect() && !Ret.getInReg()) {
2082     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2083     // On Windows, the hidden sret parameter is always returned in eax.
2084     Ret.setInAllocaSRet(IsWin32StructABI);
2085   }
2086 
2087   // Skip the 'this' parameter in ecx.
2088   if (IsThisCall)
2089     ++I;
2090 
2091   // Put arguments passed in memory into the struct.
2092   for (; I != E; ++I) {
2093     if (isArgInAlloca(I->info))
2094       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2095   }
2096 
2097   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2098                                         /*isPacked=*/true),
2099                   StackAlign);
2100 }
2101 
2102 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2103                                  Address VAListAddr, QualType Ty) const {
2104 
2105   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2106 
2107   // x86-32 changes the alignment of certain arguments on the stack.
2108   //
2109   // Just messing with TypeInfo like this works because we never pass
2110   // anything indirectly.
2111   TypeInfo.Align = CharUnits::fromQuantity(
2112                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2113 
2114   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2115                           TypeInfo, CharUnits::fromQuantity(4),
2116                           /*AllowHigherAlign*/ true);
2117 }
2118 
2119 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2120     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2121   assert(Triple.getArch() == llvm::Triple::x86);
2122 
2123   switch (Opts.getStructReturnConvention()) {
2124   case CodeGenOptions::SRCK_Default:
2125     break;
2126   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2127     return false;
2128   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2129     return true;
2130   }
2131 
2132   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2133     return true;
2134 
2135   switch (Triple.getOS()) {
2136   case llvm::Triple::DragonFly:
2137   case llvm::Triple::FreeBSD:
2138   case llvm::Triple::OpenBSD:
2139   case llvm::Triple::Win32:
2140     return true;
2141   default:
2142     return false;
2143   }
2144 }
2145 
2146 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2147                                  CodeGen::CodeGenModule &CGM) {
2148   if (!FD->hasAttr<AnyX86InterruptAttr>())
2149     return;
2150 
2151   llvm::Function *Fn = cast<llvm::Function>(GV);
2152   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2153   if (FD->getNumParams() == 0)
2154     return;
2155 
2156   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2157   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2158   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2159     Fn->getContext(), ByValTy);
2160   Fn->addParamAttr(0, NewAttr);
2161 }
2162 
2163 void X86_32TargetCodeGenInfo::setTargetAttributes(
2164     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2165   if (GV->isDeclaration())
2166     return;
2167   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2168     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2169       llvm::Function *Fn = cast<llvm::Function>(GV);
2170       Fn->addFnAttr("stackrealign");
2171     }
2172 
2173     addX86InterruptAttrs(FD, GV, CGM);
2174   }
2175 }
2176 
2177 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2178                                                CodeGen::CodeGenFunction &CGF,
2179                                                llvm::Value *Address) const {
2180   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2181 
2182   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2183 
2184   // 0-7 are the eight integer registers;  the order is different
2185   //   on Darwin (for EH), but the range is the same.
2186   // 8 is %eip.
2187   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2188 
2189   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2190     // 12-16 are st(0..4).  Not sure why we stop at 4.
2191     // These have size 16, which is sizeof(long double) on
2192     // platforms with 8-byte alignment for that type.
2193     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2194     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2195 
2196   } else {
2197     // 9 is %eflags, which doesn't get a size on Darwin for some
2198     // reason.
2199     Builder.CreateAlignedStore(
2200         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2201                                CharUnits::One());
2202 
2203     // 11-16 are st(0..5).  Not sure why we stop at 5.
2204     // These have size 12, which is sizeof(long double) on
2205     // platforms with 4-byte alignment for that type.
2206     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2207     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2208   }
2209 
2210   return false;
2211 }
2212 
2213 //===----------------------------------------------------------------------===//
2214 // X86-64 ABI Implementation
2215 //===----------------------------------------------------------------------===//
2216 
2217 
2218 namespace {
2219 /// The AVX ABI level for X86 targets.
2220 enum class X86AVXABILevel {
2221   None,
2222   AVX,
2223   AVX512
2224 };
2225 
2226 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2227 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2228   switch (AVXLevel) {
2229   case X86AVXABILevel::AVX512:
2230     return 512;
2231   case X86AVXABILevel::AVX:
2232     return 256;
2233   case X86AVXABILevel::None:
2234     return 128;
2235   }
2236   llvm_unreachable("Unknown AVXLevel");
2237 }
2238 
2239 /// X86_64ABIInfo - The X86_64 ABI information.
2240 class X86_64ABIInfo : public SwiftABIInfo {
2241   enum Class {
2242     Integer = 0,
2243     SSE,
2244     SSEUp,
2245     X87,
2246     X87Up,
2247     ComplexX87,
2248     NoClass,
2249     Memory
2250   };
2251 
2252   /// merge - Implement the X86_64 ABI merging algorithm.
2253   ///
2254   /// Merge an accumulating classification \arg Accum with a field
2255   /// classification \arg Field.
2256   ///
2257   /// \param Accum - The accumulating classification. This should
2258   /// always be either NoClass or the result of a previous merge
2259   /// call. In addition, this should never be Memory (the caller
2260   /// should just return Memory for the aggregate).
2261   static Class merge(Class Accum, Class Field);
2262 
2263   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2264   ///
2265   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2266   /// final MEMORY or SSE classes when necessary.
2267   ///
2268   /// \param AggregateSize - The size of the current aggregate in
2269   /// the classification process.
2270   ///
2271   /// \param Lo - The classification for the parts of the type
2272   /// residing in the low word of the containing object.
2273   ///
2274   /// \param Hi - The classification for the parts of the type
2275   /// residing in the higher words of the containing object.
2276   ///
2277   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2278 
2279   /// classify - Determine the x86_64 register classes in which the
2280   /// given type T should be passed.
2281   ///
2282   /// \param Lo - The classification for the parts of the type
2283   /// residing in the low word of the containing object.
2284   ///
2285   /// \param Hi - The classification for the parts of the type
2286   /// residing in the high word of the containing object.
2287   ///
2288   /// \param OffsetBase - The bit offset of this type in the
2289   /// containing object.  Some parameters are classified different
2290   /// depending on whether they straddle an eightbyte boundary.
2291   ///
2292   /// \param isNamedArg - Whether the argument in question is a "named"
2293   /// argument, as used in AMD64-ABI 3.5.7.
2294   ///
2295   /// If a word is unused its result will be NoClass; if a type should
2296   /// be passed in Memory then at least the classification of \arg Lo
2297   /// will be Memory.
2298   ///
2299   /// The \arg Lo class will be NoClass iff the argument is ignored.
2300   ///
2301   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2302   /// also be ComplexX87.
2303   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2304                 bool isNamedArg) const;
2305 
2306   llvm::Type *GetByteVectorType(QualType Ty) const;
2307   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2308                                  unsigned IROffset, QualType SourceTy,
2309                                  unsigned SourceOffset) const;
2310   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2311                                      unsigned IROffset, QualType SourceTy,
2312                                      unsigned SourceOffset) const;
2313 
2314   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2315   /// such that the argument will be returned in memory.
2316   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2317 
2318   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2319   /// such that the argument will be passed in memory.
2320   ///
2321   /// \param freeIntRegs - The number of free integer registers remaining
2322   /// available.
2323   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2324 
2325   ABIArgInfo classifyReturnType(QualType RetTy) const;
2326 
2327   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2328                                   unsigned &neededInt, unsigned &neededSSE,
2329                                   bool isNamedArg) const;
2330 
2331   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2332                                        unsigned &NeededSSE) const;
2333 
2334   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2335                                            unsigned &NeededSSE) const;
2336 
2337   bool IsIllegalVectorType(QualType Ty) const;
2338 
2339   /// The 0.98 ABI revision clarified a lot of ambiguities,
2340   /// unfortunately in ways that were not always consistent with
2341   /// certain previous compilers.  In particular, platforms which
2342   /// required strict binary compatibility with older versions of GCC
2343   /// may need to exempt themselves.
2344   bool honorsRevision0_98() const {
2345     return !getTarget().getTriple().isOSDarwin();
2346   }
2347 
2348   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2349   /// classify it as INTEGER (for compatibility with older clang compilers).
2350   bool classifyIntegerMMXAsSSE() const {
2351     // Clang <= 3.8 did not do this.
2352     if (getContext().getLangOpts().getClangABICompat() <=
2353         LangOptions::ClangABI::Ver3_8)
2354       return false;
2355 
2356     const llvm::Triple &Triple = getTarget().getTriple();
2357     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2358       return false;
2359     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2360       return false;
2361     return true;
2362   }
2363 
2364   // GCC classifies vectors of __int128 as memory.
2365   bool passInt128VectorsInMem() const {
2366     // Clang <= 9.0 did not do this.
2367     if (getContext().getLangOpts().getClangABICompat() <=
2368         LangOptions::ClangABI::Ver9)
2369       return false;
2370 
2371     const llvm::Triple &T = getTarget().getTriple();
2372     return T.isOSLinux() || T.isOSNetBSD();
2373   }
2374 
2375   X86AVXABILevel AVXLevel;
2376   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2377   // 64-bit hardware.
2378   bool Has64BitPointers;
2379 
2380 public:
2381   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2382       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2383       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2384   }
2385 
2386   bool isPassedUsingAVXType(QualType type) const {
2387     unsigned neededInt, neededSSE;
2388     // The freeIntRegs argument doesn't matter here.
2389     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2390                                            /*isNamedArg*/true);
2391     if (info.isDirect()) {
2392       llvm::Type *ty = info.getCoerceToType();
2393       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2394         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2395     }
2396     return false;
2397   }
2398 
2399   void computeInfo(CGFunctionInfo &FI) const override;
2400 
2401   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2402                     QualType Ty) const override;
2403   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2404                       QualType Ty) const override;
2405 
2406   bool has64BitPointers() const {
2407     return Has64BitPointers;
2408   }
2409 
2410   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2411                                     bool asReturnValue) const override {
2412     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2413   }
2414   bool isSwiftErrorInRegister() const override {
2415     return true;
2416   }
2417 };
2418 
2419 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2420 class WinX86_64ABIInfo : public SwiftABIInfo {
2421 public:
2422   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2423       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2424         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2425 
2426   void computeInfo(CGFunctionInfo &FI) const override;
2427 
2428   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2429                     QualType Ty) const override;
2430 
2431   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2432     // FIXME: Assumes vectorcall is in use.
2433     return isX86VectorTypeForVectorCall(getContext(), Ty);
2434   }
2435 
2436   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2437                                          uint64_t NumMembers) const override {
2438     // FIXME: Assumes vectorcall is in use.
2439     return isX86VectorCallAggregateSmallEnough(NumMembers);
2440   }
2441 
2442   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2443                                     bool asReturnValue) const override {
2444     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2445   }
2446 
2447   bool isSwiftErrorInRegister() const override {
2448     return true;
2449   }
2450 
2451 private:
2452   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2453                       bool IsVectorCall, bool IsRegCall) const;
2454   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2455                                            const ABIArgInfo &current) const;
2456 
2457   X86AVXABILevel AVXLevel;
2458 
2459   bool IsMingw64;
2460 };
2461 
2462 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2463 public:
2464   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2465       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2466 
2467   const X86_64ABIInfo &getABIInfo() const {
2468     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2469   }
2470 
2471   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2472   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2473   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2474 
2475   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2476     return 7;
2477   }
2478 
2479   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2480                                llvm::Value *Address) const override {
2481     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2482 
2483     // 0-15 are the 16 integer registers.
2484     // 16 is %rip.
2485     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2486     return false;
2487   }
2488 
2489   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2490                                   StringRef Constraint,
2491                                   llvm::Type* Ty) const override {
2492     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2493   }
2494 
2495   bool isNoProtoCallVariadic(const CallArgList &args,
2496                              const FunctionNoProtoType *fnType) const override {
2497     // The default CC on x86-64 sets %al to the number of SSA
2498     // registers used, and GCC sets this when calling an unprototyped
2499     // function, so we override the default behavior.  However, don't do
2500     // that when AVX types are involved: the ABI explicitly states it is
2501     // undefined, and it doesn't work in practice because of how the ABI
2502     // defines varargs anyway.
2503     if (fnType->getCallConv() == CC_C) {
2504       bool HasAVXType = false;
2505       for (CallArgList::const_iterator
2506              it = args.begin(), ie = args.end(); it != ie; ++it) {
2507         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2508           HasAVXType = true;
2509           break;
2510         }
2511       }
2512 
2513       if (!HasAVXType)
2514         return true;
2515     }
2516 
2517     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2518   }
2519 
2520   llvm::Constant *
2521   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2522     unsigned Sig = (0xeb << 0) | // jmp rel8
2523                    (0x06 << 8) | //           .+0x08
2524                    ('v' << 16) |
2525                    ('2' << 24);
2526     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2527   }
2528 
2529   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2530                            CodeGen::CodeGenModule &CGM) const override {
2531     if (GV->isDeclaration())
2532       return;
2533     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2534       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2535         llvm::Function *Fn = cast<llvm::Function>(GV);
2536         Fn->addFnAttr("stackrealign");
2537       }
2538 
2539       addX86InterruptAttrs(FD, GV, CGM);
2540     }
2541   }
2542 
2543   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2544                             const FunctionDecl *Caller,
2545                             const FunctionDecl *Callee,
2546                             const CallArgList &Args) const override;
2547 };
2548 
2549 static void initFeatureMaps(const ASTContext &Ctx,
2550                             llvm::StringMap<bool> &CallerMap,
2551                             const FunctionDecl *Caller,
2552                             llvm::StringMap<bool> &CalleeMap,
2553                             const FunctionDecl *Callee) {
2554   if (CalleeMap.empty() && CallerMap.empty()) {
2555     // The caller is potentially nullptr in the case where the call isn't in a
2556     // function.  In this case, the getFunctionFeatureMap ensures we just get
2557     // the TU level setting (since it cannot be modified by 'target'..
2558     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2559     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2560   }
2561 }
2562 
2563 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2564                                  SourceLocation CallLoc,
2565                                  const llvm::StringMap<bool> &CallerMap,
2566                                  const llvm::StringMap<bool> &CalleeMap,
2567                                  QualType Ty, StringRef Feature,
2568                                  bool IsArgument) {
2569   bool CallerHasFeat = CallerMap.lookup(Feature);
2570   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2571   if (!CallerHasFeat && !CalleeHasFeat)
2572     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2573            << IsArgument << Ty << Feature;
2574 
2575   // Mixing calling conventions here is very clearly an error.
2576   if (!CallerHasFeat || !CalleeHasFeat)
2577     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2578            << IsArgument << Ty << Feature;
2579 
2580   // Else, both caller and callee have the required feature, so there is no need
2581   // to diagnose.
2582   return false;
2583 }
2584 
2585 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2586                           SourceLocation CallLoc,
2587                           const llvm::StringMap<bool> &CallerMap,
2588                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2589                           bool IsArgument) {
2590   uint64_t Size = Ctx.getTypeSize(Ty);
2591   if (Size > 256)
2592     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2593                                 "avx512f", IsArgument);
2594 
2595   if (Size > 128)
2596     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2597                                 IsArgument);
2598 
2599   return false;
2600 }
2601 
2602 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2603     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2604     const FunctionDecl *Callee, const CallArgList &Args) const {
2605   llvm::StringMap<bool> CallerMap;
2606   llvm::StringMap<bool> CalleeMap;
2607   unsigned ArgIndex = 0;
2608 
2609   // We need to loop through the actual call arguments rather than the the
2610   // function's parameters, in case this variadic.
2611   for (const CallArg &Arg : Args) {
2612     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2613     // additionally changes how vectors >256 in size are passed. Like GCC, we
2614     // warn when a function is called with an argument where this will change.
2615     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2616     // the caller and callee features are mismatched.
2617     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2618     // change its ABI with attribute-target after this call.
2619     if (Arg.getType()->isVectorType() &&
2620         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2621       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2622       QualType Ty = Arg.getType();
2623       // The CallArg seems to have desugared the type already, so for clearer
2624       // diagnostics, replace it with the type in the FunctionDecl if possible.
2625       if (ArgIndex < Callee->getNumParams())
2626         Ty = Callee->getParamDecl(ArgIndex)->getType();
2627 
2628       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2629                         CalleeMap, Ty, /*IsArgument*/ true))
2630         return;
2631     }
2632     ++ArgIndex;
2633   }
2634 
2635   // Check return always, as we don't have a good way of knowing in codegen
2636   // whether this value is used, tail-called, etc.
2637   if (Callee->getReturnType()->isVectorType() &&
2638       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2639     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2640     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2641                   CalleeMap, Callee->getReturnType(),
2642                   /*IsArgument*/ false);
2643   }
2644 }
2645 
2646 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2647   // If the argument does not end in .lib, automatically add the suffix.
2648   // If the argument contains a space, enclose it in quotes.
2649   // This matches the behavior of MSVC.
2650   bool Quote = Lib.contains(' ');
2651   std::string ArgStr = Quote ? "\"" : "";
2652   ArgStr += Lib;
2653   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2654     ArgStr += ".lib";
2655   ArgStr += Quote ? "\"" : "";
2656   return ArgStr;
2657 }
2658 
2659 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2660 public:
2661   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2662         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2663         unsigned NumRegisterParameters)
2664     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2665         Win32StructABI, NumRegisterParameters, false) {}
2666 
2667   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2668                            CodeGen::CodeGenModule &CGM) const override;
2669 
2670   void getDependentLibraryOption(llvm::StringRef Lib,
2671                                  llvm::SmallString<24> &Opt) const override {
2672     Opt = "/DEFAULTLIB:";
2673     Opt += qualifyWindowsLibrary(Lib);
2674   }
2675 
2676   void getDetectMismatchOption(llvm::StringRef Name,
2677                                llvm::StringRef Value,
2678                                llvm::SmallString<32> &Opt) const override {
2679     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2680   }
2681 };
2682 
2683 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2684                                           CodeGen::CodeGenModule &CGM) {
2685   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2686 
2687     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2688       Fn->addFnAttr("stack-probe-size",
2689                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2690     if (CGM.getCodeGenOpts().NoStackArgProbe)
2691       Fn->addFnAttr("no-stack-arg-probe");
2692   }
2693 }
2694 
2695 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2696     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2697   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2698   if (GV->isDeclaration())
2699     return;
2700   addStackProbeTargetAttributes(D, GV, CGM);
2701 }
2702 
2703 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2704 public:
2705   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2706                              X86AVXABILevel AVXLevel)
2707       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2708 
2709   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2710                            CodeGen::CodeGenModule &CGM) const override;
2711 
2712   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2713     return 7;
2714   }
2715 
2716   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2717                                llvm::Value *Address) const override {
2718     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2719 
2720     // 0-15 are the 16 integer registers.
2721     // 16 is %rip.
2722     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2723     return false;
2724   }
2725 
2726   void getDependentLibraryOption(llvm::StringRef Lib,
2727                                  llvm::SmallString<24> &Opt) const override {
2728     Opt = "/DEFAULTLIB:";
2729     Opt += qualifyWindowsLibrary(Lib);
2730   }
2731 
2732   void getDetectMismatchOption(llvm::StringRef Name,
2733                                llvm::StringRef Value,
2734                                llvm::SmallString<32> &Opt) const override {
2735     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2736   }
2737 };
2738 
2739 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2740     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2741   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2742   if (GV->isDeclaration())
2743     return;
2744   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2745     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2746       llvm::Function *Fn = cast<llvm::Function>(GV);
2747       Fn->addFnAttr("stackrealign");
2748     }
2749 
2750     addX86InterruptAttrs(FD, GV, CGM);
2751   }
2752 
2753   addStackProbeTargetAttributes(D, GV, CGM);
2754 }
2755 }
2756 
2757 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2758                               Class &Hi) const {
2759   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2760   //
2761   // (a) If one of the classes is Memory, the whole argument is passed in
2762   //     memory.
2763   //
2764   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2765   //     memory.
2766   //
2767   // (c) If the size of the aggregate exceeds two eightbytes and the first
2768   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2769   //     argument is passed in memory. NOTE: This is necessary to keep the
2770   //     ABI working for processors that don't support the __m256 type.
2771   //
2772   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2773   //
2774   // Some of these are enforced by the merging logic.  Others can arise
2775   // only with unions; for example:
2776   //   union { _Complex double; unsigned; }
2777   //
2778   // Note that clauses (b) and (c) were added in 0.98.
2779   //
2780   if (Hi == Memory)
2781     Lo = Memory;
2782   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2783     Lo = Memory;
2784   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2785     Lo = Memory;
2786   if (Hi == SSEUp && Lo != SSE)
2787     Hi = SSE;
2788 }
2789 
2790 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2791   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2792   // classified recursively so that always two fields are
2793   // considered. The resulting class is calculated according to
2794   // the classes of the fields in the eightbyte:
2795   //
2796   // (a) If both classes are equal, this is the resulting class.
2797   //
2798   // (b) If one of the classes is NO_CLASS, the resulting class is
2799   // the other class.
2800   //
2801   // (c) If one of the classes is MEMORY, the result is the MEMORY
2802   // class.
2803   //
2804   // (d) If one of the classes is INTEGER, the result is the
2805   // INTEGER.
2806   //
2807   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2808   // MEMORY is used as class.
2809   //
2810   // (f) Otherwise class SSE is used.
2811 
2812   // Accum should never be memory (we should have returned) or
2813   // ComplexX87 (because this cannot be passed in a structure).
2814   assert((Accum != Memory && Accum != ComplexX87) &&
2815          "Invalid accumulated classification during merge.");
2816   if (Accum == Field || Field == NoClass)
2817     return Accum;
2818   if (Field == Memory)
2819     return Memory;
2820   if (Accum == NoClass)
2821     return Field;
2822   if (Accum == Integer || Field == Integer)
2823     return Integer;
2824   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2825       Accum == X87 || Accum == X87Up)
2826     return Memory;
2827   return SSE;
2828 }
2829 
2830 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2831                              Class &Lo, Class &Hi, bool isNamedArg) const {
2832   // FIXME: This code can be simplified by introducing a simple value class for
2833   // Class pairs with appropriate constructor methods for the various
2834   // situations.
2835 
2836   // FIXME: Some of the split computations are wrong; unaligned vectors
2837   // shouldn't be passed in registers for example, so there is no chance they
2838   // can straddle an eightbyte. Verify & simplify.
2839 
2840   Lo = Hi = NoClass;
2841 
2842   Class &Current = OffsetBase < 64 ? Lo : Hi;
2843   Current = Memory;
2844 
2845   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2846     BuiltinType::Kind k = BT->getKind();
2847 
2848     if (k == BuiltinType::Void) {
2849       Current = NoClass;
2850     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2851       Lo = Integer;
2852       Hi = Integer;
2853     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2854       Current = Integer;
2855     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2856                k == BuiltinType::Float16) {
2857       Current = SSE;
2858     } else if (k == BuiltinType::LongDouble) {
2859       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2860       if (LDF == &llvm::APFloat::IEEEquad()) {
2861         Lo = SSE;
2862         Hi = SSEUp;
2863       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2864         Lo = X87;
2865         Hi = X87Up;
2866       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2867         Current = SSE;
2868       } else
2869         llvm_unreachable("unexpected long double representation!");
2870     }
2871     // FIXME: _Decimal32 and _Decimal64 are SSE.
2872     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2873     return;
2874   }
2875 
2876   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2877     // Classify the underlying integer type.
2878     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2879     return;
2880   }
2881 
2882   if (Ty->hasPointerRepresentation()) {
2883     Current = Integer;
2884     return;
2885   }
2886 
2887   if (Ty->isMemberPointerType()) {
2888     if (Ty->isMemberFunctionPointerType()) {
2889       if (Has64BitPointers) {
2890         // If Has64BitPointers, this is an {i64, i64}, so classify both
2891         // Lo and Hi now.
2892         Lo = Hi = Integer;
2893       } else {
2894         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2895         // straddles an eightbyte boundary, Hi should be classified as well.
2896         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2897         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2898         if (EB_FuncPtr != EB_ThisAdj) {
2899           Lo = Hi = Integer;
2900         } else {
2901           Current = Integer;
2902         }
2903       }
2904     } else {
2905       Current = Integer;
2906     }
2907     return;
2908   }
2909 
2910   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2911     uint64_t Size = getContext().getTypeSize(VT);
2912     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2913       // gcc passes the following as integer:
2914       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2915       // 2 bytes - <2 x char>, <1 x short>
2916       // 1 byte  - <1 x char>
2917       Current = Integer;
2918 
2919       // If this type crosses an eightbyte boundary, it should be
2920       // split.
2921       uint64_t EB_Lo = (OffsetBase) / 64;
2922       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2923       if (EB_Lo != EB_Hi)
2924         Hi = Lo;
2925     } else if (Size == 64) {
2926       QualType ElementType = VT->getElementType();
2927 
2928       // gcc passes <1 x double> in memory. :(
2929       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2930         return;
2931 
2932       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2933       // pass them as integer.  For platforms where clang is the de facto
2934       // platform compiler, we must continue to use integer.
2935       if (!classifyIntegerMMXAsSSE() &&
2936           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2937            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2938            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2939            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2940         Current = Integer;
2941       else
2942         Current = SSE;
2943 
2944       // If this type crosses an eightbyte boundary, it should be
2945       // split.
2946       if (OffsetBase && OffsetBase != 64)
2947         Hi = Lo;
2948     } else if (Size == 128 ||
2949                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2950       QualType ElementType = VT->getElementType();
2951 
2952       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2953       if (passInt128VectorsInMem() && Size != 128 &&
2954           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2955            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2956         return;
2957 
2958       // Arguments of 256-bits are split into four eightbyte chunks. The
2959       // least significant one belongs to class SSE and all the others to class
2960       // SSEUP. The original Lo and Hi design considers that types can't be
2961       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2962       // This design isn't correct for 256-bits, but since there're no cases
2963       // where the upper parts would need to be inspected, avoid adding
2964       // complexity and just consider Hi to match the 64-256 part.
2965       //
2966       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2967       // registers if they are "named", i.e. not part of the "..." of a
2968       // variadic function.
2969       //
2970       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2971       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2972       Lo = SSE;
2973       Hi = SSEUp;
2974     }
2975     return;
2976   }
2977 
2978   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2979     QualType ET = getContext().getCanonicalType(CT->getElementType());
2980 
2981     uint64_t Size = getContext().getTypeSize(Ty);
2982     if (ET->isIntegralOrEnumerationType()) {
2983       if (Size <= 64)
2984         Current = Integer;
2985       else if (Size <= 128)
2986         Lo = Hi = Integer;
2987     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2988       Current = SSE;
2989     } else if (ET == getContext().DoubleTy) {
2990       Lo = Hi = SSE;
2991     } else if (ET == getContext().LongDoubleTy) {
2992       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2993       if (LDF == &llvm::APFloat::IEEEquad())
2994         Current = Memory;
2995       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2996         Current = ComplexX87;
2997       else if (LDF == &llvm::APFloat::IEEEdouble())
2998         Lo = Hi = SSE;
2999       else
3000         llvm_unreachable("unexpected long double representation!");
3001     }
3002 
3003     // If this complex type crosses an eightbyte boundary then it
3004     // should be split.
3005     uint64_t EB_Real = (OffsetBase) / 64;
3006     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3007     if (Hi == NoClass && EB_Real != EB_Imag)
3008       Hi = Lo;
3009 
3010     return;
3011   }
3012 
3013   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3014     if (EITy->getNumBits() <= 64)
3015       Current = Integer;
3016     else if (EITy->getNumBits() <= 128)
3017       Lo = Hi = Integer;
3018     // Larger values need to get passed in memory.
3019     return;
3020   }
3021 
3022   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3023     // Arrays are treated like structures.
3024 
3025     uint64_t Size = getContext().getTypeSize(Ty);
3026 
3027     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3028     // than eight eightbytes, ..., it has class MEMORY.
3029     if (Size > 512)
3030       return;
3031 
3032     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3033     // fields, it has class MEMORY.
3034     //
3035     // Only need to check alignment of array base.
3036     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3037       return;
3038 
3039     // Otherwise implement simplified merge. We could be smarter about
3040     // this, but it isn't worth it and would be harder to verify.
3041     Current = NoClass;
3042     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3043     uint64_t ArraySize = AT->getSize().getZExtValue();
3044 
3045     // The only case a 256-bit wide vector could be used is when the array
3046     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3047     // to work for sizes wider than 128, early check and fallback to memory.
3048     //
3049     if (Size > 128 &&
3050         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3051       return;
3052 
3053     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3054       Class FieldLo, FieldHi;
3055       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3056       Lo = merge(Lo, FieldLo);
3057       Hi = merge(Hi, FieldHi);
3058       if (Lo == Memory || Hi == Memory)
3059         break;
3060     }
3061 
3062     postMerge(Size, Lo, Hi);
3063     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3064     return;
3065   }
3066 
3067   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3068     uint64_t Size = getContext().getTypeSize(Ty);
3069 
3070     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3071     // than eight eightbytes, ..., it has class MEMORY.
3072     if (Size > 512)
3073       return;
3074 
3075     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3076     // copy constructor or a non-trivial destructor, it is passed by invisible
3077     // reference.
3078     if (getRecordArgABI(RT, getCXXABI()))
3079       return;
3080 
3081     const RecordDecl *RD = RT->getDecl();
3082 
3083     // Assume variable sized types are passed in memory.
3084     if (RD->hasFlexibleArrayMember())
3085       return;
3086 
3087     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3088 
3089     // Reset Lo class, this will be recomputed.
3090     Current = NoClass;
3091 
3092     // If this is a C++ record, classify the bases first.
3093     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3094       for (const auto &I : CXXRD->bases()) {
3095         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3096                "Unexpected base class!");
3097         const auto *Base =
3098             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3099 
3100         // Classify this field.
3101         //
3102         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3103         // single eightbyte, each is classified separately. Each eightbyte gets
3104         // initialized to class NO_CLASS.
3105         Class FieldLo, FieldHi;
3106         uint64_t Offset =
3107           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3108         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3109         Lo = merge(Lo, FieldLo);
3110         Hi = merge(Hi, FieldHi);
3111         if (Lo == Memory || Hi == Memory) {
3112           postMerge(Size, Lo, Hi);
3113           return;
3114         }
3115       }
3116     }
3117 
3118     // Classify the fields one at a time, merging the results.
3119     unsigned idx = 0;
3120     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3121                                 LangOptions::ClangABI::Ver11 ||
3122                             getContext().getTargetInfo().getTriple().isPS4();
3123     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3124 
3125     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3126            i != e; ++i, ++idx) {
3127       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3128       bool BitField = i->isBitField();
3129 
3130       // Ignore padding bit-fields.
3131       if (BitField && i->isUnnamedBitfield())
3132         continue;
3133 
3134       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3135       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3136       //
3137       // The only case a 256-bit or a 512-bit wide vector could be used is when
3138       // the struct contains a single 256-bit or 512-bit element. Early check
3139       // and fallback to memory.
3140       //
3141       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3142       // than 128.
3143       if (Size > 128 &&
3144           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3145            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3146         Lo = Memory;
3147         postMerge(Size, Lo, Hi);
3148         return;
3149       }
3150       // Note, skip this test for bit-fields, see below.
3151       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3152         Lo = Memory;
3153         postMerge(Size, Lo, Hi);
3154         return;
3155       }
3156 
3157       // Classify this field.
3158       //
3159       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3160       // exceeds a single eightbyte, each is classified
3161       // separately. Each eightbyte gets initialized to class
3162       // NO_CLASS.
3163       Class FieldLo, FieldHi;
3164 
3165       // Bit-fields require special handling, they do not force the
3166       // structure to be passed in memory even if unaligned, and
3167       // therefore they can straddle an eightbyte.
3168       if (BitField) {
3169         assert(!i->isUnnamedBitfield());
3170         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3171         uint64_t Size = i->getBitWidthValue(getContext());
3172 
3173         uint64_t EB_Lo = Offset / 64;
3174         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3175 
3176         if (EB_Lo) {
3177           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3178           FieldLo = NoClass;
3179           FieldHi = Integer;
3180         } else {
3181           FieldLo = Integer;
3182           FieldHi = EB_Hi ? Integer : NoClass;
3183         }
3184       } else
3185         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3186       Lo = merge(Lo, FieldLo);
3187       Hi = merge(Hi, FieldHi);
3188       if (Lo == Memory || Hi == Memory)
3189         break;
3190     }
3191 
3192     postMerge(Size, Lo, Hi);
3193   }
3194 }
3195 
3196 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3197   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3198   // place naturally.
3199   if (!isAggregateTypeForABI(Ty)) {
3200     // Treat an enum type as its underlying type.
3201     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3202       Ty = EnumTy->getDecl()->getIntegerType();
3203 
3204     if (Ty->isBitIntType())
3205       return getNaturalAlignIndirect(Ty);
3206 
3207     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3208                                               : ABIArgInfo::getDirect());
3209   }
3210 
3211   return getNaturalAlignIndirect(Ty);
3212 }
3213 
3214 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3215   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3216     uint64_t Size = getContext().getTypeSize(VecTy);
3217     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3218     if (Size <= 64 || Size > LargestVector)
3219       return true;
3220     QualType EltTy = VecTy->getElementType();
3221     if (passInt128VectorsInMem() &&
3222         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3223          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3224       return true;
3225   }
3226 
3227   return false;
3228 }
3229 
3230 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3231                                             unsigned freeIntRegs) const {
3232   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3233   // place naturally.
3234   //
3235   // This assumption is optimistic, as there could be free registers available
3236   // when we need to pass this argument in memory, and LLVM could try to pass
3237   // the argument in the free register. This does not seem to happen currently,
3238   // but this code would be much safer if we could mark the argument with
3239   // 'onstack'. See PR12193.
3240   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3241       !Ty->isBitIntType()) {
3242     // Treat an enum type as its underlying type.
3243     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3244       Ty = EnumTy->getDecl()->getIntegerType();
3245 
3246     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3247                                               : ABIArgInfo::getDirect());
3248   }
3249 
3250   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3251     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3252 
3253   // Compute the byval alignment. We specify the alignment of the byval in all
3254   // cases so that the mid-level optimizer knows the alignment of the byval.
3255   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3256 
3257   // Attempt to avoid passing indirect results using byval when possible. This
3258   // is important for good codegen.
3259   //
3260   // We do this by coercing the value into a scalar type which the backend can
3261   // handle naturally (i.e., without using byval).
3262   //
3263   // For simplicity, we currently only do this when we have exhausted all of the
3264   // free integer registers. Doing this when there are free integer registers
3265   // would require more care, as we would have to ensure that the coerced value
3266   // did not claim the unused register. That would require either reording the
3267   // arguments to the function (so that any subsequent inreg values came first),
3268   // or only doing this optimization when there were no following arguments that
3269   // might be inreg.
3270   //
3271   // We currently expect it to be rare (particularly in well written code) for
3272   // arguments to be passed on the stack when there are still free integer
3273   // registers available (this would typically imply large structs being passed
3274   // by value), so this seems like a fair tradeoff for now.
3275   //
3276   // We can revisit this if the backend grows support for 'onstack' parameter
3277   // attributes. See PR12193.
3278   if (freeIntRegs == 0) {
3279     uint64_t Size = getContext().getTypeSize(Ty);
3280 
3281     // If this type fits in an eightbyte, coerce it into the matching integral
3282     // type, which will end up on the stack (with alignment 8).
3283     if (Align == 8 && Size <= 64)
3284       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3285                                                           Size));
3286   }
3287 
3288   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3289 }
3290 
3291 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3292 /// register. Pick an LLVM IR type that will be passed as a vector register.
3293 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3294   // Wrapper structs/arrays that only contain vectors are passed just like
3295   // vectors; strip them off if present.
3296   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3297     Ty = QualType(InnerTy, 0);
3298 
3299   llvm::Type *IRType = CGT.ConvertType(Ty);
3300   if (isa<llvm::VectorType>(IRType)) {
3301     // Don't pass vXi128 vectors in their native type, the backend can't
3302     // legalize them.
3303     if (passInt128VectorsInMem() &&
3304         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3305       // Use a vXi64 vector.
3306       uint64_t Size = getContext().getTypeSize(Ty);
3307       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3308                                         Size / 64);
3309     }
3310 
3311     return IRType;
3312   }
3313 
3314   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3315     return IRType;
3316 
3317   // We couldn't find the preferred IR vector type for 'Ty'.
3318   uint64_t Size = getContext().getTypeSize(Ty);
3319   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3320 
3321 
3322   // Return a LLVM IR vector type based on the size of 'Ty'.
3323   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3324                                     Size / 64);
3325 }
3326 
3327 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3328 /// is known to either be off the end of the specified type or being in
3329 /// alignment padding.  The user type specified is known to be at most 128 bits
3330 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3331 /// classification that put one of the two halves in the INTEGER class.
3332 ///
3333 /// It is conservatively correct to return false.
3334 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3335                                   unsigned EndBit, ASTContext &Context) {
3336   // If the bytes being queried are off the end of the type, there is no user
3337   // data hiding here.  This handles analysis of builtins, vectors and other
3338   // types that don't contain interesting padding.
3339   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3340   if (TySize <= StartBit)
3341     return true;
3342 
3343   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3344     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3345     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3346 
3347     // Check each element to see if the element overlaps with the queried range.
3348     for (unsigned i = 0; i != NumElts; ++i) {
3349       // If the element is after the span we care about, then we're done..
3350       unsigned EltOffset = i*EltSize;
3351       if (EltOffset >= EndBit) break;
3352 
3353       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3354       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3355                                  EndBit-EltOffset, Context))
3356         return false;
3357     }
3358     // If it overlaps no elements, then it is safe to process as padding.
3359     return true;
3360   }
3361 
3362   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3363     const RecordDecl *RD = RT->getDecl();
3364     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3365 
3366     // If this is a C++ record, check the bases first.
3367     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3368       for (const auto &I : CXXRD->bases()) {
3369         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3370                "Unexpected base class!");
3371         const auto *Base =
3372             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3373 
3374         // If the base is after the span we care about, ignore it.
3375         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3376         if (BaseOffset >= EndBit) continue;
3377 
3378         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3379         if (!BitsContainNoUserData(I.getType(), BaseStart,
3380                                    EndBit-BaseOffset, Context))
3381           return false;
3382       }
3383     }
3384 
3385     // Verify that no field has data that overlaps the region of interest.  Yes
3386     // this could be sped up a lot by being smarter about queried fields,
3387     // however we're only looking at structs up to 16 bytes, so we don't care
3388     // much.
3389     unsigned idx = 0;
3390     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3391          i != e; ++i, ++idx) {
3392       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3393 
3394       // If we found a field after the region we care about, then we're done.
3395       if (FieldOffset >= EndBit) break;
3396 
3397       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3398       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3399                                  Context))
3400         return false;
3401     }
3402 
3403     // If nothing in this record overlapped the area of interest, then we're
3404     // clean.
3405     return true;
3406   }
3407 
3408   return false;
3409 }
3410 
3411 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3412 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3413                                      const llvm::DataLayout &TD) {
3414   if (IROffset == 0 && IRType->isFloatingPointTy())
3415     return IRType;
3416 
3417   // If this is a struct, recurse into the field at the specified offset.
3418   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3419     if (!STy->getNumContainedTypes())
3420       return nullptr;
3421 
3422     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3423     unsigned Elt = SL->getElementContainingOffset(IROffset);
3424     IROffset -= SL->getElementOffset(Elt);
3425     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3426   }
3427 
3428   // If this is an array, recurse into the field at the specified offset.
3429   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3430     llvm::Type *EltTy = ATy->getElementType();
3431     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3432     IROffset -= IROffset / EltSize * EltSize;
3433     return getFPTypeAtOffset(EltTy, IROffset, TD);
3434   }
3435 
3436   return nullptr;
3437 }
3438 
3439 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3440 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3441 llvm::Type *X86_64ABIInfo::
3442 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3443                    QualType SourceTy, unsigned SourceOffset) const {
3444   const llvm::DataLayout &TD = getDataLayout();
3445   unsigned SourceSize =
3446       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3447   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3448   if (!T0 || T0->isDoubleTy())
3449     return llvm::Type::getDoubleTy(getVMContext());
3450 
3451   // Get the adjacent FP type.
3452   llvm::Type *T1 = nullptr;
3453   unsigned T0Size = TD.getTypeAllocSize(T0);
3454   if (SourceSize > T0Size)
3455       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3456   if (T1 == nullptr) {
3457     // Check if IRType is a half + float. float type will be in IROffset+4 due
3458     // to its alignment.
3459     if (T0->isHalfTy() && SourceSize > 4)
3460       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3461     // If we can't get a second FP type, return a simple half or float.
3462     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3463     // {float, i8} too.
3464     if (T1 == nullptr)
3465       return T0;
3466   }
3467 
3468   if (T0->isFloatTy() && T1->isFloatTy())
3469     return llvm::FixedVectorType::get(T0, 2);
3470 
3471   if (T0->isHalfTy() && T1->isHalfTy()) {
3472     llvm::Type *T2 = nullptr;
3473     if (SourceSize > 4)
3474       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3475     if (T2 == nullptr)
3476       return llvm::FixedVectorType::get(T0, 2);
3477     return llvm::FixedVectorType::get(T0, 4);
3478   }
3479 
3480   if (T0->isHalfTy() || T1->isHalfTy())
3481     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3482 
3483   return llvm::Type::getDoubleTy(getVMContext());
3484 }
3485 
3486 
3487 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3488 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3489 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3490 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3491 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3492 /// etc).
3493 ///
3494 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3495 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3496 /// the 8-byte value references.  PrefType may be null.
3497 ///
3498 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3499 /// an offset into this that we're processing (which is always either 0 or 8).
3500 ///
3501 llvm::Type *X86_64ABIInfo::
3502 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3503                        QualType SourceTy, unsigned SourceOffset) const {
3504   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3505   // returning an 8-byte unit starting with it.  See if we can safely use it.
3506   if (IROffset == 0) {
3507     // Pointers and int64's always fill the 8-byte unit.
3508     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3509         IRType->isIntegerTy(64))
3510       return IRType;
3511 
3512     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3513     // goodness in the source type is just tail padding.  This is allowed to
3514     // kick in for struct {double,int} on the int, but not on
3515     // struct{double,int,int} because we wouldn't return the second int.  We
3516     // have to do this analysis on the source type because we can't depend on
3517     // unions being lowered a specific way etc.
3518     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3519         IRType->isIntegerTy(32) ||
3520         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3521       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3522           cast<llvm::IntegerType>(IRType)->getBitWidth();
3523 
3524       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3525                                 SourceOffset*8+64, getContext()))
3526         return IRType;
3527     }
3528   }
3529 
3530   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3531     // If this is a struct, recurse into the field at the specified offset.
3532     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3533     if (IROffset < SL->getSizeInBytes()) {
3534       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3535       IROffset -= SL->getElementOffset(FieldIdx);
3536 
3537       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3538                                     SourceTy, SourceOffset);
3539     }
3540   }
3541 
3542   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3543     llvm::Type *EltTy = ATy->getElementType();
3544     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3545     unsigned EltOffset = IROffset/EltSize*EltSize;
3546     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3547                                   SourceOffset);
3548   }
3549 
3550   // Okay, we don't have any better idea of what to pass, so we pass this in an
3551   // integer register that isn't too big to fit the rest of the struct.
3552   unsigned TySizeInBytes =
3553     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3554 
3555   assert(TySizeInBytes != SourceOffset && "Empty field?");
3556 
3557   // It is always safe to classify this as an integer type up to i64 that
3558   // isn't larger than the structure.
3559   return llvm::IntegerType::get(getVMContext(),
3560                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3561 }
3562 
3563 
3564 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3565 /// be used as elements of a two register pair to pass or return, return a
3566 /// first class aggregate to represent them.  For example, if the low part of
3567 /// a by-value argument should be passed as i32* and the high part as float,
3568 /// return {i32*, float}.
3569 static llvm::Type *
3570 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3571                            const llvm::DataLayout &TD) {
3572   // In order to correctly satisfy the ABI, we need to the high part to start
3573   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3574   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3575   // the second element at offset 8.  Check for this:
3576   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3577   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3578   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3579   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3580 
3581   // To handle this, we have to increase the size of the low part so that the
3582   // second element will start at an 8 byte offset.  We can't increase the size
3583   // of the second element because it might make us access off the end of the
3584   // struct.
3585   if (HiStart != 8) {
3586     // There are usually two sorts of types the ABI generation code can produce
3587     // for the low part of a pair that aren't 8 bytes in size: half, float or
3588     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3589     // NaCl).
3590     // Promote these to a larger type.
3591     if (Lo->isHalfTy() || Lo->isFloatTy())
3592       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3593     else {
3594       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3595              && "Invalid/unknown lo type");
3596       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3597     }
3598   }
3599 
3600   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3601 
3602   // Verify that the second element is at an 8-byte offset.
3603   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3604          "Invalid x86-64 argument pair!");
3605   return Result;
3606 }
3607 
3608 ABIArgInfo X86_64ABIInfo::
3609 classifyReturnType(QualType RetTy) const {
3610   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3611   // classification algorithm.
3612   X86_64ABIInfo::Class Lo, Hi;
3613   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3614 
3615   // Check some invariants.
3616   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3617   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3618 
3619   llvm::Type *ResType = nullptr;
3620   switch (Lo) {
3621   case NoClass:
3622     if (Hi == NoClass)
3623       return ABIArgInfo::getIgnore();
3624     // If the low part is just padding, it takes no register, leave ResType
3625     // null.
3626     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3627            "Unknown missing lo part");
3628     break;
3629 
3630   case SSEUp:
3631   case X87Up:
3632     llvm_unreachable("Invalid classification for lo word.");
3633 
3634     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3635     // hidden argument.
3636   case Memory:
3637     return getIndirectReturnResult(RetTy);
3638 
3639     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3640     // available register of the sequence %rax, %rdx is used.
3641   case Integer:
3642     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3643 
3644     // If we have a sign or zero extended integer, make sure to return Extend
3645     // so that the parameter gets the right LLVM IR attributes.
3646     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3647       // Treat an enum type as its underlying type.
3648       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3649         RetTy = EnumTy->getDecl()->getIntegerType();
3650 
3651       if (RetTy->isIntegralOrEnumerationType() &&
3652           isPromotableIntegerTypeForABI(RetTy))
3653         return ABIArgInfo::getExtend(RetTy);
3654     }
3655     break;
3656 
3657     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3658     // available SSE register of the sequence %xmm0, %xmm1 is used.
3659   case SSE:
3660     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3661     break;
3662 
3663     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3664     // returned on the X87 stack in %st0 as 80-bit x87 number.
3665   case X87:
3666     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3667     break;
3668 
3669     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3670     // part of the value is returned in %st0 and the imaginary part in
3671     // %st1.
3672   case ComplexX87:
3673     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3674     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3675                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3676     break;
3677   }
3678 
3679   llvm::Type *HighPart = nullptr;
3680   switch (Hi) {
3681     // Memory was handled previously and X87 should
3682     // never occur as a hi class.
3683   case Memory:
3684   case X87:
3685     llvm_unreachable("Invalid classification for hi word.");
3686 
3687   case ComplexX87: // Previously handled.
3688   case NoClass:
3689     break;
3690 
3691   case Integer:
3692     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3693     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3694       return ABIArgInfo::getDirect(HighPart, 8);
3695     break;
3696   case SSE:
3697     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3698     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3699       return ABIArgInfo::getDirect(HighPart, 8);
3700     break;
3701 
3702     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3703     // is passed in the next available eightbyte chunk if the last used
3704     // vector register.
3705     //
3706     // SSEUP should always be preceded by SSE, just widen.
3707   case SSEUp:
3708     assert(Lo == SSE && "Unexpected SSEUp classification.");
3709     ResType = GetByteVectorType(RetTy);
3710     break;
3711 
3712     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3713     // returned together with the previous X87 value in %st0.
3714   case X87Up:
3715     // If X87Up is preceded by X87, we don't need to do
3716     // anything. However, in some cases with unions it may not be
3717     // preceded by X87. In such situations we follow gcc and pass the
3718     // extra bits in an SSE reg.
3719     if (Lo != X87) {
3720       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3721       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3722         return ABIArgInfo::getDirect(HighPart, 8);
3723     }
3724     break;
3725   }
3726 
3727   // If a high part was specified, merge it together with the low part.  It is
3728   // known to pass in the high eightbyte of the result.  We do this by forming a
3729   // first class struct aggregate with the high and low part: {low, high}
3730   if (HighPart)
3731     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3732 
3733   return ABIArgInfo::getDirect(ResType);
3734 }
3735 
3736 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3737   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3738   bool isNamedArg)
3739   const
3740 {
3741   Ty = useFirstFieldIfTransparentUnion(Ty);
3742 
3743   X86_64ABIInfo::Class Lo, Hi;
3744   classify(Ty, 0, Lo, Hi, isNamedArg);
3745 
3746   // Check some invariants.
3747   // FIXME: Enforce these by construction.
3748   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3749   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3750 
3751   neededInt = 0;
3752   neededSSE = 0;
3753   llvm::Type *ResType = nullptr;
3754   switch (Lo) {
3755   case NoClass:
3756     if (Hi == NoClass)
3757       return ABIArgInfo::getIgnore();
3758     // If the low part is just padding, it takes no register, leave ResType
3759     // null.
3760     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3761            "Unknown missing lo part");
3762     break;
3763 
3764     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3765     // on the stack.
3766   case Memory:
3767 
3768     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3769     // COMPLEX_X87, it is passed in memory.
3770   case X87:
3771   case ComplexX87:
3772     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3773       ++neededInt;
3774     return getIndirectResult(Ty, freeIntRegs);
3775 
3776   case SSEUp:
3777   case X87Up:
3778     llvm_unreachable("Invalid classification for lo word.");
3779 
3780     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3781     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3782     // and %r9 is used.
3783   case Integer:
3784     ++neededInt;
3785 
3786     // Pick an 8-byte type based on the preferred type.
3787     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3788 
3789     // If we have a sign or zero extended integer, make sure to return Extend
3790     // so that the parameter gets the right LLVM IR attributes.
3791     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3792       // Treat an enum type as its underlying type.
3793       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3794         Ty = EnumTy->getDecl()->getIntegerType();
3795 
3796       if (Ty->isIntegralOrEnumerationType() &&
3797           isPromotableIntegerTypeForABI(Ty))
3798         return ABIArgInfo::getExtend(Ty);
3799     }
3800 
3801     break;
3802 
3803     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3804     // available SSE register is used, the registers are taken in the
3805     // order from %xmm0 to %xmm7.
3806   case SSE: {
3807     llvm::Type *IRType = CGT.ConvertType(Ty);
3808     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3809     ++neededSSE;
3810     break;
3811   }
3812   }
3813 
3814   llvm::Type *HighPart = nullptr;
3815   switch (Hi) {
3816     // Memory was handled previously, ComplexX87 and X87 should
3817     // never occur as hi classes, and X87Up must be preceded by X87,
3818     // which is passed in memory.
3819   case Memory:
3820   case X87:
3821   case ComplexX87:
3822     llvm_unreachable("Invalid classification for hi word.");
3823 
3824   case NoClass: break;
3825 
3826   case Integer:
3827     ++neededInt;
3828     // Pick an 8-byte type based on the preferred type.
3829     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3830 
3831     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3832       return ABIArgInfo::getDirect(HighPart, 8);
3833     break;
3834 
3835     // X87Up generally doesn't occur here (long double is passed in
3836     // memory), except in situations involving unions.
3837   case X87Up:
3838   case SSE:
3839     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3840 
3841     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3842       return ABIArgInfo::getDirect(HighPart, 8);
3843 
3844     ++neededSSE;
3845     break;
3846 
3847     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3848     // eightbyte is passed in the upper half of the last used SSE
3849     // register.  This only happens when 128-bit vectors are passed.
3850   case SSEUp:
3851     assert(Lo == SSE && "Unexpected SSEUp classification");
3852     ResType = GetByteVectorType(Ty);
3853     break;
3854   }
3855 
3856   // If a high part was specified, merge it together with the low part.  It is
3857   // known to pass in the high eightbyte of the result.  We do this by forming a
3858   // first class struct aggregate with the high and low part: {low, high}
3859   if (HighPart)
3860     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3861 
3862   return ABIArgInfo::getDirect(ResType);
3863 }
3864 
3865 ABIArgInfo
3866 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3867                                              unsigned &NeededSSE) const {
3868   auto RT = Ty->getAs<RecordType>();
3869   assert(RT && "classifyRegCallStructType only valid with struct types");
3870 
3871   if (RT->getDecl()->hasFlexibleArrayMember())
3872     return getIndirectReturnResult(Ty);
3873 
3874   // Sum up bases
3875   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3876     if (CXXRD->isDynamicClass()) {
3877       NeededInt = NeededSSE = 0;
3878       return getIndirectReturnResult(Ty);
3879     }
3880 
3881     for (const auto &I : CXXRD->bases())
3882       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3883               .isIndirect()) {
3884         NeededInt = NeededSSE = 0;
3885         return getIndirectReturnResult(Ty);
3886       }
3887   }
3888 
3889   // Sum up members
3890   for (const auto *FD : RT->getDecl()->fields()) {
3891     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3892       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3893               .isIndirect()) {
3894         NeededInt = NeededSSE = 0;
3895         return getIndirectReturnResult(Ty);
3896       }
3897     } else {
3898       unsigned LocalNeededInt, LocalNeededSSE;
3899       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3900                                LocalNeededSSE, true)
3901               .isIndirect()) {
3902         NeededInt = NeededSSE = 0;
3903         return getIndirectReturnResult(Ty);
3904       }
3905       NeededInt += LocalNeededInt;
3906       NeededSSE += LocalNeededSSE;
3907     }
3908   }
3909 
3910   return ABIArgInfo::getDirect();
3911 }
3912 
3913 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3914                                                     unsigned &NeededInt,
3915                                                     unsigned &NeededSSE) const {
3916 
3917   NeededInt = 0;
3918   NeededSSE = 0;
3919 
3920   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3921 }
3922 
3923 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3924 
3925   const unsigned CallingConv = FI.getCallingConvention();
3926   // It is possible to force Win64 calling convention on any x86_64 target by
3927   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3928   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3929   if (CallingConv == llvm::CallingConv::Win64) {
3930     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3931     Win64ABIInfo.computeInfo(FI);
3932     return;
3933   }
3934 
3935   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3936 
3937   // Keep track of the number of assigned registers.
3938   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3939   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3940   unsigned NeededInt, NeededSSE;
3941 
3942   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3943     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3944         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3945       FI.getReturnInfo() =
3946           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3947       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3948         FreeIntRegs -= NeededInt;
3949         FreeSSERegs -= NeededSSE;
3950       } else {
3951         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3952       }
3953     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3954                getContext().getCanonicalType(FI.getReturnType()
3955                                                  ->getAs<ComplexType>()
3956                                                  ->getElementType()) ==
3957                    getContext().LongDoubleTy)
3958       // Complex Long Double Type is passed in Memory when Regcall
3959       // calling convention is used.
3960       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3961     else
3962       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3963   }
3964 
3965   // If the return value is indirect, then the hidden argument is consuming one
3966   // integer register.
3967   if (FI.getReturnInfo().isIndirect())
3968     --FreeIntRegs;
3969 
3970   // The chain argument effectively gives us another free register.
3971   if (FI.isChainCall())
3972     ++FreeIntRegs;
3973 
3974   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3975   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3976   // get assigned (in left-to-right order) for passing as follows...
3977   unsigned ArgNo = 0;
3978   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3979        it != ie; ++it, ++ArgNo) {
3980     bool IsNamedArg = ArgNo < NumRequiredArgs;
3981 
3982     if (IsRegCall && it->type->isStructureOrClassType())
3983       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3984     else
3985       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3986                                       NeededSSE, IsNamedArg);
3987 
3988     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3989     // eightbyte of an argument, the whole argument is passed on the
3990     // stack. If registers have already been assigned for some
3991     // eightbytes of such an argument, the assignments get reverted.
3992     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3993       FreeIntRegs -= NeededInt;
3994       FreeSSERegs -= NeededSSE;
3995     } else {
3996       it->info = getIndirectResult(it->type, FreeIntRegs);
3997     }
3998   }
3999 }
4000 
4001 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4002                                          Address VAListAddr, QualType Ty) {
4003   Address overflow_arg_area_p =
4004       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4005   llvm::Value *overflow_arg_area =
4006     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4007 
4008   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4009   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4010   // It isn't stated explicitly in the standard, but in practice we use
4011   // alignment greater than 16 where necessary.
4012   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4013   if (Align > CharUnits::fromQuantity(8)) {
4014     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4015                                                       Align);
4016   }
4017 
4018   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4019   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4020   llvm::Value *Res =
4021     CGF.Builder.CreateBitCast(overflow_arg_area,
4022                               llvm::PointerType::getUnqual(LTy));
4023 
4024   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4025   // l->overflow_arg_area + sizeof(type).
4026   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4027   // an 8 byte boundary.
4028 
4029   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4030   llvm::Value *Offset =
4031       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4032   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4033                                             Offset, "overflow_arg_area.next");
4034   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4035 
4036   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4037   return Address(Res, LTy, Align);
4038 }
4039 
4040 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4041                                  QualType Ty) const {
4042   // Assume that va_list type is correct; should be pointer to LLVM type:
4043   // struct {
4044   //   i32 gp_offset;
4045   //   i32 fp_offset;
4046   //   i8* overflow_arg_area;
4047   //   i8* reg_save_area;
4048   // };
4049   unsigned neededInt, neededSSE;
4050 
4051   Ty = getContext().getCanonicalType(Ty);
4052   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4053                                        /*isNamedArg*/false);
4054 
4055   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4056   // in the registers. If not go to step 7.
4057   if (!neededInt && !neededSSE)
4058     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4059 
4060   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4061   // general purpose registers needed to pass type and num_fp to hold
4062   // the number of floating point registers needed.
4063 
4064   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4065   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4066   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4067   //
4068   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4069   // register save space).
4070 
4071   llvm::Value *InRegs = nullptr;
4072   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4073   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4074   if (neededInt) {
4075     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4076     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4077     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4078     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4079   }
4080 
4081   if (neededSSE) {
4082     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4083     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4084     llvm::Value *FitsInFP =
4085       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4086     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4087     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4088   }
4089 
4090   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4091   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4092   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4093   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4094 
4095   // Emit code to load the value if it was passed in registers.
4096 
4097   CGF.EmitBlock(InRegBlock);
4098 
4099   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4100   // an offset of l->gp_offset and/or l->fp_offset. This may require
4101   // copying to a temporary location in case the parameter is passed
4102   // in different register classes or requires an alignment greater
4103   // than 8 for general purpose registers and 16 for XMM registers.
4104   //
4105   // FIXME: This really results in shameful code when we end up needing to
4106   // collect arguments from different places; often what should result in a
4107   // simple assembling of a structure from scattered addresses has many more
4108   // loads than necessary. Can we clean this up?
4109   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4110   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4111       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4112 
4113   Address RegAddr = Address::invalid();
4114   if (neededInt && neededSSE) {
4115     // FIXME: Cleanup.
4116     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4117     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4118     Address Tmp = CGF.CreateMemTemp(Ty);
4119     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4120     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4121     llvm::Type *TyLo = ST->getElementType(0);
4122     llvm::Type *TyHi = ST->getElementType(1);
4123     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4124            "Unexpected ABI info for mixed regs");
4125     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4126     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4127     llvm::Value *GPAddr =
4128         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4129     llvm::Value *FPAddr =
4130         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4131     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4132     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4133 
4134     // Copy the first element.
4135     // FIXME: Our choice of alignment here and below is probably pessimistic.
4136     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4137         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4138         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4139     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4140 
4141     // Copy the second element.
4142     V = CGF.Builder.CreateAlignedLoad(
4143         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4144         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4145     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4146 
4147     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4148   } else if (neededInt) {
4149     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4150                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4151     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4152 
4153     // Copy to a temporary if necessary to ensure the appropriate alignment.
4154     auto TInfo = getContext().getTypeInfoInChars(Ty);
4155     uint64_t TySize = TInfo.Width.getQuantity();
4156     CharUnits TyAlign = TInfo.Align;
4157 
4158     // Copy into a temporary if the type is more aligned than the
4159     // register save area.
4160     if (TyAlign.getQuantity() > 8) {
4161       Address Tmp = CGF.CreateMemTemp(Ty);
4162       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4163       RegAddr = Tmp;
4164     }
4165 
4166   } else if (neededSSE == 1) {
4167     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4168                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4169     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4170   } else {
4171     assert(neededSSE == 2 && "Invalid number of needed registers!");
4172     // SSE registers are spaced 16 bytes apart in the register save
4173     // area, we need to collect the two eightbytes together.
4174     // The ABI isn't explicit about this, but it seems reasonable
4175     // to assume that the slots are 16-byte aligned, since the stack is
4176     // naturally 16-byte aligned and the prologue is expected to store
4177     // all the SSE registers to the RSA.
4178     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4179                                                       fp_offset),
4180                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4181     Address RegAddrHi =
4182       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4183                                              CharUnits::fromQuantity(16));
4184     llvm::Type *ST = AI.canHaveCoerceToType()
4185                          ? AI.getCoerceToType()
4186                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4187     llvm::Value *V;
4188     Address Tmp = CGF.CreateMemTemp(Ty);
4189     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4190     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4191         RegAddrLo, ST->getStructElementType(0)));
4192     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4193     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4194         RegAddrHi, ST->getStructElementType(1)));
4195     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4196 
4197     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4198   }
4199 
4200   // AMD64-ABI 3.5.7p5: Step 5. Set:
4201   // l->gp_offset = l->gp_offset + num_gp * 8
4202   // l->fp_offset = l->fp_offset + num_fp * 16.
4203   if (neededInt) {
4204     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4205     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4206                             gp_offset_p);
4207   }
4208   if (neededSSE) {
4209     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4210     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4211                             fp_offset_p);
4212   }
4213   CGF.EmitBranch(ContBlock);
4214 
4215   // Emit code to load the value if it was passed in memory.
4216 
4217   CGF.EmitBlock(InMemBlock);
4218   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4219 
4220   // Return the appropriate result.
4221 
4222   CGF.EmitBlock(ContBlock);
4223   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4224                                  "vaarg.addr");
4225   return ResAddr;
4226 }
4227 
4228 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4229                                    QualType Ty) const {
4230   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4231   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4232   uint64_t Width = getContext().getTypeSize(Ty);
4233   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4234 
4235   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4236                           CGF.getContext().getTypeInfoInChars(Ty),
4237                           CharUnits::fromQuantity(8),
4238                           /*allowHigherAlign*/ false);
4239 }
4240 
4241 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4242     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4243   const Type *Base = nullptr;
4244   uint64_t NumElts = 0;
4245 
4246   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4247       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4248     FreeSSERegs -= NumElts;
4249     return getDirectX86Hva();
4250   }
4251   return current;
4252 }
4253 
4254 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4255                                       bool IsReturnType, bool IsVectorCall,
4256                                       bool IsRegCall) const {
4257 
4258   if (Ty->isVoidType())
4259     return ABIArgInfo::getIgnore();
4260 
4261   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4262     Ty = EnumTy->getDecl()->getIntegerType();
4263 
4264   TypeInfo Info = getContext().getTypeInfo(Ty);
4265   uint64_t Width = Info.Width;
4266   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4267 
4268   const RecordType *RT = Ty->getAs<RecordType>();
4269   if (RT) {
4270     if (!IsReturnType) {
4271       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4272         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4273     }
4274 
4275     if (RT->getDecl()->hasFlexibleArrayMember())
4276       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4277 
4278   }
4279 
4280   const Type *Base = nullptr;
4281   uint64_t NumElts = 0;
4282   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4283   // other targets.
4284   if ((IsVectorCall || IsRegCall) &&
4285       isHomogeneousAggregate(Ty, Base, NumElts)) {
4286     if (IsRegCall) {
4287       if (FreeSSERegs >= NumElts) {
4288         FreeSSERegs -= NumElts;
4289         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4290           return ABIArgInfo::getDirect();
4291         return ABIArgInfo::getExpand();
4292       }
4293       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4294     } else if (IsVectorCall) {
4295       if (FreeSSERegs >= NumElts &&
4296           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4297         FreeSSERegs -= NumElts;
4298         return ABIArgInfo::getDirect();
4299       } else if (IsReturnType) {
4300         return ABIArgInfo::getExpand();
4301       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4302         // HVAs are delayed and reclassified in the 2nd step.
4303         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4304       }
4305     }
4306   }
4307 
4308   if (Ty->isMemberPointerType()) {
4309     // If the member pointer is represented by an LLVM int or ptr, pass it
4310     // directly.
4311     llvm::Type *LLTy = CGT.ConvertType(Ty);
4312     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4313       return ABIArgInfo::getDirect();
4314   }
4315 
4316   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4317     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4318     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4319     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4320       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4321 
4322     // Otherwise, coerce it to a small integer.
4323     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4324   }
4325 
4326   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4327     switch (BT->getKind()) {
4328     case BuiltinType::Bool:
4329       // Bool type is always extended to the ABI, other builtin types are not
4330       // extended.
4331       return ABIArgInfo::getExtend(Ty);
4332 
4333     case BuiltinType::LongDouble:
4334       // Mingw64 GCC uses the old 80 bit extended precision floating point
4335       // unit. It passes them indirectly through memory.
4336       if (IsMingw64) {
4337         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4338         if (LDF == &llvm::APFloat::x87DoubleExtended())
4339           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4340       }
4341       break;
4342 
4343     case BuiltinType::Int128:
4344     case BuiltinType::UInt128:
4345       // If it's a parameter type, the normal ABI rule is that arguments larger
4346       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4347       // even though it isn't particularly efficient.
4348       if (!IsReturnType)
4349         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4350 
4351       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4352       // Clang matches them for compatibility.
4353       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4354           llvm::Type::getInt64Ty(getVMContext()), 2));
4355 
4356     default:
4357       break;
4358     }
4359   }
4360 
4361   if (Ty->isBitIntType()) {
4362     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4363     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4364     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4365     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4366     // the power of 2.
4367     if (Width <= 64)
4368       return ABIArgInfo::getDirect();
4369     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4370   }
4371 
4372   return ABIArgInfo::getDirect();
4373 }
4374 
4375 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4376   const unsigned CC = FI.getCallingConvention();
4377   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4378   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4379 
4380   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4381   // classification rules.
4382   if (CC == llvm::CallingConv::X86_64_SysV) {
4383     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4384     SysVABIInfo.computeInfo(FI);
4385     return;
4386   }
4387 
4388   unsigned FreeSSERegs = 0;
4389   if (IsVectorCall) {
4390     // We can use up to 4 SSE return registers with vectorcall.
4391     FreeSSERegs = 4;
4392   } else if (IsRegCall) {
4393     // RegCall gives us 16 SSE registers.
4394     FreeSSERegs = 16;
4395   }
4396 
4397   if (!getCXXABI().classifyReturnType(FI))
4398     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4399                                   IsVectorCall, IsRegCall);
4400 
4401   if (IsVectorCall) {
4402     // We can use up to 6 SSE register parameters with vectorcall.
4403     FreeSSERegs = 6;
4404   } else if (IsRegCall) {
4405     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4406     FreeSSERegs = 16;
4407   }
4408 
4409   unsigned ArgNum = 0;
4410   unsigned ZeroSSERegs = 0;
4411   for (auto &I : FI.arguments()) {
4412     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4413     // XMM/YMM registers. After the sixth argument, pretend no vector
4414     // registers are left.
4415     unsigned *MaybeFreeSSERegs =
4416         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4417     I.info =
4418         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4419     ++ArgNum;
4420   }
4421 
4422   if (IsVectorCall) {
4423     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4424     // second pass.
4425     for (auto &I : FI.arguments())
4426       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4427   }
4428 }
4429 
4430 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4431                                     QualType Ty) const {
4432   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4433   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4434   uint64_t Width = getContext().getTypeSize(Ty);
4435   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4436 
4437   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4438                           CGF.getContext().getTypeInfoInChars(Ty),
4439                           CharUnits::fromQuantity(8),
4440                           /*allowHigherAlign*/ false);
4441 }
4442 
4443 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4444                                         llvm::Value *Address, bool Is64Bit,
4445                                         bool IsAIX) {
4446   // This is calculated from the LLVM and GCC tables and verified
4447   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4448 
4449   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4450 
4451   llvm::IntegerType *i8 = CGF.Int8Ty;
4452   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4453   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4454   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4455 
4456   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4457   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4458 
4459   // 32-63: fp0-31, the 8-byte floating-point registers
4460   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4461 
4462   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4463   // 64: mq
4464   // 65: lr
4465   // 66: ctr
4466   // 67: ap
4467   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4468 
4469   // 68-76 are various 4-byte special-purpose registers:
4470   // 68-75 cr0-7
4471   // 76: xer
4472   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4473 
4474   // 77-108: v0-31, the 16-byte vector registers
4475   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4476 
4477   // 109: vrsave
4478   // 110: vscr
4479   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4480 
4481   // AIX does not utilize the rest of the registers.
4482   if (IsAIX)
4483     return false;
4484 
4485   // 111: spe_acc
4486   // 112: spefscr
4487   // 113: sfp
4488   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4489 
4490   if (!Is64Bit)
4491     return false;
4492 
4493   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4494   // or above CPU.
4495   // 64-bit only registers:
4496   // 114: tfhar
4497   // 115: tfiar
4498   // 116: texasr
4499   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4500 
4501   return false;
4502 }
4503 
4504 // AIX
4505 namespace {
4506 /// AIXABIInfo - The AIX XCOFF ABI information.
4507 class AIXABIInfo : public ABIInfo {
4508   const bool Is64Bit;
4509   const unsigned PtrByteSize;
4510   CharUnits getParamTypeAlignment(QualType Ty) const;
4511 
4512 public:
4513   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4514       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4515 
4516   bool isPromotableTypeForABI(QualType Ty) const;
4517 
4518   ABIArgInfo classifyReturnType(QualType RetTy) const;
4519   ABIArgInfo classifyArgumentType(QualType Ty) const;
4520 
4521   void computeInfo(CGFunctionInfo &FI) const override {
4522     if (!getCXXABI().classifyReturnType(FI))
4523       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4524 
4525     for (auto &I : FI.arguments())
4526       I.info = classifyArgumentType(I.type);
4527   }
4528 
4529   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4530                     QualType Ty) const override;
4531 };
4532 
4533 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4534   const bool Is64Bit;
4535 
4536 public:
4537   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4538       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4539         Is64Bit(Is64Bit) {}
4540   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4541     return 1; // r1 is the dedicated stack pointer
4542   }
4543 
4544   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4545                                llvm::Value *Address) const override;
4546 };
4547 } // namespace
4548 
4549 // Return true if the ABI requires Ty to be passed sign- or zero-
4550 // extended to 32/64 bits.
4551 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4552   // Treat an enum type as its underlying type.
4553   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4554     Ty = EnumTy->getDecl()->getIntegerType();
4555 
4556   // Promotable integer types are required to be promoted by the ABI.
4557   if (Ty->isPromotableIntegerType())
4558     return true;
4559 
4560   if (!Is64Bit)
4561     return false;
4562 
4563   // For 64 bit mode, in addition to the usual promotable integer types, we also
4564   // need to extend all 32-bit types, since the ABI requires promotion to 64
4565   // bits.
4566   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4567     switch (BT->getKind()) {
4568     case BuiltinType::Int:
4569     case BuiltinType::UInt:
4570       return true;
4571     default:
4572       break;
4573     }
4574 
4575   return false;
4576 }
4577 
4578 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4579   if (RetTy->isAnyComplexType())
4580     return ABIArgInfo::getDirect();
4581 
4582   if (RetTy->isVectorType())
4583     return ABIArgInfo::getDirect();
4584 
4585   if (RetTy->isVoidType())
4586     return ABIArgInfo::getIgnore();
4587 
4588   if (isAggregateTypeForABI(RetTy))
4589     return getNaturalAlignIndirect(RetTy);
4590 
4591   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4592                                         : ABIArgInfo::getDirect());
4593 }
4594 
4595 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4596   Ty = useFirstFieldIfTransparentUnion(Ty);
4597 
4598   if (Ty->isAnyComplexType())
4599     return ABIArgInfo::getDirect();
4600 
4601   if (Ty->isVectorType())
4602     return ABIArgInfo::getDirect();
4603 
4604   if (isAggregateTypeForABI(Ty)) {
4605     // Records with non-trivial destructors/copy-constructors should not be
4606     // passed by value.
4607     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4608       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4609 
4610     CharUnits CCAlign = getParamTypeAlignment(Ty);
4611     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4612 
4613     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4614                                    /*Realign*/ TyAlign > CCAlign);
4615   }
4616 
4617   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4618                                      : ABIArgInfo::getDirect());
4619 }
4620 
4621 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4622   // Complex types are passed just like their elements.
4623   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4624     Ty = CTy->getElementType();
4625 
4626   if (Ty->isVectorType())
4627     return CharUnits::fromQuantity(16);
4628 
4629   // If the structure contains a vector type, the alignment is 16.
4630   if (isRecordWithSIMDVectorType(getContext(), Ty))
4631     return CharUnits::fromQuantity(16);
4632 
4633   return CharUnits::fromQuantity(PtrByteSize);
4634 }
4635 
4636 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4637                               QualType Ty) const {
4638 
4639   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4640   TypeInfo.Align = getParamTypeAlignment(Ty);
4641 
4642   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4643 
4644   // If we have a complex type and the base type is smaller than the register
4645   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4646   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4647   // Clang expects us to produce a pointer to a structure with the two parts
4648   // packed tightly. So generate loads of the real and imaginary parts relative
4649   // to the va_list pointer, and store them to a temporary structure. We do the
4650   // same as the PPC64ABI here.
4651   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4652     CharUnits EltSize = TypeInfo.Width / 2;
4653     if (EltSize < SlotSize)
4654       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4655   }
4656 
4657   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4658                           SlotSize, /*AllowHigher*/ true);
4659 }
4660 
4661 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4662     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4663   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4664 }
4665 
4666 // PowerPC-32
4667 namespace {
4668 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4669 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4670   bool IsSoftFloatABI;
4671   bool IsRetSmallStructInRegABI;
4672 
4673   CharUnits getParamTypeAlignment(QualType Ty) const;
4674 
4675 public:
4676   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4677                      bool RetSmallStructInRegABI)
4678       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4679         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4680 
4681   ABIArgInfo classifyReturnType(QualType RetTy) const;
4682 
4683   void computeInfo(CGFunctionInfo &FI) const override {
4684     if (!getCXXABI().classifyReturnType(FI))
4685       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4686     for (auto &I : FI.arguments())
4687       I.info = classifyArgumentType(I.type);
4688   }
4689 
4690   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4691                     QualType Ty) const override;
4692 };
4693 
4694 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4695 public:
4696   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4697                          bool RetSmallStructInRegABI)
4698       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4699             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4700 
4701   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4702                                      const CodeGenOptions &Opts);
4703 
4704   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4705     // This is recovered from gcc output.
4706     return 1; // r1 is the dedicated stack pointer
4707   }
4708 
4709   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4710                                llvm::Value *Address) const override;
4711 };
4712 }
4713 
4714 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4715   // Complex types are passed just like their elements.
4716   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4717     Ty = CTy->getElementType();
4718 
4719   if (Ty->isVectorType())
4720     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4721                                                                        : 4);
4722 
4723   // For single-element float/vector structs, we consider the whole type
4724   // to have the same alignment requirements as its single element.
4725   const Type *AlignTy = nullptr;
4726   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4727     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4728     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4729         (BT && BT->isFloatingPoint()))
4730       AlignTy = EltType;
4731   }
4732 
4733   if (AlignTy)
4734     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4735   return CharUnits::fromQuantity(4);
4736 }
4737 
4738 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4739   uint64_t Size;
4740 
4741   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4742   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4743       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4744     // System V ABI (1995), page 3-22, specified:
4745     // > A structure or union whose size is less than or equal to 8 bytes
4746     // > shall be returned in r3 and r4, as if it were first stored in the
4747     // > 8-byte aligned memory area and then the low addressed word were
4748     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4749     // > the last member of the structure or union are not defined.
4750     //
4751     // GCC for big-endian PPC32 inserts the pad before the first member,
4752     // not "beyond the last member" of the struct.  To stay compatible
4753     // with GCC, we coerce the struct to an integer of the same size.
4754     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4755     if (Size == 0)
4756       return ABIArgInfo::getIgnore();
4757     else {
4758       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4759       return ABIArgInfo::getDirect(CoerceTy);
4760     }
4761   }
4762 
4763   return DefaultABIInfo::classifyReturnType(RetTy);
4764 }
4765 
4766 // TODO: this implementation is now likely redundant with
4767 // DefaultABIInfo::EmitVAArg.
4768 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4769                                       QualType Ty) const {
4770   if (getTarget().getTriple().isOSDarwin()) {
4771     auto TI = getContext().getTypeInfoInChars(Ty);
4772     TI.Align = getParamTypeAlignment(Ty);
4773 
4774     CharUnits SlotSize = CharUnits::fromQuantity(4);
4775     return emitVoidPtrVAArg(CGF, VAList, Ty,
4776                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4777                             /*AllowHigherAlign=*/true);
4778   }
4779 
4780   const unsigned OverflowLimit = 8;
4781   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4782     // TODO: Implement this. For now ignore.
4783     (void)CTy;
4784     return Address::invalid(); // FIXME?
4785   }
4786 
4787   // struct __va_list_tag {
4788   //   unsigned char gpr;
4789   //   unsigned char fpr;
4790   //   unsigned short reserved;
4791   //   void *overflow_arg_area;
4792   //   void *reg_save_area;
4793   // };
4794 
4795   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4796   bool isInt = !Ty->isFloatingType();
4797   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4798 
4799   // All aggregates are passed indirectly?  That doesn't seem consistent
4800   // with the argument-lowering code.
4801   bool isIndirect = isAggregateTypeForABI(Ty);
4802 
4803   CGBuilderTy &Builder = CGF.Builder;
4804 
4805   // The calling convention either uses 1-2 GPRs or 1 FPR.
4806   Address NumRegsAddr = Address::invalid();
4807   if (isInt || IsSoftFloatABI) {
4808     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4809   } else {
4810     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4811   }
4812 
4813   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4814 
4815   // "Align" the register count when TY is i64.
4816   if (isI64 || (isF64 && IsSoftFloatABI)) {
4817     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4818     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4819   }
4820 
4821   llvm::Value *CC =
4822       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4823 
4824   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4825   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4826   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4827 
4828   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4829 
4830   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4831   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4832 
4833   // Case 1: consume registers.
4834   Address RegAddr = Address::invalid();
4835   {
4836     CGF.EmitBlock(UsingRegs);
4837 
4838     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4839     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4840                       CharUnits::fromQuantity(8));
4841     assert(RegAddr.getElementType() == CGF.Int8Ty);
4842 
4843     // Floating-point registers start after the general-purpose registers.
4844     if (!(isInt || IsSoftFloatABI)) {
4845       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4846                                                    CharUnits::fromQuantity(32));
4847     }
4848 
4849     // Get the address of the saved value by scaling the number of
4850     // registers we've used by the number of
4851     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4852     llvm::Value *RegOffset =
4853       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4854     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4855                                             RegAddr.getPointer(), RegOffset),
4856                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4857     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4858 
4859     // Increase the used-register count.
4860     NumRegs =
4861       Builder.CreateAdd(NumRegs,
4862                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4863     Builder.CreateStore(NumRegs, NumRegsAddr);
4864 
4865     CGF.EmitBranch(Cont);
4866   }
4867 
4868   // Case 2: consume space in the overflow area.
4869   Address MemAddr = Address::invalid();
4870   {
4871     CGF.EmitBlock(UsingOverflow);
4872 
4873     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4874 
4875     // Everything in the overflow area is rounded up to a size of at least 4.
4876     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4877 
4878     CharUnits Size;
4879     if (!isIndirect) {
4880       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4881       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4882     } else {
4883       Size = CGF.getPointerSize();
4884     }
4885 
4886     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4887     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4888                          OverflowAreaAlign);
4889     // Round up address of argument to alignment
4890     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4891     if (Align > OverflowAreaAlign) {
4892       llvm::Value *Ptr = OverflowArea.getPointer();
4893       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4894                                                            Align);
4895     }
4896 
4897     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4898 
4899     // Increase the overflow area.
4900     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4901     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4902     CGF.EmitBranch(Cont);
4903   }
4904 
4905   CGF.EmitBlock(Cont);
4906 
4907   // Merge the cases with a phi.
4908   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4909                                 "vaarg.addr");
4910 
4911   // Load the pointer if the argument was passed indirectly.
4912   if (isIndirect) {
4913     Result = Address(Builder.CreateLoad(Result, "aggr"),
4914                      getContext().getTypeAlignInChars(Ty));
4915   }
4916 
4917   return Result;
4918 }
4919 
4920 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4921     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4922   assert(Triple.isPPC32());
4923 
4924   switch (Opts.getStructReturnConvention()) {
4925   case CodeGenOptions::SRCK_Default:
4926     break;
4927   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4928     return false;
4929   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4930     return true;
4931   }
4932 
4933   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4934     return true;
4935 
4936   return false;
4937 }
4938 
4939 bool
4940 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4941                                                 llvm::Value *Address) const {
4942   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4943                                      /*IsAIX*/ false);
4944 }
4945 
4946 // PowerPC-64
4947 
4948 namespace {
4949 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4950 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4951 public:
4952   enum ABIKind {
4953     ELFv1 = 0,
4954     ELFv2
4955   };
4956 
4957 private:
4958   static const unsigned GPRBits = 64;
4959   ABIKind Kind;
4960   bool IsSoftFloatABI;
4961 
4962 public:
4963   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4964                      bool SoftFloatABI)
4965       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4966 
4967   bool isPromotableTypeForABI(QualType Ty) const;
4968   CharUnits getParamTypeAlignment(QualType Ty) const;
4969 
4970   ABIArgInfo classifyReturnType(QualType RetTy) const;
4971   ABIArgInfo classifyArgumentType(QualType Ty) const;
4972 
4973   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4974   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4975                                          uint64_t Members) const override;
4976 
4977   // TODO: We can add more logic to computeInfo to improve performance.
4978   // Example: For aggregate arguments that fit in a register, we could
4979   // use getDirectInReg (as is done below for structs containing a single
4980   // floating-point value) to avoid pushing them to memory on function
4981   // entry.  This would require changing the logic in PPCISelLowering
4982   // when lowering the parameters in the caller and args in the callee.
4983   void computeInfo(CGFunctionInfo &FI) const override {
4984     if (!getCXXABI().classifyReturnType(FI))
4985       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4986     for (auto &I : FI.arguments()) {
4987       // We rely on the default argument classification for the most part.
4988       // One exception:  An aggregate containing a single floating-point
4989       // or vector item must be passed in a register if one is available.
4990       const Type *T = isSingleElementStruct(I.type, getContext());
4991       if (T) {
4992         const BuiltinType *BT = T->getAs<BuiltinType>();
4993         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4994             (BT && BT->isFloatingPoint())) {
4995           QualType QT(T, 0);
4996           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4997           continue;
4998         }
4999       }
5000       I.info = classifyArgumentType(I.type);
5001     }
5002   }
5003 
5004   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5005                     QualType Ty) const override;
5006 
5007   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5008                                     bool asReturnValue) const override {
5009     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5010   }
5011 
5012   bool isSwiftErrorInRegister() const override {
5013     return false;
5014   }
5015 };
5016 
5017 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5018 
5019 public:
5020   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5021                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5022                                bool SoftFloatABI)
5023       : TargetCodeGenInfo(
5024             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5025 
5026   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5027     // This is recovered from gcc output.
5028     return 1; // r1 is the dedicated stack pointer
5029   }
5030 
5031   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5032                                llvm::Value *Address) const override;
5033 };
5034 
5035 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5036 public:
5037   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5038 
5039   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5040     // This is recovered from gcc output.
5041     return 1; // r1 is the dedicated stack pointer
5042   }
5043 
5044   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5045                                llvm::Value *Address) const override;
5046 };
5047 
5048 }
5049 
5050 // Return true if the ABI requires Ty to be passed sign- or zero-
5051 // extended to 64 bits.
5052 bool
5053 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5054   // Treat an enum type as its underlying type.
5055   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5056     Ty = EnumTy->getDecl()->getIntegerType();
5057 
5058   // Promotable integer types are required to be promoted by the ABI.
5059   if (isPromotableIntegerTypeForABI(Ty))
5060     return true;
5061 
5062   // In addition to the usual promotable integer types, we also need to
5063   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5064   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5065     switch (BT->getKind()) {
5066     case BuiltinType::Int:
5067     case BuiltinType::UInt:
5068       return true;
5069     default:
5070       break;
5071     }
5072 
5073   if (const auto *EIT = Ty->getAs<BitIntType>())
5074     if (EIT->getNumBits() < 64)
5075       return true;
5076 
5077   return false;
5078 }
5079 
5080 /// isAlignedParamType - Determine whether a type requires 16-byte or
5081 /// higher alignment in the parameter area.  Always returns at least 8.
5082 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5083   // Complex types are passed just like their elements.
5084   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5085     Ty = CTy->getElementType();
5086 
5087   auto FloatUsesVector = [this](QualType Ty){
5088     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5089                                            Ty) == &llvm::APFloat::IEEEquad();
5090   };
5091 
5092   // Only vector types of size 16 bytes need alignment (larger types are
5093   // passed via reference, smaller types are not aligned).
5094   if (Ty->isVectorType()) {
5095     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5096   } else if (FloatUsesVector(Ty)) {
5097     // According to ABI document section 'Optional Save Areas': If extended
5098     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5099     // format are supported, map them to a single quadword, quadword aligned.
5100     return CharUnits::fromQuantity(16);
5101   }
5102 
5103   // For single-element float/vector structs, we consider the whole type
5104   // to have the same alignment requirements as its single element.
5105   const Type *AlignAsType = nullptr;
5106   const Type *EltType = isSingleElementStruct(Ty, getContext());
5107   if (EltType) {
5108     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5109     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5110         (BT && BT->isFloatingPoint()))
5111       AlignAsType = EltType;
5112   }
5113 
5114   // Likewise for ELFv2 homogeneous aggregates.
5115   const Type *Base = nullptr;
5116   uint64_t Members = 0;
5117   if (!AlignAsType && Kind == ELFv2 &&
5118       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5119     AlignAsType = Base;
5120 
5121   // With special case aggregates, only vector base types need alignment.
5122   if (AlignAsType) {
5123     bool UsesVector = AlignAsType->isVectorType() ||
5124                       FloatUsesVector(QualType(AlignAsType, 0));
5125     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5126   }
5127 
5128   // Otherwise, we only need alignment for any aggregate type that
5129   // has an alignment requirement of >= 16 bytes.
5130   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5131     return CharUnits::fromQuantity(16);
5132   }
5133 
5134   return CharUnits::fromQuantity(8);
5135 }
5136 
5137 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5138 /// aggregate.  Base is set to the base element type, and Members is set
5139 /// to the number of base elements.
5140 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5141                                      uint64_t &Members) const {
5142   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5143     uint64_t NElements = AT->getSize().getZExtValue();
5144     if (NElements == 0)
5145       return false;
5146     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5147       return false;
5148     Members *= NElements;
5149   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5150     const RecordDecl *RD = RT->getDecl();
5151     if (RD->hasFlexibleArrayMember())
5152       return false;
5153 
5154     Members = 0;
5155 
5156     // If this is a C++ record, check the properties of the record such as
5157     // bases and ABI specific restrictions
5158     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5159       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5160         return false;
5161 
5162       for (const auto &I : CXXRD->bases()) {
5163         // Ignore empty records.
5164         if (isEmptyRecord(getContext(), I.getType(), true))
5165           continue;
5166 
5167         uint64_t FldMembers;
5168         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5169           return false;
5170 
5171         Members += FldMembers;
5172       }
5173     }
5174 
5175     for (const auto *FD : RD->fields()) {
5176       // Ignore (non-zero arrays of) empty records.
5177       QualType FT = FD->getType();
5178       while (const ConstantArrayType *AT =
5179              getContext().getAsConstantArrayType(FT)) {
5180         if (AT->getSize().getZExtValue() == 0)
5181           return false;
5182         FT = AT->getElementType();
5183       }
5184       if (isEmptyRecord(getContext(), FT, true))
5185         continue;
5186 
5187       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5188       if (getContext().getLangOpts().CPlusPlus &&
5189           FD->isZeroLengthBitField(getContext()))
5190         continue;
5191 
5192       uint64_t FldMembers;
5193       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5194         return false;
5195 
5196       Members = (RD->isUnion() ?
5197                  std::max(Members, FldMembers) : Members + FldMembers);
5198     }
5199 
5200     if (!Base)
5201       return false;
5202 
5203     // Ensure there is no padding.
5204     if (getContext().getTypeSize(Base) * Members !=
5205         getContext().getTypeSize(Ty))
5206       return false;
5207   } else {
5208     Members = 1;
5209     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5210       Members = 2;
5211       Ty = CT->getElementType();
5212     }
5213 
5214     // Most ABIs only support float, double, and some vector type widths.
5215     if (!isHomogeneousAggregateBaseType(Ty))
5216       return false;
5217 
5218     // The base type must be the same for all members.  Types that
5219     // agree in both total size and mode (float vs. vector) are
5220     // treated as being equivalent here.
5221     const Type *TyPtr = Ty.getTypePtr();
5222     if (!Base) {
5223       Base = TyPtr;
5224       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5225       // so make sure to widen it explicitly.
5226       if (const VectorType *VT = Base->getAs<VectorType>()) {
5227         QualType EltTy = VT->getElementType();
5228         unsigned NumElements =
5229             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5230         Base = getContext()
5231                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5232                    .getTypePtr();
5233       }
5234     }
5235 
5236     if (Base->isVectorType() != TyPtr->isVectorType() ||
5237         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5238       return false;
5239   }
5240   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5241 }
5242 
5243 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5244   // Homogeneous aggregates for ELFv2 must have base types of float,
5245   // double, long double, or 128-bit vectors.
5246   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5247     if (BT->getKind() == BuiltinType::Float ||
5248         BT->getKind() == BuiltinType::Double ||
5249         BT->getKind() == BuiltinType::LongDouble ||
5250         BT->getKind() == BuiltinType::Ibm128 ||
5251         (getContext().getTargetInfo().hasFloat128Type() &&
5252          (BT->getKind() == BuiltinType::Float128))) {
5253       if (IsSoftFloatABI)
5254         return false;
5255       return true;
5256     }
5257   }
5258   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5259     if (getContext().getTypeSize(VT) == 128)
5260       return true;
5261   }
5262   return false;
5263 }
5264 
5265 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5266     const Type *Base, uint64_t Members) const {
5267   // Vector and fp128 types require one register, other floating point types
5268   // require one or two registers depending on their size.
5269   uint32_t NumRegs =
5270       ((getContext().getTargetInfo().hasFloat128Type() &&
5271           Base->isFloat128Type()) ||
5272         Base->isVectorType()) ? 1
5273                               : (getContext().getTypeSize(Base) + 63) / 64;
5274 
5275   // Homogeneous Aggregates may occupy at most 8 registers.
5276   return Members * NumRegs <= 8;
5277 }
5278 
5279 ABIArgInfo
5280 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5281   Ty = useFirstFieldIfTransparentUnion(Ty);
5282 
5283   if (Ty->isAnyComplexType())
5284     return ABIArgInfo::getDirect();
5285 
5286   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5287   // or via reference (larger than 16 bytes).
5288   if (Ty->isVectorType()) {
5289     uint64_t Size = getContext().getTypeSize(Ty);
5290     if (Size > 128)
5291       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5292     else if (Size < 128) {
5293       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5294       return ABIArgInfo::getDirect(CoerceTy);
5295     }
5296   }
5297 
5298   if (const auto *EIT = Ty->getAs<BitIntType>())
5299     if (EIT->getNumBits() > 128)
5300       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5301 
5302   if (isAggregateTypeForABI(Ty)) {
5303     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5304       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5305 
5306     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5307     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5308 
5309     // ELFv2 homogeneous aggregates are passed as array types.
5310     const Type *Base = nullptr;
5311     uint64_t Members = 0;
5312     if (Kind == ELFv2 &&
5313         isHomogeneousAggregate(Ty, Base, Members)) {
5314       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5315       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5316       return ABIArgInfo::getDirect(CoerceTy);
5317     }
5318 
5319     // If an aggregate may end up fully in registers, we do not
5320     // use the ByVal method, but pass the aggregate as array.
5321     // This is usually beneficial since we avoid forcing the
5322     // back-end to store the argument to memory.
5323     uint64_t Bits = getContext().getTypeSize(Ty);
5324     if (Bits > 0 && Bits <= 8 * GPRBits) {
5325       llvm::Type *CoerceTy;
5326 
5327       // Types up to 8 bytes are passed as integer type (which will be
5328       // properly aligned in the argument save area doubleword).
5329       if (Bits <= GPRBits)
5330         CoerceTy =
5331             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5332       // Larger types are passed as arrays, with the base type selected
5333       // according to the required alignment in the save area.
5334       else {
5335         uint64_t RegBits = ABIAlign * 8;
5336         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5337         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5338         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5339       }
5340 
5341       return ABIArgInfo::getDirect(CoerceTy);
5342     }
5343 
5344     // All other aggregates are passed ByVal.
5345     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5346                                    /*ByVal=*/true,
5347                                    /*Realign=*/TyAlign > ABIAlign);
5348   }
5349 
5350   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5351                                      : ABIArgInfo::getDirect());
5352 }
5353 
5354 ABIArgInfo
5355 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5356   if (RetTy->isVoidType())
5357     return ABIArgInfo::getIgnore();
5358 
5359   if (RetTy->isAnyComplexType())
5360     return ABIArgInfo::getDirect();
5361 
5362   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5363   // or via reference (larger than 16 bytes).
5364   if (RetTy->isVectorType()) {
5365     uint64_t Size = getContext().getTypeSize(RetTy);
5366     if (Size > 128)
5367       return getNaturalAlignIndirect(RetTy);
5368     else if (Size < 128) {
5369       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5370       return ABIArgInfo::getDirect(CoerceTy);
5371     }
5372   }
5373 
5374   if (const auto *EIT = RetTy->getAs<BitIntType>())
5375     if (EIT->getNumBits() > 128)
5376       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5377 
5378   if (isAggregateTypeForABI(RetTy)) {
5379     // ELFv2 homogeneous aggregates are returned as array types.
5380     const Type *Base = nullptr;
5381     uint64_t Members = 0;
5382     if (Kind == ELFv2 &&
5383         isHomogeneousAggregate(RetTy, Base, Members)) {
5384       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5385       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5386       return ABIArgInfo::getDirect(CoerceTy);
5387     }
5388 
5389     // ELFv2 small aggregates are returned in up to two registers.
5390     uint64_t Bits = getContext().getTypeSize(RetTy);
5391     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5392       if (Bits == 0)
5393         return ABIArgInfo::getIgnore();
5394 
5395       llvm::Type *CoerceTy;
5396       if (Bits > GPRBits) {
5397         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5398         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5399       } else
5400         CoerceTy =
5401             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5402       return ABIArgInfo::getDirect(CoerceTy);
5403     }
5404 
5405     // All other aggregates are returned indirectly.
5406     return getNaturalAlignIndirect(RetTy);
5407   }
5408 
5409   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5410                                         : ABIArgInfo::getDirect());
5411 }
5412 
5413 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5414 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5415                                       QualType Ty) const {
5416   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5417   TypeInfo.Align = getParamTypeAlignment(Ty);
5418 
5419   CharUnits SlotSize = CharUnits::fromQuantity(8);
5420 
5421   // If we have a complex type and the base type is smaller than 8 bytes,
5422   // the ABI calls for the real and imaginary parts to be right-adjusted
5423   // in separate doublewords.  However, Clang expects us to produce a
5424   // pointer to a structure with the two parts packed tightly.  So generate
5425   // loads of the real and imaginary parts relative to the va_list pointer,
5426   // and store them to a temporary structure.
5427   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5428     CharUnits EltSize = TypeInfo.Width / 2;
5429     if (EltSize < SlotSize)
5430       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5431   }
5432 
5433   // Otherwise, just use the general rule.
5434   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5435                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5436 }
5437 
5438 bool
5439 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5440   CodeGen::CodeGenFunction &CGF,
5441   llvm::Value *Address) const {
5442   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5443                                      /*IsAIX*/ false);
5444 }
5445 
5446 bool
5447 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5448                                                 llvm::Value *Address) const {
5449   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5450                                      /*IsAIX*/ false);
5451 }
5452 
5453 //===----------------------------------------------------------------------===//
5454 // AArch64 ABI Implementation
5455 //===----------------------------------------------------------------------===//
5456 
5457 namespace {
5458 
5459 class AArch64ABIInfo : public SwiftABIInfo {
5460 public:
5461   enum ABIKind {
5462     AAPCS = 0,
5463     DarwinPCS,
5464     Win64
5465   };
5466 
5467 private:
5468   ABIKind Kind;
5469 
5470 public:
5471   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5472     : SwiftABIInfo(CGT), Kind(Kind) {}
5473 
5474 private:
5475   ABIKind getABIKind() const { return Kind; }
5476   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5477 
5478   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5479   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5480                                   unsigned CallingConvention) const;
5481   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5482   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5483   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5484                                          uint64_t Members) const override;
5485 
5486   bool isIllegalVectorType(QualType Ty) const;
5487 
5488   void computeInfo(CGFunctionInfo &FI) const override {
5489     if (!::classifyReturnType(getCXXABI(), FI, *this))
5490       FI.getReturnInfo() =
5491           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5492 
5493     for (auto &it : FI.arguments())
5494       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5495                                      FI.getCallingConvention());
5496   }
5497 
5498   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5499                           CodeGenFunction &CGF) const;
5500 
5501   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5502                          CodeGenFunction &CGF) const;
5503 
5504   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5505                     QualType Ty) const override {
5506     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5507     if (isa<llvm::ScalableVectorType>(BaseTy))
5508       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5509                                "currently not supported");
5510 
5511     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5512                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5513                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5514   }
5515 
5516   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5517                       QualType Ty) const override;
5518 
5519   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5520                                     bool asReturnValue) const override {
5521     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5522   }
5523   bool isSwiftErrorInRegister() const override {
5524     return true;
5525   }
5526 
5527   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5528                                  unsigned elts) const override;
5529 
5530   bool allowBFloatArgsAndRet() const override {
5531     return getTarget().hasBFloat16Type();
5532   }
5533 };
5534 
5535 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5536 public:
5537   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5538       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5539 
5540   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5541     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5542   }
5543 
5544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5545     return 31;
5546   }
5547 
5548   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5549 
5550   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5551                            CodeGen::CodeGenModule &CGM) const override {
5552     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5553     if (!FD)
5554       return;
5555 
5556     const auto *TA = FD->getAttr<TargetAttr>();
5557     if (TA == nullptr)
5558       return;
5559 
5560     ParsedTargetAttr Attr = TA->parse();
5561     if (Attr.BranchProtection.empty())
5562       return;
5563 
5564     TargetInfo::BranchProtectionInfo BPI;
5565     StringRef Error;
5566     (void)CGM.getTarget().validateBranchProtection(
5567         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5568     assert(Error.empty());
5569 
5570     auto *Fn = cast<llvm::Function>(GV);
5571     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5572     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5573 
5574     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5575       Fn->addFnAttr("sign-return-address-key",
5576                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5577                         ? "a_key"
5578                         : "b_key");
5579     }
5580 
5581     Fn->addFnAttr("branch-target-enforcement",
5582                   BPI.BranchTargetEnforcement ? "true" : "false");
5583   }
5584 
5585   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5586                                 llvm::Type *Ty) const override {
5587     if (CGF.getTarget().hasFeature("ls64")) {
5588       auto *ST = dyn_cast<llvm::StructType>(Ty);
5589       if (ST && ST->getNumElements() == 1) {
5590         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5591         if (AT && AT->getNumElements() == 8 &&
5592             AT->getElementType()->isIntegerTy(64))
5593           return true;
5594       }
5595     }
5596     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5597   }
5598 };
5599 
5600 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5601 public:
5602   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5603       : AArch64TargetCodeGenInfo(CGT, K) {}
5604 
5605   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5606                            CodeGen::CodeGenModule &CGM) const override;
5607 
5608   void getDependentLibraryOption(llvm::StringRef Lib,
5609                                  llvm::SmallString<24> &Opt) const override {
5610     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5611   }
5612 
5613   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5614                                llvm::SmallString<32> &Opt) const override {
5615     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5616   }
5617 };
5618 
5619 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5620     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5621   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5622   if (GV->isDeclaration())
5623     return;
5624   addStackProbeTargetAttributes(D, GV, CGM);
5625 }
5626 }
5627 
5628 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5629   assert(Ty->isVectorType() && "expected vector type!");
5630 
5631   const auto *VT = Ty->castAs<VectorType>();
5632   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5633     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5634     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5635                BuiltinType::UChar &&
5636            "unexpected builtin type for SVE predicate!");
5637     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5638         llvm::Type::getInt1Ty(getVMContext()), 16));
5639   }
5640 
5641   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5642     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5643 
5644     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5645     llvm::ScalableVectorType *ResType = nullptr;
5646     switch (BT->getKind()) {
5647     default:
5648       llvm_unreachable("unexpected builtin type for SVE vector!");
5649     case BuiltinType::SChar:
5650     case BuiltinType::UChar:
5651       ResType = llvm::ScalableVectorType::get(
5652           llvm::Type::getInt8Ty(getVMContext()), 16);
5653       break;
5654     case BuiltinType::Short:
5655     case BuiltinType::UShort:
5656       ResType = llvm::ScalableVectorType::get(
5657           llvm::Type::getInt16Ty(getVMContext()), 8);
5658       break;
5659     case BuiltinType::Int:
5660     case BuiltinType::UInt:
5661       ResType = llvm::ScalableVectorType::get(
5662           llvm::Type::getInt32Ty(getVMContext()), 4);
5663       break;
5664     case BuiltinType::Long:
5665     case BuiltinType::ULong:
5666       ResType = llvm::ScalableVectorType::get(
5667           llvm::Type::getInt64Ty(getVMContext()), 2);
5668       break;
5669     case BuiltinType::Half:
5670       ResType = llvm::ScalableVectorType::get(
5671           llvm::Type::getHalfTy(getVMContext()), 8);
5672       break;
5673     case BuiltinType::Float:
5674       ResType = llvm::ScalableVectorType::get(
5675           llvm::Type::getFloatTy(getVMContext()), 4);
5676       break;
5677     case BuiltinType::Double:
5678       ResType = llvm::ScalableVectorType::get(
5679           llvm::Type::getDoubleTy(getVMContext()), 2);
5680       break;
5681     case BuiltinType::BFloat16:
5682       ResType = llvm::ScalableVectorType::get(
5683           llvm::Type::getBFloatTy(getVMContext()), 8);
5684       break;
5685     }
5686     return ABIArgInfo::getDirect(ResType);
5687   }
5688 
5689   uint64_t Size = getContext().getTypeSize(Ty);
5690   // Android promotes <2 x i8> to i16, not i32
5691   if (isAndroid() && (Size <= 16)) {
5692     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5693     return ABIArgInfo::getDirect(ResType);
5694   }
5695   if (Size <= 32) {
5696     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5697     return ABIArgInfo::getDirect(ResType);
5698   }
5699   if (Size == 64) {
5700     auto *ResType =
5701         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5702     return ABIArgInfo::getDirect(ResType);
5703   }
5704   if (Size == 128) {
5705     auto *ResType =
5706         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5707     return ABIArgInfo::getDirect(ResType);
5708   }
5709   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5710 }
5711 
5712 ABIArgInfo
5713 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5714                                      unsigned CallingConvention) const {
5715   Ty = useFirstFieldIfTransparentUnion(Ty);
5716 
5717   // Handle illegal vector types here.
5718   if (isIllegalVectorType(Ty))
5719     return coerceIllegalVector(Ty);
5720 
5721   if (!isAggregateTypeForABI(Ty)) {
5722     // Treat an enum type as its underlying type.
5723     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5724       Ty = EnumTy->getDecl()->getIntegerType();
5725 
5726     if (const auto *EIT = Ty->getAs<BitIntType>())
5727       if (EIT->getNumBits() > 128)
5728         return getNaturalAlignIndirect(Ty);
5729 
5730     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5731                 ? ABIArgInfo::getExtend(Ty)
5732                 : ABIArgInfo::getDirect());
5733   }
5734 
5735   // Structures with either a non-trivial destructor or a non-trivial
5736   // copy constructor are always indirect.
5737   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5738     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5739                                      CGCXXABI::RAA_DirectInMemory);
5740   }
5741 
5742   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5743   // elsewhere for GNU compatibility.
5744   uint64_t Size = getContext().getTypeSize(Ty);
5745   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5746   if (IsEmpty || Size == 0) {
5747     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5748       return ABIArgInfo::getIgnore();
5749 
5750     // GNU C mode. The only argument that gets ignored is an empty one with size
5751     // 0.
5752     if (IsEmpty && Size == 0)
5753       return ABIArgInfo::getIgnore();
5754     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5755   }
5756 
5757   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5758   const Type *Base = nullptr;
5759   uint64_t Members = 0;
5760   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5761   bool IsWinVariadic = IsWin64 && IsVariadic;
5762   // In variadic functions on Windows, all composite types are treated alike,
5763   // no special handling of HFAs/HVAs.
5764   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5765     if (Kind != AArch64ABIInfo::AAPCS)
5766       return ABIArgInfo::getDirect(
5767           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5768 
5769     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5770     // default otherwise.
5771     unsigned Align =
5772         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5773     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5774     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5775     return ABIArgInfo::getDirect(
5776         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5777         nullptr, true, Align);
5778   }
5779 
5780   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5781   if (Size <= 128) {
5782     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5783     // same size and alignment.
5784     if (getTarget().isRenderScriptTarget()) {
5785       return coerceToIntArray(Ty, getContext(), getVMContext());
5786     }
5787     unsigned Alignment;
5788     if (Kind == AArch64ABIInfo::AAPCS) {
5789       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5790       Alignment = Alignment < 128 ? 64 : 128;
5791     } else {
5792       Alignment = std::max(getContext().getTypeAlign(Ty),
5793                            (unsigned)getTarget().getPointerWidth(0));
5794     }
5795     Size = llvm::alignTo(Size, Alignment);
5796 
5797     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5798     // For aggregates with 16-byte alignment, we use i128.
5799     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5800     return ABIArgInfo::getDirect(
5801         Size == Alignment ? BaseTy
5802                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5803   }
5804 
5805   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5806 }
5807 
5808 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5809                                               bool IsVariadic) const {
5810   if (RetTy->isVoidType())
5811     return ABIArgInfo::getIgnore();
5812 
5813   if (const auto *VT = RetTy->getAs<VectorType>()) {
5814     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5815         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5816       return coerceIllegalVector(RetTy);
5817   }
5818 
5819   // Large vector types should be returned via memory.
5820   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5821     return getNaturalAlignIndirect(RetTy);
5822 
5823   if (!isAggregateTypeForABI(RetTy)) {
5824     // Treat an enum type as its underlying type.
5825     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5826       RetTy = EnumTy->getDecl()->getIntegerType();
5827 
5828     if (const auto *EIT = RetTy->getAs<BitIntType>())
5829       if (EIT->getNumBits() > 128)
5830         return getNaturalAlignIndirect(RetTy);
5831 
5832     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5833                 ? ABIArgInfo::getExtend(RetTy)
5834                 : ABIArgInfo::getDirect());
5835   }
5836 
5837   uint64_t Size = getContext().getTypeSize(RetTy);
5838   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5839     return ABIArgInfo::getIgnore();
5840 
5841   const Type *Base = nullptr;
5842   uint64_t Members = 0;
5843   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5844       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5845         IsVariadic))
5846     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5847     return ABIArgInfo::getDirect();
5848 
5849   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5850   if (Size <= 128) {
5851     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5852     // same size and alignment.
5853     if (getTarget().isRenderScriptTarget()) {
5854       return coerceToIntArray(RetTy, getContext(), getVMContext());
5855     }
5856 
5857     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5858       // Composite types are returned in lower bits of a 64-bit register for LE,
5859       // and in higher bits for BE. However, integer types are always returned
5860       // in lower bits for both LE and BE, and they are not rounded up to
5861       // 64-bits. We can skip rounding up of composite types for LE, but not for
5862       // BE, otherwise composite types will be indistinguishable from integer
5863       // types.
5864       return ABIArgInfo::getDirect(
5865           llvm::IntegerType::get(getVMContext(), Size));
5866     }
5867 
5868     unsigned Alignment = getContext().getTypeAlign(RetTy);
5869     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5870 
5871     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5872     // For aggregates with 16-byte alignment, we use i128.
5873     if (Alignment < 128 && Size == 128) {
5874       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5875       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5876     }
5877     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5878   }
5879 
5880   return getNaturalAlignIndirect(RetTy);
5881 }
5882 
5883 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5884 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5885   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5886     // Check whether VT is a fixed-length SVE vector. These types are
5887     // represented as scalable vectors in function args/return and must be
5888     // coerced from fixed vectors.
5889     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5890         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5891       return true;
5892 
5893     // Check whether VT is legal.
5894     unsigned NumElements = VT->getNumElements();
5895     uint64_t Size = getContext().getTypeSize(VT);
5896     // NumElements should be power of 2.
5897     if (!llvm::isPowerOf2_32(NumElements))
5898       return true;
5899 
5900     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5901     // vectors for some reason.
5902     llvm::Triple Triple = getTarget().getTriple();
5903     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5904         Triple.isOSBinFormatMachO())
5905       return Size <= 32;
5906 
5907     return Size != 64 && (Size != 128 || NumElements == 1);
5908   }
5909   return false;
5910 }
5911 
5912 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5913                                                llvm::Type *eltTy,
5914                                                unsigned elts) const {
5915   if (!llvm::isPowerOf2_32(elts))
5916     return false;
5917   if (totalSize.getQuantity() != 8 &&
5918       (totalSize.getQuantity() != 16 || elts == 1))
5919     return false;
5920   return true;
5921 }
5922 
5923 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5924   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5925   // point type or a short-vector type. This is the same as the 32-bit ABI,
5926   // but with the difference that any floating-point type is allowed,
5927   // including __fp16.
5928   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5929     if (BT->isFloatingPoint())
5930       return true;
5931   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5932     unsigned VecSize = getContext().getTypeSize(VT);
5933     if (VecSize == 64 || VecSize == 128)
5934       return true;
5935   }
5936   return false;
5937 }
5938 
5939 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5940                                                        uint64_t Members) const {
5941   return Members <= 4;
5942 }
5943 
5944 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5945                                        CodeGenFunction &CGF) const {
5946   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5947                                        CGF.CurFnInfo->getCallingConvention());
5948   bool IsIndirect = AI.isIndirect();
5949 
5950   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5951   if (IsIndirect)
5952     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5953   else if (AI.getCoerceToType())
5954     BaseTy = AI.getCoerceToType();
5955 
5956   unsigned NumRegs = 1;
5957   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5958     BaseTy = ArrTy->getElementType();
5959     NumRegs = ArrTy->getNumElements();
5960   }
5961   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5962 
5963   // The AArch64 va_list type and handling is specified in the Procedure Call
5964   // Standard, section B.4:
5965   //
5966   // struct {
5967   //   void *__stack;
5968   //   void *__gr_top;
5969   //   void *__vr_top;
5970   //   int __gr_offs;
5971   //   int __vr_offs;
5972   // };
5973 
5974   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5975   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5976   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5977   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5978 
5979   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5980   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5981 
5982   Address reg_offs_p = Address::invalid();
5983   llvm::Value *reg_offs = nullptr;
5984   int reg_top_index;
5985   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5986   if (!IsFPR) {
5987     // 3 is the field number of __gr_offs
5988     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5989     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5990     reg_top_index = 1; // field number for __gr_top
5991     RegSize = llvm::alignTo(RegSize, 8);
5992   } else {
5993     // 4 is the field number of __vr_offs.
5994     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5995     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5996     reg_top_index = 2; // field number for __vr_top
5997     RegSize = 16 * NumRegs;
5998   }
5999 
6000   //=======================================
6001   // Find out where argument was passed
6002   //=======================================
6003 
6004   // If reg_offs >= 0 we're already using the stack for this type of
6005   // argument. We don't want to keep updating reg_offs (in case it overflows,
6006   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6007   // whatever they get).
6008   llvm::Value *UsingStack = nullptr;
6009   UsingStack = CGF.Builder.CreateICmpSGE(
6010       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6011 
6012   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6013 
6014   // Otherwise, at least some kind of argument could go in these registers, the
6015   // question is whether this particular type is too big.
6016   CGF.EmitBlock(MaybeRegBlock);
6017 
6018   // Integer arguments may need to correct register alignment (for example a
6019   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6020   // align __gr_offs to calculate the potential address.
6021   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6022     int Align = TyAlign.getQuantity();
6023 
6024     reg_offs = CGF.Builder.CreateAdd(
6025         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6026         "align_regoffs");
6027     reg_offs = CGF.Builder.CreateAnd(
6028         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6029         "aligned_regoffs");
6030   }
6031 
6032   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6033   // The fact that this is done unconditionally reflects the fact that
6034   // allocating an argument to the stack also uses up all the remaining
6035   // registers of the appropriate kind.
6036   llvm::Value *NewOffset = nullptr;
6037   NewOffset = CGF.Builder.CreateAdd(
6038       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6039   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6040 
6041   // Now we're in a position to decide whether this argument really was in
6042   // registers or not.
6043   llvm::Value *InRegs = nullptr;
6044   InRegs = CGF.Builder.CreateICmpSLE(
6045       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6046 
6047   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6048 
6049   //=======================================
6050   // Argument was in registers
6051   //=======================================
6052 
6053   // Now we emit the code for if the argument was originally passed in
6054   // registers. First start the appropriate block:
6055   CGF.EmitBlock(InRegBlock);
6056 
6057   llvm::Value *reg_top = nullptr;
6058   Address reg_top_p =
6059       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6060   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6061   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6062                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
6063   Address RegAddr = Address::invalid();
6064   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
6065 
6066   if (IsIndirect) {
6067     // If it's been passed indirectly (actually a struct), whatever we find from
6068     // stored registers or on the stack will actually be a struct **.
6069     MemTy = llvm::PointerType::getUnqual(MemTy);
6070   }
6071 
6072   const Type *Base = nullptr;
6073   uint64_t NumMembers = 0;
6074   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6075   if (IsHFA && NumMembers > 1) {
6076     // Homogeneous aggregates passed in registers will have their elements split
6077     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6078     // qN+1, ...). We reload and store into a temporary local variable
6079     // contiguously.
6080     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6081     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6082     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6083     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6084     Address Tmp = CGF.CreateTempAlloca(HFATy,
6085                                        std::max(TyAlign, BaseTyInfo.Align));
6086 
6087     // On big-endian platforms, the value will be right-aligned in its slot.
6088     int Offset = 0;
6089     if (CGF.CGM.getDataLayout().isBigEndian() &&
6090         BaseTyInfo.Width.getQuantity() < 16)
6091       Offset = 16 - BaseTyInfo.Width.getQuantity();
6092 
6093     for (unsigned i = 0; i < NumMembers; ++i) {
6094       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6095       Address LoadAddr =
6096         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6097       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6098 
6099       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6100 
6101       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6102       CGF.Builder.CreateStore(Elem, StoreAddr);
6103     }
6104 
6105     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6106   } else {
6107     // Otherwise the object is contiguous in memory.
6108 
6109     // It might be right-aligned in its slot.
6110     CharUnits SlotSize = BaseAddr.getAlignment();
6111     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6112         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6113         TySize < SlotSize) {
6114       CharUnits Offset = SlotSize - TySize;
6115       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6116     }
6117 
6118     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6119   }
6120 
6121   CGF.EmitBranch(ContBlock);
6122 
6123   //=======================================
6124   // Argument was on the stack
6125   //=======================================
6126   CGF.EmitBlock(OnStackBlock);
6127 
6128   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6129   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6130 
6131   // Again, stack arguments may need realignment. In this case both integer and
6132   // floating-point ones might be affected.
6133   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6134     int Align = TyAlign.getQuantity();
6135 
6136     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6137 
6138     OnStackPtr = CGF.Builder.CreateAdd(
6139         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6140         "align_stack");
6141     OnStackPtr = CGF.Builder.CreateAnd(
6142         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6143         "align_stack");
6144 
6145     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6146   }
6147   Address OnStackAddr(OnStackPtr,
6148                       std::max(CharUnits::fromQuantity(8), TyAlign));
6149 
6150   // All stack slots are multiples of 8 bytes.
6151   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6152   CharUnits StackSize;
6153   if (IsIndirect)
6154     StackSize = StackSlotSize;
6155   else
6156     StackSize = TySize.alignTo(StackSlotSize);
6157 
6158   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6159   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6160       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6161 
6162   // Write the new value of __stack for the next call to va_arg
6163   CGF.Builder.CreateStore(NewStack, stack_p);
6164 
6165   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6166       TySize < StackSlotSize) {
6167     CharUnits Offset = StackSlotSize - TySize;
6168     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6169   }
6170 
6171   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6172 
6173   CGF.EmitBranch(ContBlock);
6174 
6175   //=======================================
6176   // Tidy up
6177   //=======================================
6178   CGF.EmitBlock(ContBlock);
6179 
6180   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6181                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6182 
6183   if (IsIndirect)
6184     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6185                    TyAlign);
6186 
6187   return ResAddr;
6188 }
6189 
6190 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6191                                         CodeGenFunction &CGF) const {
6192   // The backend's lowering doesn't support va_arg for aggregates or
6193   // illegal vector types.  Lower VAArg here for these cases and use
6194   // the LLVM va_arg instruction for everything else.
6195   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6196     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6197 
6198   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6199   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6200 
6201   // Empty records are ignored for parameter passing purposes.
6202   if (isEmptyRecord(getContext(), Ty, true)) {
6203     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6204     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6205     return Addr;
6206   }
6207 
6208   // The size of the actual thing passed, which might end up just
6209   // being a pointer for indirect types.
6210   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6211 
6212   // Arguments bigger than 16 bytes which aren't homogeneous
6213   // aggregates should be passed indirectly.
6214   bool IsIndirect = false;
6215   if (TyInfo.Width.getQuantity() > 16) {
6216     const Type *Base = nullptr;
6217     uint64_t Members = 0;
6218     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6219   }
6220 
6221   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6222                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6223 }
6224 
6225 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6226                                     QualType Ty) const {
6227   bool IsIndirect = false;
6228 
6229   // Composites larger than 16 bytes are passed by reference.
6230   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6231     IsIndirect = true;
6232 
6233   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6234                           CGF.getContext().getTypeInfoInChars(Ty),
6235                           CharUnits::fromQuantity(8),
6236                           /*allowHigherAlign*/ false);
6237 }
6238 
6239 //===----------------------------------------------------------------------===//
6240 // ARM ABI Implementation
6241 //===----------------------------------------------------------------------===//
6242 
6243 namespace {
6244 
6245 class ARMABIInfo : public SwiftABIInfo {
6246 public:
6247   enum ABIKind {
6248     APCS = 0,
6249     AAPCS = 1,
6250     AAPCS_VFP = 2,
6251     AAPCS16_VFP = 3,
6252   };
6253 
6254 private:
6255   ABIKind Kind;
6256   bool IsFloatABISoftFP;
6257 
6258 public:
6259   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6260       : SwiftABIInfo(CGT), Kind(_Kind) {
6261     setCCs();
6262     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6263         CGT.getCodeGenOpts().FloatABI == ""; // default
6264   }
6265 
6266   bool isEABI() const {
6267     switch (getTarget().getTriple().getEnvironment()) {
6268     case llvm::Triple::Android:
6269     case llvm::Triple::EABI:
6270     case llvm::Triple::EABIHF:
6271     case llvm::Triple::GNUEABI:
6272     case llvm::Triple::GNUEABIHF:
6273     case llvm::Triple::MuslEABI:
6274     case llvm::Triple::MuslEABIHF:
6275       return true;
6276     default:
6277       return false;
6278     }
6279   }
6280 
6281   bool isEABIHF() const {
6282     switch (getTarget().getTriple().getEnvironment()) {
6283     case llvm::Triple::EABIHF:
6284     case llvm::Triple::GNUEABIHF:
6285     case llvm::Triple::MuslEABIHF:
6286       return true;
6287     default:
6288       return false;
6289     }
6290   }
6291 
6292   ABIKind getABIKind() const { return Kind; }
6293 
6294   bool allowBFloatArgsAndRet() const override {
6295     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6296   }
6297 
6298 private:
6299   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6300                                 unsigned functionCallConv) const;
6301   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6302                                   unsigned functionCallConv) const;
6303   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6304                                           uint64_t Members) const;
6305   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6306   bool isIllegalVectorType(QualType Ty) const;
6307   bool containsAnyFP16Vectors(QualType Ty) const;
6308 
6309   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6310   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6311                                          uint64_t Members) const override;
6312 
6313   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6314 
6315   void computeInfo(CGFunctionInfo &FI) const override;
6316 
6317   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6318                     QualType Ty) const override;
6319 
6320   llvm::CallingConv::ID getLLVMDefaultCC() const;
6321   llvm::CallingConv::ID getABIDefaultCC() const;
6322   void setCCs();
6323 
6324   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6325                                     bool asReturnValue) const override {
6326     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6327   }
6328   bool isSwiftErrorInRegister() const override {
6329     return true;
6330   }
6331   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6332                                  unsigned elts) const override;
6333 };
6334 
6335 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6336 public:
6337   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6338       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6339 
6340   const ARMABIInfo &getABIInfo() const {
6341     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6342   }
6343 
6344   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6345     return 13;
6346   }
6347 
6348   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6349     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6350   }
6351 
6352   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6353                                llvm::Value *Address) const override {
6354     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6355 
6356     // 0-15 are the 16 integer registers.
6357     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6358     return false;
6359   }
6360 
6361   unsigned getSizeOfUnwindException() const override {
6362     if (getABIInfo().isEABI()) return 88;
6363     return TargetCodeGenInfo::getSizeOfUnwindException();
6364   }
6365 
6366   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6367                            CodeGen::CodeGenModule &CGM) const override {
6368     if (GV->isDeclaration())
6369       return;
6370     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6371     if (!FD)
6372       return;
6373     auto *Fn = cast<llvm::Function>(GV);
6374 
6375     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6376       ParsedTargetAttr Attr = TA->parse();
6377       if (!Attr.BranchProtection.empty()) {
6378         TargetInfo::BranchProtectionInfo BPI;
6379         StringRef DiagMsg;
6380         StringRef Arch = Attr.Architecture.empty()
6381                              ? CGM.getTarget().getTargetOpts().CPU
6382                              : Attr.Architecture;
6383         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6384                                                       Arch, BPI, DiagMsg)) {
6385           CGM.getDiags().Report(
6386               D->getLocation(),
6387               diag::warn_target_unsupported_branch_protection_attribute)
6388               << Arch;
6389         } else {
6390           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6391           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6392                  "Unexpected SignReturnAddressScopeKind");
6393           Fn->addFnAttr(
6394               "sign-return-address",
6395               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6396 
6397           Fn->addFnAttr("branch-target-enforcement",
6398                         BPI.BranchTargetEnforcement ? "true" : "false");
6399         }
6400       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6401                  CGM.getLangOpts().hasSignReturnAddress()) {
6402         // If the Branch Protection attribute is missing, validate the target
6403         // Architecture attribute against Branch Protection command line
6404         // settings.
6405         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6406           CGM.getDiags().Report(
6407               D->getLocation(),
6408               diag::warn_target_unsupported_branch_protection_attribute)
6409               << Attr.Architecture;
6410       }
6411     }
6412 
6413     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6414     if (!Attr)
6415       return;
6416 
6417     const char *Kind;
6418     switch (Attr->getInterrupt()) {
6419     case ARMInterruptAttr::Generic: Kind = ""; break;
6420     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6421     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6422     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6423     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6424     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6425     }
6426 
6427     Fn->addFnAttr("interrupt", Kind);
6428 
6429     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6430     if (ABI == ARMABIInfo::APCS)
6431       return;
6432 
6433     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6434     // however this is not necessarily true on taking any interrupt. Instruct
6435     // the backend to perform a realignment as part of the function prologue.
6436     llvm::AttrBuilder B(Fn->getContext());
6437     B.addStackAlignmentAttr(8);
6438     Fn->addFnAttrs(B);
6439   }
6440 };
6441 
6442 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6443 public:
6444   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6445       : ARMTargetCodeGenInfo(CGT, K) {}
6446 
6447   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6448                            CodeGen::CodeGenModule &CGM) const override;
6449 
6450   void getDependentLibraryOption(llvm::StringRef Lib,
6451                                  llvm::SmallString<24> &Opt) const override {
6452     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6453   }
6454 
6455   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6456                                llvm::SmallString<32> &Opt) const override {
6457     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6458   }
6459 };
6460 
6461 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6462     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6463   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6464   if (GV->isDeclaration())
6465     return;
6466   addStackProbeTargetAttributes(D, GV, CGM);
6467 }
6468 }
6469 
6470 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6471   if (!::classifyReturnType(getCXXABI(), FI, *this))
6472     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6473                                             FI.getCallingConvention());
6474 
6475   for (auto &I : FI.arguments())
6476     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6477                                   FI.getCallingConvention());
6478 
6479 
6480   // Always honor user-specified calling convention.
6481   if (FI.getCallingConvention() != llvm::CallingConv::C)
6482     return;
6483 
6484   llvm::CallingConv::ID cc = getRuntimeCC();
6485   if (cc != llvm::CallingConv::C)
6486     FI.setEffectiveCallingConvention(cc);
6487 }
6488 
6489 /// Return the default calling convention that LLVM will use.
6490 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6491   // The default calling convention that LLVM will infer.
6492   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6493     return llvm::CallingConv::ARM_AAPCS_VFP;
6494   else if (isEABI())
6495     return llvm::CallingConv::ARM_AAPCS;
6496   else
6497     return llvm::CallingConv::ARM_APCS;
6498 }
6499 
6500 /// Return the calling convention that our ABI would like us to use
6501 /// as the C calling convention.
6502 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6503   switch (getABIKind()) {
6504   case APCS: return llvm::CallingConv::ARM_APCS;
6505   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6506   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6507   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6508   }
6509   llvm_unreachable("bad ABI kind");
6510 }
6511 
6512 void ARMABIInfo::setCCs() {
6513   assert(getRuntimeCC() == llvm::CallingConv::C);
6514 
6515   // Don't muddy up the IR with a ton of explicit annotations if
6516   // they'd just match what LLVM will infer from the triple.
6517   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6518   if (abiCC != getLLVMDefaultCC())
6519     RuntimeCC = abiCC;
6520 }
6521 
6522 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6523   uint64_t Size = getContext().getTypeSize(Ty);
6524   if (Size <= 32) {
6525     llvm::Type *ResType =
6526         llvm::Type::getInt32Ty(getVMContext());
6527     return ABIArgInfo::getDirect(ResType);
6528   }
6529   if (Size == 64 || Size == 128) {
6530     auto *ResType = llvm::FixedVectorType::get(
6531         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6532     return ABIArgInfo::getDirect(ResType);
6533   }
6534   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6535 }
6536 
6537 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6538                                                     const Type *Base,
6539                                                     uint64_t Members) const {
6540   assert(Base && "Base class should be set for homogeneous aggregate");
6541   // Base can be a floating-point or a vector.
6542   if (const VectorType *VT = Base->getAs<VectorType>()) {
6543     // FP16 vectors should be converted to integer vectors
6544     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6545       uint64_t Size = getContext().getTypeSize(VT);
6546       auto *NewVecTy = llvm::FixedVectorType::get(
6547           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6548       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6549       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6550     }
6551   }
6552   unsigned Align = 0;
6553   if (getABIKind() == ARMABIInfo::AAPCS ||
6554       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6555     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6556     // default otherwise.
6557     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6558     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6559     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6560   }
6561   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6562 }
6563 
6564 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6565                                             unsigned functionCallConv) const {
6566   // 6.1.2.1 The following argument types are VFP CPRCs:
6567   //   A single-precision floating-point type (including promoted
6568   //   half-precision types); A double-precision floating-point type;
6569   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6570   //   with a Base Type of a single- or double-precision floating-point type,
6571   //   64-bit containerized vectors or 128-bit containerized vectors with one
6572   //   to four Elements.
6573   // Variadic functions should always marshal to the base standard.
6574   bool IsAAPCS_VFP =
6575       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6576 
6577   Ty = useFirstFieldIfTransparentUnion(Ty);
6578 
6579   // Handle illegal vector types here.
6580   if (isIllegalVectorType(Ty))
6581     return coerceIllegalVector(Ty);
6582 
6583   if (!isAggregateTypeForABI(Ty)) {
6584     // Treat an enum type as its underlying type.
6585     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6586       Ty = EnumTy->getDecl()->getIntegerType();
6587     }
6588 
6589     if (const auto *EIT = Ty->getAs<BitIntType>())
6590       if (EIT->getNumBits() > 64)
6591         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6592 
6593     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6594                                               : ABIArgInfo::getDirect());
6595   }
6596 
6597   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6598     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6599   }
6600 
6601   // Ignore empty records.
6602   if (isEmptyRecord(getContext(), Ty, true))
6603     return ABIArgInfo::getIgnore();
6604 
6605   if (IsAAPCS_VFP) {
6606     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6607     // into VFP registers.
6608     const Type *Base = nullptr;
6609     uint64_t Members = 0;
6610     if (isHomogeneousAggregate(Ty, Base, Members))
6611       return classifyHomogeneousAggregate(Ty, Base, Members);
6612   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6613     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6614     // this convention even for a variadic function: the backend will use GPRs
6615     // if needed.
6616     const Type *Base = nullptr;
6617     uint64_t Members = 0;
6618     if (isHomogeneousAggregate(Ty, Base, Members)) {
6619       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6620       llvm::Type *Ty =
6621         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6622       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6623     }
6624   }
6625 
6626   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6627       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6628     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6629     // bigger than 128-bits, they get placed in space allocated by the caller,
6630     // and a pointer is passed.
6631     return ABIArgInfo::getIndirect(
6632         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6633   }
6634 
6635   // Support byval for ARM.
6636   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6637   // most 8-byte. We realign the indirect argument if type alignment is bigger
6638   // than ABI alignment.
6639   uint64_t ABIAlign = 4;
6640   uint64_t TyAlign;
6641   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6642       getABIKind() == ARMABIInfo::AAPCS) {
6643     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6644     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6645   } else {
6646     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6647   }
6648   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6649     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6650     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6651                                    /*ByVal=*/true,
6652                                    /*Realign=*/TyAlign > ABIAlign);
6653   }
6654 
6655   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6656   // same size and alignment.
6657   if (getTarget().isRenderScriptTarget()) {
6658     return coerceToIntArray(Ty, getContext(), getVMContext());
6659   }
6660 
6661   // Otherwise, pass by coercing to a structure of the appropriate size.
6662   llvm::Type* ElemTy;
6663   unsigned SizeRegs;
6664   // FIXME: Try to match the types of the arguments more accurately where
6665   // we can.
6666   if (TyAlign <= 4) {
6667     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6668     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6669   } else {
6670     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6671     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6672   }
6673 
6674   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6675 }
6676 
6677 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6678                               llvm::LLVMContext &VMContext) {
6679   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6680   // is called integer-like if its size is less than or equal to one word, and
6681   // the offset of each of its addressable sub-fields is zero.
6682 
6683   uint64_t Size = Context.getTypeSize(Ty);
6684 
6685   // Check that the type fits in a word.
6686   if (Size > 32)
6687     return false;
6688 
6689   // FIXME: Handle vector types!
6690   if (Ty->isVectorType())
6691     return false;
6692 
6693   // Float types are never treated as "integer like".
6694   if (Ty->isRealFloatingType())
6695     return false;
6696 
6697   // If this is a builtin or pointer type then it is ok.
6698   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6699     return true;
6700 
6701   // Small complex integer types are "integer like".
6702   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6703     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6704 
6705   // Single element and zero sized arrays should be allowed, by the definition
6706   // above, but they are not.
6707 
6708   // Otherwise, it must be a record type.
6709   const RecordType *RT = Ty->getAs<RecordType>();
6710   if (!RT) return false;
6711 
6712   // Ignore records with flexible arrays.
6713   const RecordDecl *RD = RT->getDecl();
6714   if (RD->hasFlexibleArrayMember())
6715     return false;
6716 
6717   // Check that all sub-fields are at offset 0, and are themselves "integer
6718   // like".
6719   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6720 
6721   bool HadField = false;
6722   unsigned idx = 0;
6723   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6724        i != e; ++i, ++idx) {
6725     const FieldDecl *FD = *i;
6726 
6727     // Bit-fields are not addressable, we only need to verify they are "integer
6728     // like". We still have to disallow a subsequent non-bitfield, for example:
6729     //   struct { int : 0; int x }
6730     // is non-integer like according to gcc.
6731     if (FD->isBitField()) {
6732       if (!RD->isUnion())
6733         HadField = true;
6734 
6735       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6736         return false;
6737 
6738       continue;
6739     }
6740 
6741     // Check if this field is at offset 0.
6742     if (Layout.getFieldOffset(idx) != 0)
6743       return false;
6744 
6745     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6746       return false;
6747 
6748     // Only allow at most one field in a structure. This doesn't match the
6749     // wording above, but follows gcc in situations with a field following an
6750     // empty structure.
6751     if (!RD->isUnion()) {
6752       if (HadField)
6753         return false;
6754 
6755       HadField = true;
6756     }
6757   }
6758 
6759   return true;
6760 }
6761 
6762 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6763                                           unsigned functionCallConv) const {
6764 
6765   // Variadic functions should always marshal to the base standard.
6766   bool IsAAPCS_VFP =
6767       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6768 
6769   if (RetTy->isVoidType())
6770     return ABIArgInfo::getIgnore();
6771 
6772   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6773     // Large vector types should be returned via memory.
6774     if (getContext().getTypeSize(RetTy) > 128)
6775       return getNaturalAlignIndirect(RetTy);
6776     // TODO: FP16/BF16 vectors should be converted to integer vectors
6777     // This check is similar  to isIllegalVectorType - refactor?
6778     if ((!getTarget().hasLegalHalfType() &&
6779         (VT->getElementType()->isFloat16Type() ||
6780          VT->getElementType()->isHalfType())) ||
6781         (IsFloatABISoftFP &&
6782          VT->getElementType()->isBFloat16Type()))
6783       return coerceIllegalVector(RetTy);
6784   }
6785 
6786   if (!isAggregateTypeForABI(RetTy)) {
6787     // Treat an enum type as its underlying type.
6788     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6789       RetTy = EnumTy->getDecl()->getIntegerType();
6790 
6791     if (const auto *EIT = RetTy->getAs<BitIntType>())
6792       if (EIT->getNumBits() > 64)
6793         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6794 
6795     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6796                                                 : ABIArgInfo::getDirect();
6797   }
6798 
6799   // Are we following APCS?
6800   if (getABIKind() == APCS) {
6801     if (isEmptyRecord(getContext(), RetTy, false))
6802       return ABIArgInfo::getIgnore();
6803 
6804     // Complex types are all returned as packed integers.
6805     //
6806     // FIXME: Consider using 2 x vector types if the back end handles them
6807     // correctly.
6808     if (RetTy->isAnyComplexType())
6809       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6810           getVMContext(), getContext().getTypeSize(RetTy)));
6811 
6812     // Integer like structures are returned in r0.
6813     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6814       // Return in the smallest viable integer type.
6815       uint64_t Size = getContext().getTypeSize(RetTy);
6816       if (Size <= 8)
6817         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6818       if (Size <= 16)
6819         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6820       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6821     }
6822 
6823     // Otherwise return in memory.
6824     return getNaturalAlignIndirect(RetTy);
6825   }
6826 
6827   // Otherwise this is an AAPCS variant.
6828 
6829   if (isEmptyRecord(getContext(), RetTy, true))
6830     return ABIArgInfo::getIgnore();
6831 
6832   // Check for homogeneous aggregates with AAPCS-VFP.
6833   if (IsAAPCS_VFP) {
6834     const Type *Base = nullptr;
6835     uint64_t Members = 0;
6836     if (isHomogeneousAggregate(RetTy, Base, Members))
6837       return classifyHomogeneousAggregate(RetTy, Base, Members);
6838   }
6839 
6840   // Aggregates <= 4 bytes are returned in r0; other aggregates
6841   // are returned indirectly.
6842   uint64_t Size = getContext().getTypeSize(RetTy);
6843   if (Size <= 32) {
6844     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6845     // same size and alignment.
6846     if (getTarget().isRenderScriptTarget()) {
6847       return coerceToIntArray(RetTy, getContext(), getVMContext());
6848     }
6849     if (getDataLayout().isBigEndian())
6850       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6851       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6852 
6853     // Return in the smallest viable integer type.
6854     if (Size <= 8)
6855       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6856     if (Size <= 16)
6857       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6858     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6859   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6860     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6861     llvm::Type *CoerceTy =
6862         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6863     return ABIArgInfo::getDirect(CoerceTy);
6864   }
6865 
6866   return getNaturalAlignIndirect(RetTy);
6867 }
6868 
6869 /// isIllegalVector - check whether Ty is an illegal vector type.
6870 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6871   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6872     // On targets that don't support half, fp16 or bfloat, they are expanded
6873     // into float, and we don't want the ABI to depend on whether or not they
6874     // are supported in hardware. Thus return false to coerce vectors of these
6875     // types into integer vectors.
6876     // We do not depend on hasLegalHalfType for bfloat as it is a
6877     // separate IR type.
6878     if ((!getTarget().hasLegalHalfType() &&
6879         (VT->getElementType()->isFloat16Type() ||
6880          VT->getElementType()->isHalfType())) ||
6881         (IsFloatABISoftFP &&
6882          VT->getElementType()->isBFloat16Type()))
6883       return true;
6884     if (isAndroid()) {
6885       // Android shipped using Clang 3.1, which supported a slightly different
6886       // vector ABI. The primary differences were that 3-element vector types
6887       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6888       // accepts that legacy behavior for Android only.
6889       // Check whether VT is legal.
6890       unsigned NumElements = VT->getNumElements();
6891       // NumElements should be power of 2 or equal to 3.
6892       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6893         return true;
6894     } else {
6895       // Check whether VT is legal.
6896       unsigned NumElements = VT->getNumElements();
6897       uint64_t Size = getContext().getTypeSize(VT);
6898       // NumElements should be power of 2.
6899       if (!llvm::isPowerOf2_32(NumElements))
6900         return true;
6901       // Size should be greater than 32 bits.
6902       return Size <= 32;
6903     }
6904   }
6905   return false;
6906 }
6907 
6908 /// Return true if a type contains any 16-bit floating point vectors
6909 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6910   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6911     uint64_t NElements = AT->getSize().getZExtValue();
6912     if (NElements == 0)
6913       return false;
6914     return containsAnyFP16Vectors(AT->getElementType());
6915   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6916     const RecordDecl *RD = RT->getDecl();
6917 
6918     // If this is a C++ record, check the bases first.
6919     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6920       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6921             return containsAnyFP16Vectors(B.getType());
6922           }))
6923         return true;
6924 
6925     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6926           return FD && containsAnyFP16Vectors(FD->getType());
6927         }))
6928       return true;
6929 
6930     return false;
6931   } else {
6932     if (const VectorType *VT = Ty->getAs<VectorType>())
6933       return (VT->getElementType()->isFloat16Type() ||
6934               VT->getElementType()->isBFloat16Type() ||
6935               VT->getElementType()->isHalfType());
6936     return false;
6937   }
6938 }
6939 
6940 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6941                                            llvm::Type *eltTy,
6942                                            unsigned numElts) const {
6943   if (!llvm::isPowerOf2_32(numElts))
6944     return false;
6945   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6946   if (size > 64)
6947     return false;
6948   if (vectorSize.getQuantity() != 8 &&
6949       (vectorSize.getQuantity() != 16 || numElts == 1))
6950     return false;
6951   return true;
6952 }
6953 
6954 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6955   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6956   // double, or 64-bit or 128-bit vectors.
6957   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6958     if (BT->getKind() == BuiltinType::Float ||
6959         BT->getKind() == BuiltinType::Double ||
6960         BT->getKind() == BuiltinType::LongDouble)
6961       return true;
6962   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6963     unsigned VecSize = getContext().getTypeSize(VT);
6964     if (VecSize == 64 || VecSize == 128)
6965       return true;
6966   }
6967   return false;
6968 }
6969 
6970 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6971                                                    uint64_t Members) const {
6972   return Members <= 4;
6973 }
6974 
6975 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6976                                         bool acceptHalf) const {
6977   // Give precedence to user-specified calling conventions.
6978   if (callConvention != llvm::CallingConv::C)
6979     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6980   else
6981     return (getABIKind() == AAPCS_VFP) ||
6982            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6983 }
6984 
6985 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6986                               QualType Ty) const {
6987   CharUnits SlotSize = CharUnits::fromQuantity(4);
6988 
6989   // Empty records are ignored for parameter passing purposes.
6990   if (isEmptyRecord(getContext(), Ty, true)) {
6991     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6992     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6993     return Addr;
6994   }
6995 
6996   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6997   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6998 
6999   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7000   bool IsIndirect = false;
7001   const Type *Base = nullptr;
7002   uint64_t Members = 0;
7003   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7004     IsIndirect = true;
7005 
7006   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7007   // allocated by the caller.
7008   } else if (TySize > CharUnits::fromQuantity(16) &&
7009              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7010              !isHomogeneousAggregate(Ty, Base, Members)) {
7011     IsIndirect = true;
7012 
7013   // Otherwise, bound the type's ABI alignment.
7014   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7015   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7016   // Our callers should be prepared to handle an under-aligned address.
7017   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7018              getABIKind() == ARMABIInfo::AAPCS) {
7019     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7020     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7021   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7022     // ARMv7k allows type alignment up to 16 bytes.
7023     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7024     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7025   } else {
7026     TyAlignForABI = CharUnits::fromQuantity(4);
7027   }
7028 
7029   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7030   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7031                           SlotSize, /*AllowHigherAlign*/ true);
7032 }
7033 
7034 //===----------------------------------------------------------------------===//
7035 // NVPTX ABI Implementation
7036 //===----------------------------------------------------------------------===//
7037 
7038 namespace {
7039 
7040 class NVPTXTargetCodeGenInfo;
7041 
7042 class NVPTXABIInfo : public ABIInfo {
7043   NVPTXTargetCodeGenInfo &CGInfo;
7044 
7045 public:
7046   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7047       : ABIInfo(CGT), CGInfo(Info) {}
7048 
7049   ABIArgInfo classifyReturnType(QualType RetTy) const;
7050   ABIArgInfo classifyArgumentType(QualType Ty) const;
7051 
7052   void computeInfo(CGFunctionInfo &FI) const override;
7053   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7054                     QualType Ty) const override;
7055   bool isUnsupportedType(QualType T) const;
7056   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7057 };
7058 
7059 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7060 public:
7061   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7062       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7063 
7064   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7065                            CodeGen::CodeGenModule &M) const override;
7066   bool shouldEmitStaticExternCAliases() const override;
7067 
7068   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7069     // On the device side, surface reference is represented as an object handle
7070     // in 64-bit integer.
7071     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7072   }
7073 
7074   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7075     // On the device side, texture reference is represented as an object handle
7076     // in 64-bit integer.
7077     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7078   }
7079 
7080   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7081                                               LValue Src) const override {
7082     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7083     return true;
7084   }
7085 
7086   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7087                                               LValue Src) const override {
7088     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7089     return true;
7090   }
7091 
7092 private:
7093   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7094   // resulting MDNode to the nvvm.annotations MDNode.
7095   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7096                               int Operand);
7097 
7098   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7099                                            LValue Src) {
7100     llvm::Value *Handle = nullptr;
7101     llvm::Constant *C =
7102         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7103     // Lookup `addrspacecast` through the constant pointer if any.
7104     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7105       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7106     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7107       // Load the handle from the specific global variable using
7108       // `nvvm.texsurf.handle.internal` intrinsic.
7109       Handle = CGF.EmitRuntimeCall(
7110           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7111                                {GV->getType()}),
7112           {GV}, "texsurf_handle");
7113     } else
7114       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7115     CGF.EmitStoreOfScalar(Handle, Dst);
7116   }
7117 };
7118 
7119 /// Checks if the type is unsupported directly by the current target.
7120 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7121   ASTContext &Context = getContext();
7122   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7123     return true;
7124   if (!Context.getTargetInfo().hasFloat128Type() &&
7125       (T->isFloat128Type() ||
7126        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7127     return true;
7128   if (const auto *EIT = T->getAs<BitIntType>())
7129     return EIT->getNumBits() >
7130            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7131   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7132       Context.getTypeSize(T) > 64U)
7133     return true;
7134   if (const auto *AT = T->getAsArrayTypeUnsafe())
7135     return isUnsupportedType(AT->getElementType());
7136   const auto *RT = T->getAs<RecordType>();
7137   if (!RT)
7138     return false;
7139   const RecordDecl *RD = RT->getDecl();
7140 
7141   // If this is a C++ record, check the bases first.
7142   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7143     for (const CXXBaseSpecifier &I : CXXRD->bases())
7144       if (isUnsupportedType(I.getType()))
7145         return true;
7146 
7147   for (const FieldDecl *I : RD->fields())
7148     if (isUnsupportedType(I->getType()))
7149       return true;
7150   return false;
7151 }
7152 
7153 /// Coerce the given type into an array with maximum allowed size of elements.
7154 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7155                                                    unsigned MaxSize) const {
7156   // Alignment and Size are measured in bits.
7157   const uint64_t Size = getContext().getTypeSize(Ty);
7158   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7159   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7160   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7161   const uint64_t NumElements = (Size + Div - 1) / Div;
7162   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7163 }
7164 
7165 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7166   if (RetTy->isVoidType())
7167     return ABIArgInfo::getIgnore();
7168 
7169   if (getContext().getLangOpts().OpenMP &&
7170       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7171     return coerceToIntArrayWithLimit(RetTy, 64);
7172 
7173   // note: this is different from default ABI
7174   if (!RetTy->isScalarType())
7175     return ABIArgInfo::getDirect();
7176 
7177   // Treat an enum type as its underlying type.
7178   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7179     RetTy = EnumTy->getDecl()->getIntegerType();
7180 
7181   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7182                                                : ABIArgInfo::getDirect());
7183 }
7184 
7185 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7186   // Treat an enum type as its underlying type.
7187   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7188     Ty = EnumTy->getDecl()->getIntegerType();
7189 
7190   // Return aggregates type as indirect by value
7191   if (isAggregateTypeForABI(Ty)) {
7192     // Under CUDA device compilation, tex/surf builtin types are replaced with
7193     // object types and passed directly.
7194     if (getContext().getLangOpts().CUDAIsDevice) {
7195       if (Ty->isCUDADeviceBuiltinSurfaceType())
7196         return ABIArgInfo::getDirect(
7197             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7198       if (Ty->isCUDADeviceBuiltinTextureType())
7199         return ABIArgInfo::getDirect(
7200             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7201     }
7202     return getNaturalAlignIndirect(Ty, /* byval */ true);
7203   }
7204 
7205   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7206     if ((EIT->getNumBits() > 128) ||
7207         (!getContext().getTargetInfo().hasInt128Type() &&
7208          EIT->getNumBits() > 64))
7209       return getNaturalAlignIndirect(Ty, /* byval */ true);
7210   }
7211 
7212   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7213                                             : ABIArgInfo::getDirect());
7214 }
7215 
7216 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7217   if (!getCXXABI().classifyReturnType(FI))
7218     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7219   for (auto &I : FI.arguments())
7220     I.info = classifyArgumentType(I.type);
7221 
7222   // Always honor user-specified calling convention.
7223   if (FI.getCallingConvention() != llvm::CallingConv::C)
7224     return;
7225 
7226   FI.setEffectiveCallingConvention(getRuntimeCC());
7227 }
7228 
7229 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7230                                 QualType Ty) const {
7231   llvm_unreachable("NVPTX does not support varargs");
7232 }
7233 
7234 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7235     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7236   if (GV->isDeclaration())
7237     return;
7238   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7239   if (VD) {
7240     if (M.getLangOpts().CUDA) {
7241       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7242         addNVVMMetadata(GV, "surface", 1);
7243       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7244         addNVVMMetadata(GV, "texture", 1);
7245       return;
7246     }
7247   }
7248 
7249   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7250   if (!FD) return;
7251 
7252   llvm::Function *F = cast<llvm::Function>(GV);
7253 
7254   // Perform special handling in OpenCL mode
7255   if (M.getLangOpts().OpenCL) {
7256     // Use OpenCL function attributes to check for kernel functions
7257     // By default, all functions are device functions
7258     if (FD->hasAttr<OpenCLKernelAttr>()) {
7259       // OpenCL __kernel functions get kernel metadata
7260       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7261       addNVVMMetadata(F, "kernel", 1);
7262       // And kernel functions are not subject to inlining
7263       F->addFnAttr(llvm::Attribute::NoInline);
7264     }
7265   }
7266 
7267   // Perform special handling in CUDA mode.
7268   if (M.getLangOpts().CUDA) {
7269     // CUDA __global__ functions get a kernel metadata entry.  Since
7270     // __global__ functions cannot be called from the device, we do not
7271     // need to set the noinline attribute.
7272     if (FD->hasAttr<CUDAGlobalAttr>()) {
7273       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7274       addNVVMMetadata(F, "kernel", 1);
7275     }
7276     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7277       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7278       llvm::APSInt MaxThreads(32);
7279       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7280       if (MaxThreads > 0)
7281         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7282 
7283       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7284       // not specified in __launch_bounds__ or if the user specified a 0 value,
7285       // we don't have to add a PTX directive.
7286       if (Attr->getMinBlocks()) {
7287         llvm::APSInt MinBlocks(32);
7288         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7289         if (MinBlocks > 0)
7290           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7291           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7292       }
7293     }
7294   }
7295 }
7296 
7297 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7298                                              StringRef Name, int Operand) {
7299   llvm::Module *M = GV->getParent();
7300   llvm::LLVMContext &Ctx = M->getContext();
7301 
7302   // Get "nvvm.annotations" metadata node
7303   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7304 
7305   llvm::Metadata *MDVals[] = {
7306       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7307       llvm::ConstantAsMetadata::get(
7308           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7309   // Append metadata to nvvm.annotations
7310   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7311 }
7312 
7313 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7314   return false;
7315 }
7316 }
7317 
7318 //===----------------------------------------------------------------------===//
7319 // SystemZ ABI Implementation
7320 //===----------------------------------------------------------------------===//
7321 
7322 namespace {
7323 
7324 class SystemZABIInfo : public SwiftABIInfo {
7325   bool HasVector;
7326   bool IsSoftFloatABI;
7327 
7328 public:
7329   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7330     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7331 
7332   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7333   bool isCompoundType(QualType Ty) const;
7334   bool isVectorArgumentType(QualType Ty) const;
7335   bool isFPArgumentType(QualType Ty) const;
7336   QualType GetSingleElementType(QualType Ty) const;
7337 
7338   ABIArgInfo classifyReturnType(QualType RetTy) const;
7339   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7340 
7341   void computeInfo(CGFunctionInfo &FI) const override {
7342     if (!getCXXABI().classifyReturnType(FI))
7343       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7344     for (auto &I : FI.arguments())
7345       I.info = classifyArgumentType(I.type);
7346   }
7347 
7348   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7349                     QualType Ty) const override;
7350 
7351   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7352                                     bool asReturnValue) const override {
7353     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7354   }
7355   bool isSwiftErrorInRegister() const override {
7356     return false;
7357   }
7358 };
7359 
7360 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7361 public:
7362   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7363       : TargetCodeGenInfo(
7364             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7365 
7366   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7367                           CGBuilderTy &Builder,
7368                           CodeGenModule &CGM) const override {
7369     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7370     // Only use TDC in constrained FP mode.
7371     if (!Builder.getIsFPConstrained())
7372       return nullptr;
7373 
7374     llvm::Type *Ty = V->getType();
7375     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7376       llvm::Module &M = CGM.getModule();
7377       auto &Ctx = M.getContext();
7378       llvm::Function *TDCFunc =
7379           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7380       unsigned TDCBits = 0;
7381       switch (BuiltinID) {
7382       case Builtin::BI__builtin_isnan:
7383         TDCBits = 0xf;
7384         break;
7385       case Builtin::BIfinite:
7386       case Builtin::BI__finite:
7387       case Builtin::BIfinitef:
7388       case Builtin::BI__finitef:
7389       case Builtin::BIfinitel:
7390       case Builtin::BI__finitel:
7391       case Builtin::BI__builtin_isfinite:
7392         TDCBits = 0xfc0;
7393         break;
7394       case Builtin::BI__builtin_isinf:
7395         TDCBits = 0x30;
7396         break;
7397       default:
7398         break;
7399       }
7400       if (TDCBits)
7401         return Builder.CreateCall(
7402             TDCFunc,
7403             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7404     }
7405     return nullptr;
7406   }
7407 };
7408 }
7409 
7410 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7411   // Treat an enum type as its underlying type.
7412   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7413     Ty = EnumTy->getDecl()->getIntegerType();
7414 
7415   // Promotable integer types are required to be promoted by the ABI.
7416   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7417     return true;
7418 
7419   if (const auto *EIT = Ty->getAs<BitIntType>())
7420     if (EIT->getNumBits() < 64)
7421       return true;
7422 
7423   // 32-bit values must also be promoted.
7424   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7425     switch (BT->getKind()) {
7426     case BuiltinType::Int:
7427     case BuiltinType::UInt:
7428       return true;
7429     default:
7430       return false;
7431     }
7432   return false;
7433 }
7434 
7435 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7436   return (Ty->isAnyComplexType() ||
7437           Ty->isVectorType() ||
7438           isAggregateTypeForABI(Ty));
7439 }
7440 
7441 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7442   return (HasVector &&
7443           Ty->isVectorType() &&
7444           getContext().getTypeSize(Ty) <= 128);
7445 }
7446 
7447 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7448   if (IsSoftFloatABI)
7449     return false;
7450 
7451   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7452     switch (BT->getKind()) {
7453     case BuiltinType::Float:
7454     case BuiltinType::Double:
7455       return true;
7456     default:
7457       return false;
7458     }
7459 
7460   return false;
7461 }
7462 
7463 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7464   const RecordType *RT = Ty->getAs<RecordType>();
7465 
7466   if (RT && RT->isStructureOrClassType()) {
7467     const RecordDecl *RD = RT->getDecl();
7468     QualType Found;
7469 
7470     // If this is a C++ record, check the bases first.
7471     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7472       for (const auto &I : CXXRD->bases()) {
7473         QualType Base = I.getType();
7474 
7475         // Empty bases don't affect things either way.
7476         if (isEmptyRecord(getContext(), Base, true))
7477           continue;
7478 
7479         if (!Found.isNull())
7480           return Ty;
7481         Found = GetSingleElementType(Base);
7482       }
7483 
7484     // Check the fields.
7485     for (const auto *FD : RD->fields()) {
7486       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7487       // Unlike isSingleElementStruct(), empty structure and array fields
7488       // do count.  So do anonymous bitfields that aren't zero-sized.
7489       if (getContext().getLangOpts().CPlusPlus &&
7490           FD->isZeroLengthBitField(getContext()))
7491         continue;
7492       // Like isSingleElementStruct(), ignore C++20 empty data members.
7493       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7494           isEmptyRecord(getContext(), FD->getType(), true))
7495         continue;
7496 
7497       // Unlike isSingleElementStruct(), arrays do not count.
7498       // Nested structures still do though.
7499       if (!Found.isNull())
7500         return Ty;
7501       Found = GetSingleElementType(FD->getType());
7502     }
7503 
7504     // Unlike isSingleElementStruct(), trailing padding is allowed.
7505     // An 8-byte aligned struct s { float f; } is passed as a double.
7506     if (!Found.isNull())
7507       return Found;
7508   }
7509 
7510   return Ty;
7511 }
7512 
7513 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7514                                   QualType Ty) const {
7515   // Assume that va_list type is correct; should be pointer to LLVM type:
7516   // struct {
7517   //   i64 __gpr;
7518   //   i64 __fpr;
7519   //   i8 *__overflow_arg_area;
7520   //   i8 *__reg_save_area;
7521   // };
7522 
7523   // Every non-vector argument occupies 8 bytes and is passed by preference
7524   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7525   // always passed on the stack.
7526   Ty = getContext().getCanonicalType(Ty);
7527   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7528   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7529   llvm::Type *DirectTy = ArgTy;
7530   ABIArgInfo AI = classifyArgumentType(Ty);
7531   bool IsIndirect = AI.isIndirect();
7532   bool InFPRs = false;
7533   bool IsVector = false;
7534   CharUnits UnpaddedSize;
7535   CharUnits DirectAlign;
7536   if (IsIndirect) {
7537     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7538     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7539   } else {
7540     if (AI.getCoerceToType())
7541       ArgTy = AI.getCoerceToType();
7542     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7543     IsVector = ArgTy->isVectorTy();
7544     UnpaddedSize = TyInfo.Width;
7545     DirectAlign = TyInfo.Align;
7546   }
7547   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7548   if (IsVector && UnpaddedSize > PaddedSize)
7549     PaddedSize = CharUnits::fromQuantity(16);
7550   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7551 
7552   CharUnits Padding = (PaddedSize - UnpaddedSize);
7553 
7554   llvm::Type *IndexTy = CGF.Int64Ty;
7555   llvm::Value *PaddedSizeV =
7556     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7557 
7558   if (IsVector) {
7559     // Work out the address of a vector argument on the stack.
7560     // Vector arguments are always passed in the high bits of a
7561     // single (8 byte) or double (16 byte) stack slot.
7562     Address OverflowArgAreaPtr =
7563         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7564     Address OverflowArgArea =
7565       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7566               TyInfo.Align);
7567     Address MemAddr =
7568       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7569 
7570     // Update overflow_arg_area_ptr pointer
7571     llvm::Value *NewOverflowArgArea =
7572       CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7573                             OverflowArgArea.getPointer(), PaddedSizeV,
7574                             "overflow_arg_area");
7575     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7576 
7577     return MemAddr;
7578   }
7579 
7580   assert(PaddedSize.getQuantity() == 8);
7581 
7582   unsigned MaxRegs, RegCountField, RegSaveIndex;
7583   CharUnits RegPadding;
7584   if (InFPRs) {
7585     MaxRegs = 4; // Maximum of 4 FPR arguments
7586     RegCountField = 1; // __fpr
7587     RegSaveIndex = 16; // save offset for f0
7588     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7589   } else {
7590     MaxRegs = 5; // Maximum of 5 GPR arguments
7591     RegCountField = 0; // __gpr
7592     RegSaveIndex = 2; // save offset for r2
7593     RegPadding = Padding; // values are passed in the low bits of a GPR
7594   }
7595 
7596   Address RegCountPtr =
7597       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7598   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7599   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7600   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7601                                                  "fits_in_regs");
7602 
7603   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7604   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7605   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7606   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7607 
7608   // Emit code to load the value if it was passed in registers.
7609   CGF.EmitBlock(InRegBlock);
7610 
7611   // Work out the address of an argument register.
7612   llvm::Value *ScaledRegCount =
7613     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7614   llvm::Value *RegBase =
7615     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7616                                       + RegPadding.getQuantity());
7617   llvm::Value *RegOffset =
7618     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7619   Address RegSaveAreaPtr =
7620       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7621   llvm::Value *RegSaveArea =
7622     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7623   Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
7624                                            "raw_reg_addr"),
7625                      PaddedSize);
7626   Address RegAddr =
7627     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7628 
7629   // Update the register count
7630   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7631   llvm::Value *NewRegCount =
7632     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7633   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7634   CGF.EmitBranch(ContBlock);
7635 
7636   // Emit code to load the value if it was passed in memory.
7637   CGF.EmitBlock(InMemBlock);
7638 
7639   // Work out the address of a stack argument.
7640   Address OverflowArgAreaPtr =
7641       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7642   Address OverflowArgArea =
7643     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7644             PaddedSize);
7645   Address RawMemAddr =
7646     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7647   Address MemAddr =
7648     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7649 
7650   // Update overflow_arg_area_ptr pointer
7651   llvm::Value *NewOverflowArgArea =
7652     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7653                           OverflowArgArea.getPointer(), PaddedSizeV,
7654                           "overflow_arg_area");
7655   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7656   CGF.EmitBranch(ContBlock);
7657 
7658   // Return the appropriate result.
7659   CGF.EmitBlock(ContBlock);
7660   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7661                                  MemAddr, InMemBlock, "va_arg.addr");
7662 
7663   if (IsIndirect)
7664     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7665                       TyInfo.Align);
7666 
7667   return ResAddr;
7668 }
7669 
7670 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7671   if (RetTy->isVoidType())
7672     return ABIArgInfo::getIgnore();
7673   if (isVectorArgumentType(RetTy))
7674     return ABIArgInfo::getDirect();
7675   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7676     return getNaturalAlignIndirect(RetTy);
7677   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7678                                                : ABIArgInfo::getDirect());
7679 }
7680 
7681 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7682   // Handle the generic C++ ABI.
7683   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7684     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7685 
7686   // Integers and enums are extended to full register width.
7687   if (isPromotableIntegerTypeForABI(Ty))
7688     return ABIArgInfo::getExtend(Ty);
7689 
7690   // Handle vector types and vector-like structure types.  Note that
7691   // as opposed to float-like structure types, we do not allow any
7692   // padding for vector-like structures, so verify the sizes match.
7693   uint64_t Size = getContext().getTypeSize(Ty);
7694   QualType SingleElementTy = GetSingleElementType(Ty);
7695   if (isVectorArgumentType(SingleElementTy) &&
7696       getContext().getTypeSize(SingleElementTy) == Size)
7697     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7698 
7699   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7700   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7701     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7702 
7703   // Handle small structures.
7704   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7705     // Structures with flexible arrays have variable length, so really
7706     // fail the size test above.
7707     const RecordDecl *RD = RT->getDecl();
7708     if (RD->hasFlexibleArrayMember())
7709       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7710 
7711     // The structure is passed as an unextended integer, a float, or a double.
7712     llvm::Type *PassTy;
7713     if (isFPArgumentType(SingleElementTy)) {
7714       assert(Size == 32 || Size == 64);
7715       if (Size == 32)
7716         PassTy = llvm::Type::getFloatTy(getVMContext());
7717       else
7718         PassTy = llvm::Type::getDoubleTy(getVMContext());
7719     } else
7720       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7721     return ABIArgInfo::getDirect(PassTy);
7722   }
7723 
7724   // Non-structure compounds are passed indirectly.
7725   if (isCompoundType(Ty))
7726     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7727 
7728   return ABIArgInfo::getDirect(nullptr);
7729 }
7730 
7731 //===----------------------------------------------------------------------===//
7732 // MSP430 ABI Implementation
7733 //===----------------------------------------------------------------------===//
7734 
7735 namespace {
7736 
7737 class MSP430ABIInfo : public DefaultABIInfo {
7738   static ABIArgInfo complexArgInfo() {
7739     ABIArgInfo Info = ABIArgInfo::getDirect();
7740     Info.setCanBeFlattened(false);
7741     return Info;
7742   }
7743 
7744 public:
7745   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7746 
7747   ABIArgInfo classifyReturnType(QualType RetTy) const {
7748     if (RetTy->isAnyComplexType())
7749       return complexArgInfo();
7750 
7751     return DefaultABIInfo::classifyReturnType(RetTy);
7752   }
7753 
7754   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7755     if (RetTy->isAnyComplexType())
7756       return complexArgInfo();
7757 
7758     return DefaultABIInfo::classifyArgumentType(RetTy);
7759   }
7760 
7761   // Just copy the original implementations because
7762   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7763   void computeInfo(CGFunctionInfo &FI) const override {
7764     if (!getCXXABI().classifyReturnType(FI))
7765       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7766     for (auto &I : FI.arguments())
7767       I.info = classifyArgumentType(I.type);
7768   }
7769 
7770   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7771                     QualType Ty) const override {
7772     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7773   }
7774 };
7775 
7776 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7777 public:
7778   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7779       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7780   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7781                            CodeGen::CodeGenModule &M) const override;
7782 };
7783 
7784 }
7785 
7786 void MSP430TargetCodeGenInfo::setTargetAttributes(
7787     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7788   if (GV->isDeclaration())
7789     return;
7790   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7791     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7792     if (!InterruptAttr)
7793       return;
7794 
7795     // Handle 'interrupt' attribute:
7796     llvm::Function *F = cast<llvm::Function>(GV);
7797 
7798     // Step 1: Set ISR calling convention.
7799     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7800 
7801     // Step 2: Add attributes goodness.
7802     F->addFnAttr(llvm::Attribute::NoInline);
7803     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7804   }
7805 }
7806 
7807 //===----------------------------------------------------------------------===//
7808 // MIPS ABI Implementation.  This works for both little-endian and
7809 // big-endian variants.
7810 //===----------------------------------------------------------------------===//
7811 
7812 namespace {
7813 class MipsABIInfo : public ABIInfo {
7814   bool IsO32;
7815   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7816   void CoerceToIntArgs(uint64_t TySize,
7817                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7818   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7819   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7820   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7821 public:
7822   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7823     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7824     StackAlignInBytes(IsO32 ? 8 : 16) {}
7825 
7826   ABIArgInfo classifyReturnType(QualType RetTy) const;
7827   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7828   void computeInfo(CGFunctionInfo &FI) const override;
7829   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7830                     QualType Ty) const override;
7831   ABIArgInfo extendType(QualType Ty) const;
7832 };
7833 
7834 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7835   unsigned SizeOfUnwindException;
7836 public:
7837   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7838       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7839         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7840 
7841   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7842     return 29;
7843   }
7844 
7845   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7846                            CodeGen::CodeGenModule &CGM) const override {
7847     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7848     if (!FD) return;
7849     llvm::Function *Fn = cast<llvm::Function>(GV);
7850 
7851     if (FD->hasAttr<MipsLongCallAttr>())
7852       Fn->addFnAttr("long-call");
7853     else if (FD->hasAttr<MipsShortCallAttr>())
7854       Fn->addFnAttr("short-call");
7855 
7856     // Other attributes do not have a meaning for declarations.
7857     if (GV->isDeclaration())
7858       return;
7859 
7860     if (FD->hasAttr<Mips16Attr>()) {
7861       Fn->addFnAttr("mips16");
7862     }
7863     else if (FD->hasAttr<NoMips16Attr>()) {
7864       Fn->addFnAttr("nomips16");
7865     }
7866 
7867     if (FD->hasAttr<MicroMipsAttr>())
7868       Fn->addFnAttr("micromips");
7869     else if (FD->hasAttr<NoMicroMipsAttr>())
7870       Fn->addFnAttr("nomicromips");
7871 
7872     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7873     if (!Attr)
7874       return;
7875 
7876     const char *Kind;
7877     switch (Attr->getInterrupt()) {
7878     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7879     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7880     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7881     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7882     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7883     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7884     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7885     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7886     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7887     }
7888 
7889     Fn->addFnAttr("interrupt", Kind);
7890 
7891   }
7892 
7893   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7894                                llvm::Value *Address) const override;
7895 
7896   unsigned getSizeOfUnwindException() const override {
7897     return SizeOfUnwindException;
7898   }
7899 };
7900 }
7901 
7902 void MipsABIInfo::CoerceToIntArgs(
7903     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7904   llvm::IntegerType *IntTy =
7905     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7906 
7907   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7908   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7909     ArgList.push_back(IntTy);
7910 
7911   // If necessary, add one more integer type to ArgList.
7912   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7913 
7914   if (R)
7915     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7916 }
7917 
7918 // In N32/64, an aligned double precision floating point field is passed in
7919 // a register.
7920 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7921   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7922 
7923   if (IsO32) {
7924     CoerceToIntArgs(TySize, ArgList);
7925     return llvm::StructType::get(getVMContext(), ArgList);
7926   }
7927 
7928   if (Ty->isComplexType())
7929     return CGT.ConvertType(Ty);
7930 
7931   const RecordType *RT = Ty->getAs<RecordType>();
7932 
7933   // Unions/vectors are passed in integer registers.
7934   if (!RT || !RT->isStructureOrClassType()) {
7935     CoerceToIntArgs(TySize, ArgList);
7936     return llvm::StructType::get(getVMContext(), ArgList);
7937   }
7938 
7939   const RecordDecl *RD = RT->getDecl();
7940   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7941   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7942 
7943   uint64_t LastOffset = 0;
7944   unsigned idx = 0;
7945   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7946 
7947   // Iterate over fields in the struct/class and check if there are any aligned
7948   // double fields.
7949   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7950        i != e; ++i, ++idx) {
7951     const QualType Ty = i->getType();
7952     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7953 
7954     if (!BT || BT->getKind() != BuiltinType::Double)
7955       continue;
7956 
7957     uint64_t Offset = Layout.getFieldOffset(idx);
7958     if (Offset % 64) // Ignore doubles that are not aligned.
7959       continue;
7960 
7961     // Add ((Offset - LastOffset) / 64) args of type i64.
7962     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7963       ArgList.push_back(I64);
7964 
7965     // Add double type.
7966     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7967     LastOffset = Offset + 64;
7968   }
7969 
7970   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7971   ArgList.append(IntArgList.begin(), IntArgList.end());
7972 
7973   return llvm::StructType::get(getVMContext(), ArgList);
7974 }
7975 
7976 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7977                                         uint64_t Offset) const {
7978   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7979     return nullptr;
7980 
7981   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7982 }
7983 
7984 ABIArgInfo
7985 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7986   Ty = useFirstFieldIfTransparentUnion(Ty);
7987 
7988   uint64_t OrigOffset = Offset;
7989   uint64_t TySize = getContext().getTypeSize(Ty);
7990   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7991 
7992   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7993                    (uint64_t)StackAlignInBytes);
7994   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7995   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7996 
7997   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7998     // Ignore empty aggregates.
7999     if (TySize == 0)
8000       return ABIArgInfo::getIgnore();
8001 
8002     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8003       Offset = OrigOffset + MinABIStackAlignInBytes;
8004       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8005     }
8006 
8007     // If we have reached here, aggregates are passed directly by coercing to
8008     // another structure type. Padding is inserted if the offset of the
8009     // aggregate is unaligned.
8010     ABIArgInfo ArgInfo =
8011         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8012                               getPaddingType(OrigOffset, CurrOffset));
8013     ArgInfo.setInReg(true);
8014     return ArgInfo;
8015   }
8016 
8017   // Treat an enum type as its underlying type.
8018   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8019     Ty = EnumTy->getDecl()->getIntegerType();
8020 
8021   // Make sure we pass indirectly things that are too large.
8022   if (const auto *EIT = Ty->getAs<BitIntType>())
8023     if (EIT->getNumBits() > 128 ||
8024         (EIT->getNumBits() > 64 &&
8025          !getContext().getTargetInfo().hasInt128Type()))
8026       return getNaturalAlignIndirect(Ty);
8027 
8028   // All integral types are promoted to the GPR width.
8029   if (Ty->isIntegralOrEnumerationType())
8030     return extendType(Ty);
8031 
8032   return ABIArgInfo::getDirect(
8033       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8034 }
8035 
8036 llvm::Type*
8037 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8038   const RecordType *RT = RetTy->getAs<RecordType>();
8039   SmallVector<llvm::Type*, 8> RTList;
8040 
8041   if (RT && RT->isStructureOrClassType()) {
8042     const RecordDecl *RD = RT->getDecl();
8043     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8044     unsigned FieldCnt = Layout.getFieldCount();
8045 
8046     // N32/64 returns struct/classes in floating point registers if the
8047     // following conditions are met:
8048     // 1. The size of the struct/class is no larger than 128-bit.
8049     // 2. The struct/class has one or two fields all of which are floating
8050     //    point types.
8051     // 3. The offset of the first field is zero (this follows what gcc does).
8052     //
8053     // Any other composite results are returned in integer registers.
8054     //
8055     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8056       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8057       for (; b != e; ++b) {
8058         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8059 
8060         if (!BT || !BT->isFloatingPoint())
8061           break;
8062 
8063         RTList.push_back(CGT.ConvertType(b->getType()));
8064       }
8065 
8066       if (b == e)
8067         return llvm::StructType::get(getVMContext(), RTList,
8068                                      RD->hasAttr<PackedAttr>());
8069 
8070       RTList.clear();
8071     }
8072   }
8073 
8074   CoerceToIntArgs(Size, RTList);
8075   return llvm::StructType::get(getVMContext(), RTList);
8076 }
8077 
8078 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8079   uint64_t Size = getContext().getTypeSize(RetTy);
8080 
8081   if (RetTy->isVoidType())
8082     return ABIArgInfo::getIgnore();
8083 
8084   // O32 doesn't treat zero-sized structs differently from other structs.
8085   // However, N32/N64 ignores zero sized return values.
8086   if (!IsO32 && Size == 0)
8087     return ABIArgInfo::getIgnore();
8088 
8089   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8090     if (Size <= 128) {
8091       if (RetTy->isAnyComplexType())
8092         return ABIArgInfo::getDirect();
8093 
8094       // O32 returns integer vectors in registers and N32/N64 returns all small
8095       // aggregates in registers.
8096       if (!IsO32 ||
8097           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8098         ABIArgInfo ArgInfo =
8099             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8100         ArgInfo.setInReg(true);
8101         return ArgInfo;
8102       }
8103     }
8104 
8105     return getNaturalAlignIndirect(RetTy);
8106   }
8107 
8108   // Treat an enum type as its underlying type.
8109   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8110     RetTy = EnumTy->getDecl()->getIntegerType();
8111 
8112   // Make sure we pass indirectly things that are too large.
8113   if (const auto *EIT = RetTy->getAs<BitIntType>())
8114     if (EIT->getNumBits() > 128 ||
8115         (EIT->getNumBits() > 64 &&
8116          !getContext().getTargetInfo().hasInt128Type()))
8117       return getNaturalAlignIndirect(RetTy);
8118 
8119   if (isPromotableIntegerTypeForABI(RetTy))
8120     return ABIArgInfo::getExtend(RetTy);
8121 
8122   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8123       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8124     return ABIArgInfo::getSignExtend(RetTy);
8125 
8126   return ABIArgInfo::getDirect();
8127 }
8128 
8129 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8130   ABIArgInfo &RetInfo = FI.getReturnInfo();
8131   if (!getCXXABI().classifyReturnType(FI))
8132     RetInfo = classifyReturnType(FI.getReturnType());
8133 
8134   // Check if a pointer to an aggregate is passed as a hidden argument.
8135   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8136 
8137   for (auto &I : FI.arguments())
8138     I.info = classifyArgumentType(I.type, Offset);
8139 }
8140 
8141 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8142                                QualType OrigTy) const {
8143   QualType Ty = OrigTy;
8144 
8145   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8146   // Pointers are also promoted in the same way but this only matters for N32.
8147   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8148   unsigned PtrWidth = getTarget().getPointerWidth(0);
8149   bool DidPromote = false;
8150   if ((Ty->isIntegerType() &&
8151           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8152       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8153     DidPromote = true;
8154     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8155                                             Ty->isSignedIntegerType());
8156   }
8157 
8158   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8159 
8160   // The alignment of things in the argument area is never larger than
8161   // StackAlignInBytes.
8162   TyInfo.Align =
8163     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8164 
8165   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8166   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8167 
8168   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8169                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8170 
8171 
8172   // If there was a promotion, "unpromote" into a temporary.
8173   // TODO: can we just use a pointer into a subset of the original slot?
8174   if (DidPromote) {
8175     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8176     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8177 
8178     // Truncate down to the right width.
8179     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8180                                                  : CGF.IntPtrTy);
8181     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8182     if (OrigTy->isPointerType())
8183       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8184 
8185     CGF.Builder.CreateStore(V, Temp);
8186     Addr = Temp;
8187   }
8188 
8189   return Addr;
8190 }
8191 
8192 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8193   int TySize = getContext().getTypeSize(Ty);
8194 
8195   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8196   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8197     return ABIArgInfo::getSignExtend(Ty);
8198 
8199   return ABIArgInfo::getExtend(Ty);
8200 }
8201 
8202 bool
8203 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8204                                                llvm::Value *Address) const {
8205   // This information comes from gcc's implementation, which seems to
8206   // as canonical as it gets.
8207 
8208   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8209   // are aliased to pairs of single-precision FP registers.
8210   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8211 
8212   // 0-31 are the general purpose registers, $0 - $31.
8213   // 32-63 are the floating-point registers, $f0 - $f31.
8214   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8215   // 66 is the (notional, I think) register for signal-handler return.
8216   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8217 
8218   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8219   // They are one bit wide and ignored here.
8220 
8221   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8222   // (coprocessor 1 is the FP unit)
8223   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8224   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8225   // 176-181 are the DSP accumulator registers.
8226   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8227   return false;
8228 }
8229 
8230 //===----------------------------------------------------------------------===//
8231 // M68k ABI Implementation
8232 //===----------------------------------------------------------------------===//
8233 
8234 namespace {
8235 
8236 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8237 public:
8238   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8239       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8240   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8241                            CodeGen::CodeGenModule &M) const override;
8242 };
8243 
8244 } // namespace
8245 
8246 void M68kTargetCodeGenInfo::setTargetAttributes(
8247     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8248   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8249     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8250       // Handle 'interrupt' attribute:
8251       llvm::Function *F = cast<llvm::Function>(GV);
8252 
8253       // Step 1: Set ISR calling convention.
8254       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8255 
8256       // Step 2: Add attributes goodness.
8257       F->addFnAttr(llvm::Attribute::NoInline);
8258 
8259       // Step 3: Emit ISR vector alias.
8260       unsigned Num = attr->getNumber() / 2;
8261       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8262                                 "__isr_" + Twine(Num), F);
8263     }
8264   }
8265 }
8266 
8267 //===----------------------------------------------------------------------===//
8268 // AVR ABI Implementation. Documented at
8269 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8270 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8271 //===----------------------------------------------------------------------===//
8272 
8273 namespace {
8274 class AVRABIInfo : public DefaultABIInfo {
8275 public:
8276   AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8277 
8278   ABIArgInfo classifyReturnType(QualType Ty) const {
8279     // A return struct with size less than or equal to 8 bytes is returned
8280     // directly via registers R18-R25.
8281     if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
8282       return ABIArgInfo::getDirect();
8283     else
8284       return DefaultABIInfo::classifyReturnType(Ty);
8285   }
8286 
8287   // Just copy the original implementation of DefaultABIInfo::computeInfo(),
8288   // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
8289   void computeInfo(CGFunctionInfo &FI) const override {
8290     if (!getCXXABI().classifyReturnType(FI))
8291       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8292     for (auto &I : FI.arguments())
8293       I.info = classifyArgumentType(I.type);
8294   }
8295 };
8296 
8297 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8298 public:
8299   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8300       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
8301 
8302   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8303                                   const VarDecl *D) const override {
8304     // Check if global/static variable is defined in address space
8305     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8306     // but not constant.
8307     if (D) {
8308       LangAS AS = D->getType().getAddressSpace();
8309       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8310           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8311         CGM.getDiags().Report(D->getLocation(),
8312                               diag::err_verify_nonconst_addrspace)
8313             << "__flash*";
8314     }
8315     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8316   }
8317 
8318   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8319                            CodeGen::CodeGenModule &CGM) const override {
8320     if (GV->isDeclaration())
8321       return;
8322     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8323     if (!FD) return;
8324     auto *Fn = cast<llvm::Function>(GV);
8325 
8326     if (FD->getAttr<AVRInterruptAttr>())
8327       Fn->addFnAttr("interrupt");
8328 
8329     if (FD->getAttr<AVRSignalAttr>())
8330       Fn->addFnAttr("signal");
8331   }
8332 };
8333 }
8334 
8335 //===----------------------------------------------------------------------===//
8336 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8337 // Currently subclassed only to implement custom OpenCL C function attribute
8338 // handling.
8339 //===----------------------------------------------------------------------===//
8340 
8341 namespace {
8342 
8343 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8344 public:
8345   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8346     : DefaultTargetCodeGenInfo(CGT) {}
8347 
8348   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8349                            CodeGen::CodeGenModule &M) const override;
8350 };
8351 
8352 void TCETargetCodeGenInfo::setTargetAttributes(
8353     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8354   if (GV->isDeclaration())
8355     return;
8356   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8357   if (!FD) return;
8358 
8359   llvm::Function *F = cast<llvm::Function>(GV);
8360 
8361   if (M.getLangOpts().OpenCL) {
8362     if (FD->hasAttr<OpenCLKernelAttr>()) {
8363       // OpenCL C Kernel functions are not subject to inlining
8364       F->addFnAttr(llvm::Attribute::NoInline);
8365       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8366       if (Attr) {
8367         // Convert the reqd_work_group_size() attributes to metadata.
8368         llvm::LLVMContext &Context = F->getContext();
8369         llvm::NamedMDNode *OpenCLMetadata =
8370             M.getModule().getOrInsertNamedMetadata(
8371                 "opencl.kernel_wg_size_info");
8372 
8373         SmallVector<llvm::Metadata *, 5> Operands;
8374         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8375 
8376         Operands.push_back(
8377             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8378                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8379         Operands.push_back(
8380             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8381                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8382         Operands.push_back(
8383             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8384                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8385 
8386         // Add a boolean constant operand for "required" (true) or "hint"
8387         // (false) for implementing the work_group_size_hint attr later.
8388         // Currently always true as the hint is not yet implemented.
8389         Operands.push_back(
8390             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8391         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8392       }
8393     }
8394   }
8395 }
8396 
8397 }
8398 
8399 //===----------------------------------------------------------------------===//
8400 // Hexagon ABI Implementation
8401 //===----------------------------------------------------------------------===//
8402 
8403 namespace {
8404 
8405 class HexagonABIInfo : public DefaultABIInfo {
8406 public:
8407   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8408 
8409 private:
8410   ABIArgInfo classifyReturnType(QualType RetTy) const;
8411   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8412   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8413 
8414   void computeInfo(CGFunctionInfo &FI) const override;
8415 
8416   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8417                     QualType Ty) const override;
8418   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8419                               QualType Ty) const;
8420   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8421                               QualType Ty) const;
8422   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8423                                    QualType Ty) const;
8424 };
8425 
8426 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8427 public:
8428   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8429       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8430 
8431   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8432     return 29;
8433   }
8434 
8435   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8436                            CodeGen::CodeGenModule &GCM) const override {
8437     if (GV->isDeclaration())
8438       return;
8439     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8440     if (!FD)
8441       return;
8442   }
8443 };
8444 
8445 } // namespace
8446 
8447 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8448   unsigned RegsLeft = 6;
8449   if (!getCXXABI().classifyReturnType(FI))
8450     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8451   for (auto &I : FI.arguments())
8452     I.info = classifyArgumentType(I.type, &RegsLeft);
8453 }
8454 
8455 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8456   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8457                        " through registers");
8458 
8459   if (*RegsLeft == 0)
8460     return false;
8461 
8462   if (Size <= 32) {
8463     (*RegsLeft)--;
8464     return true;
8465   }
8466 
8467   if (2 <= (*RegsLeft & (~1U))) {
8468     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8469     return true;
8470   }
8471 
8472   // Next available register was r5 but candidate was greater than 32-bits so it
8473   // has to go on the stack. However we still consume r5
8474   if (*RegsLeft == 1)
8475     *RegsLeft = 0;
8476 
8477   return false;
8478 }
8479 
8480 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8481                                                 unsigned *RegsLeft) const {
8482   if (!isAggregateTypeForABI(Ty)) {
8483     // Treat an enum type as its underlying type.
8484     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8485       Ty = EnumTy->getDecl()->getIntegerType();
8486 
8487     uint64_t Size = getContext().getTypeSize(Ty);
8488     if (Size <= 64)
8489       HexagonAdjustRegsLeft(Size, RegsLeft);
8490 
8491     if (Size > 64 && Ty->isBitIntType())
8492       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8493 
8494     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8495                                              : ABIArgInfo::getDirect();
8496   }
8497 
8498   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8499     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8500 
8501   // Ignore empty records.
8502   if (isEmptyRecord(getContext(), Ty, true))
8503     return ABIArgInfo::getIgnore();
8504 
8505   uint64_t Size = getContext().getTypeSize(Ty);
8506   unsigned Align = getContext().getTypeAlign(Ty);
8507 
8508   if (Size > 64)
8509     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8510 
8511   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8512     Align = Size <= 32 ? 32 : 64;
8513   if (Size <= Align) {
8514     // Pass in the smallest viable integer type.
8515     if (!llvm::isPowerOf2_64(Size))
8516       Size = llvm::NextPowerOf2(Size);
8517     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8518   }
8519   return DefaultABIInfo::classifyArgumentType(Ty);
8520 }
8521 
8522 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8523   if (RetTy->isVoidType())
8524     return ABIArgInfo::getIgnore();
8525 
8526   const TargetInfo &T = CGT.getTarget();
8527   uint64_t Size = getContext().getTypeSize(RetTy);
8528 
8529   if (RetTy->getAs<VectorType>()) {
8530     // HVX vectors are returned in vector registers or register pairs.
8531     if (T.hasFeature("hvx")) {
8532       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8533       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8534       if (Size == VecSize || Size == 2*VecSize)
8535         return ABIArgInfo::getDirectInReg();
8536     }
8537     // Large vector types should be returned via memory.
8538     if (Size > 64)
8539       return getNaturalAlignIndirect(RetTy);
8540   }
8541 
8542   if (!isAggregateTypeForABI(RetTy)) {
8543     // Treat an enum type as its underlying type.
8544     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8545       RetTy = EnumTy->getDecl()->getIntegerType();
8546 
8547     if (Size > 64 && RetTy->isBitIntType())
8548       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8549 
8550     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8551                                                 : ABIArgInfo::getDirect();
8552   }
8553 
8554   if (isEmptyRecord(getContext(), RetTy, true))
8555     return ABIArgInfo::getIgnore();
8556 
8557   // Aggregates <= 8 bytes are returned in registers, other aggregates
8558   // are returned indirectly.
8559   if (Size <= 64) {
8560     // Return in the smallest viable integer type.
8561     if (!llvm::isPowerOf2_64(Size))
8562       Size = llvm::NextPowerOf2(Size);
8563     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8564   }
8565   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8566 }
8567 
8568 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8569                                             Address VAListAddr,
8570                                             QualType Ty) const {
8571   // Load the overflow area pointer.
8572   Address __overflow_area_pointer_p =
8573       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8574   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8575       __overflow_area_pointer_p, "__overflow_area_pointer");
8576 
8577   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8578   if (Align > 4) {
8579     // Alignment should be a power of 2.
8580     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8581 
8582     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8583     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8584 
8585     // Add offset to the current pointer to access the argument.
8586     __overflow_area_pointer =
8587         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8588     llvm::Value *AsInt =
8589         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8590 
8591     // Create a mask which should be "AND"ed
8592     // with (overflow_arg_area + align - 1)
8593     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8594     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8595         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8596         "__overflow_area_pointer.align");
8597   }
8598 
8599   // Get the type of the argument from memory and bitcast
8600   // overflow area pointer to the argument type.
8601   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8602   Address AddrTyped = CGF.Builder.CreateBitCast(
8603       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8604       llvm::PointerType::getUnqual(PTy));
8605 
8606   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8607   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8608 
8609   __overflow_area_pointer = CGF.Builder.CreateGEP(
8610       CGF.Int8Ty, __overflow_area_pointer,
8611       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8612       "__overflow_area_pointer.next");
8613   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8614 
8615   return AddrTyped;
8616 }
8617 
8618 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8619                                             Address VAListAddr,
8620                                             QualType Ty) const {
8621   // FIXME: Need to handle alignment
8622   llvm::Type *BP = CGF.Int8PtrTy;
8623   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8624   CGBuilderTy &Builder = CGF.Builder;
8625   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8626   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8627   // Handle address alignment for type alignment > 32 bits
8628   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8629   if (TyAlign > 4) {
8630     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8631     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8632     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8633     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8634     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8635   }
8636   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8637   Address AddrTyped = Builder.CreateBitCast(
8638       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8639 
8640   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8641   llvm::Value *NextAddr = Builder.CreateGEP(
8642       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8643   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8644 
8645   return AddrTyped;
8646 }
8647 
8648 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8649                                                  Address VAListAddr,
8650                                                  QualType Ty) const {
8651   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8652 
8653   if (ArgSize > 8)
8654     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8655 
8656   // Here we have check if the argument is in register area or
8657   // in overflow area.
8658   // If the saved register area pointer + argsize rounded up to alignment >
8659   // saved register area end pointer, argument is in overflow area.
8660   unsigned RegsLeft = 6;
8661   Ty = CGF.getContext().getCanonicalType(Ty);
8662   (void)classifyArgumentType(Ty, &RegsLeft);
8663 
8664   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8665   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8666   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8667   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8668 
8669   // Get rounded size of the argument.GCC does not allow vararg of
8670   // size < 4 bytes. We follow the same logic here.
8671   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8672   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8673 
8674   // Argument may be in saved register area
8675   CGF.EmitBlock(MaybeRegBlock);
8676 
8677   // Load the current saved register area pointer.
8678   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8679       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8680   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8681       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8682 
8683   // Load the saved register area end pointer.
8684   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8685       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8686   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8687       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8688 
8689   // If the size of argument is > 4 bytes, check if the stack
8690   // location is aligned to 8 bytes
8691   if (ArgAlign > 4) {
8692 
8693     llvm::Value *__current_saved_reg_area_pointer_int =
8694         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8695                                    CGF.Int32Ty);
8696 
8697     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8698         __current_saved_reg_area_pointer_int,
8699         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8700         "align_current_saved_reg_area_pointer");
8701 
8702     __current_saved_reg_area_pointer_int =
8703         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8704                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8705                               "align_current_saved_reg_area_pointer");
8706 
8707     __current_saved_reg_area_pointer =
8708         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8709                                    __current_saved_reg_area_pointer->getType(),
8710                                    "align_current_saved_reg_area_pointer");
8711   }
8712 
8713   llvm::Value *__new_saved_reg_area_pointer =
8714       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8715                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8716                             "__new_saved_reg_area_pointer");
8717 
8718   llvm::Value *UsingStack = nullptr;
8719   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8720                                          __saved_reg_area_end_pointer);
8721 
8722   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8723 
8724   // Argument in saved register area
8725   // Implement the block where argument is in register saved area
8726   CGF.EmitBlock(InRegBlock);
8727 
8728   llvm::Type *PTy = CGF.ConvertType(Ty);
8729   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8730       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8731 
8732   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8733                           __current_saved_reg_area_pointer_p);
8734 
8735   CGF.EmitBranch(ContBlock);
8736 
8737   // Argument in overflow area
8738   // Implement the block where the argument is in overflow area.
8739   CGF.EmitBlock(OnStackBlock);
8740 
8741   // Load the overflow area pointer
8742   Address __overflow_area_pointer_p =
8743       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8744   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8745       __overflow_area_pointer_p, "__overflow_area_pointer");
8746 
8747   // Align the overflow area pointer according to the alignment of the argument
8748   if (ArgAlign > 4) {
8749     llvm::Value *__overflow_area_pointer_int =
8750         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8751 
8752     __overflow_area_pointer_int =
8753         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8754                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8755                               "align_overflow_area_pointer");
8756 
8757     __overflow_area_pointer_int =
8758         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8759                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8760                               "align_overflow_area_pointer");
8761 
8762     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8763         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8764         "align_overflow_area_pointer");
8765   }
8766 
8767   // Get the pointer for next argument in overflow area and store it
8768   // to overflow area pointer.
8769   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8770       CGF.Int8Ty, __overflow_area_pointer,
8771       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8772       "__overflow_area_pointer.next");
8773 
8774   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8775                           __overflow_area_pointer_p);
8776 
8777   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8778                           __current_saved_reg_area_pointer_p);
8779 
8780   // Bitcast the overflow area pointer to the type of argument.
8781   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8782   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8783       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8784 
8785   CGF.EmitBranch(ContBlock);
8786 
8787   // Get the correct pointer to load the variable argument
8788   // Implement the ContBlock
8789   CGF.EmitBlock(ContBlock);
8790 
8791   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8792   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8793   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8794   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8795 
8796   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8797 }
8798 
8799 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8800                                   QualType Ty) const {
8801 
8802   if (getTarget().getTriple().isMusl())
8803     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8804 
8805   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8806 }
8807 
8808 //===----------------------------------------------------------------------===//
8809 // Lanai ABI Implementation
8810 //===----------------------------------------------------------------------===//
8811 
8812 namespace {
8813 class LanaiABIInfo : public DefaultABIInfo {
8814 public:
8815   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8816 
8817   bool shouldUseInReg(QualType Ty, CCState &State) const;
8818 
8819   void computeInfo(CGFunctionInfo &FI) const override {
8820     CCState State(FI);
8821     // Lanai uses 4 registers to pass arguments unless the function has the
8822     // regparm attribute set.
8823     if (FI.getHasRegParm()) {
8824       State.FreeRegs = FI.getRegParm();
8825     } else {
8826       State.FreeRegs = 4;
8827     }
8828 
8829     if (!getCXXABI().classifyReturnType(FI))
8830       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8831     for (auto &I : FI.arguments())
8832       I.info = classifyArgumentType(I.type, State);
8833   }
8834 
8835   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8836   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8837 };
8838 } // end anonymous namespace
8839 
8840 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8841   unsigned Size = getContext().getTypeSize(Ty);
8842   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8843 
8844   if (SizeInRegs == 0)
8845     return false;
8846 
8847   if (SizeInRegs > State.FreeRegs) {
8848     State.FreeRegs = 0;
8849     return false;
8850   }
8851 
8852   State.FreeRegs -= SizeInRegs;
8853 
8854   return true;
8855 }
8856 
8857 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8858                                            CCState &State) const {
8859   if (!ByVal) {
8860     if (State.FreeRegs) {
8861       --State.FreeRegs; // Non-byval indirects just use one pointer.
8862       return getNaturalAlignIndirectInReg(Ty);
8863     }
8864     return getNaturalAlignIndirect(Ty, false);
8865   }
8866 
8867   // Compute the byval alignment.
8868   const unsigned MinABIStackAlignInBytes = 4;
8869   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8870   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8871                                  /*Realign=*/TypeAlign >
8872                                      MinABIStackAlignInBytes);
8873 }
8874 
8875 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8876                                               CCState &State) const {
8877   // Check with the C++ ABI first.
8878   const RecordType *RT = Ty->getAs<RecordType>();
8879   if (RT) {
8880     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8881     if (RAA == CGCXXABI::RAA_Indirect) {
8882       return getIndirectResult(Ty, /*ByVal=*/false, State);
8883     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8884       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8885     }
8886   }
8887 
8888   if (isAggregateTypeForABI(Ty)) {
8889     // Structures with flexible arrays are always indirect.
8890     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8891       return getIndirectResult(Ty, /*ByVal=*/true, State);
8892 
8893     // Ignore empty structs/unions.
8894     if (isEmptyRecord(getContext(), Ty, true))
8895       return ABIArgInfo::getIgnore();
8896 
8897     llvm::LLVMContext &LLVMContext = getVMContext();
8898     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8899     if (SizeInRegs <= State.FreeRegs) {
8900       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8901       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8902       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8903       State.FreeRegs -= SizeInRegs;
8904       return ABIArgInfo::getDirectInReg(Result);
8905     } else {
8906       State.FreeRegs = 0;
8907     }
8908     return getIndirectResult(Ty, true, State);
8909   }
8910 
8911   // Treat an enum type as its underlying type.
8912   if (const auto *EnumTy = Ty->getAs<EnumType>())
8913     Ty = EnumTy->getDecl()->getIntegerType();
8914 
8915   bool InReg = shouldUseInReg(Ty, State);
8916 
8917   // Don't pass >64 bit integers in registers.
8918   if (const auto *EIT = Ty->getAs<BitIntType>())
8919     if (EIT->getNumBits() > 64)
8920       return getIndirectResult(Ty, /*ByVal=*/true, State);
8921 
8922   if (isPromotableIntegerTypeForABI(Ty)) {
8923     if (InReg)
8924       return ABIArgInfo::getDirectInReg();
8925     return ABIArgInfo::getExtend(Ty);
8926   }
8927   if (InReg)
8928     return ABIArgInfo::getDirectInReg();
8929   return ABIArgInfo::getDirect();
8930 }
8931 
8932 namespace {
8933 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8934 public:
8935   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8936       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8937 };
8938 }
8939 
8940 //===----------------------------------------------------------------------===//
8941 // AMDGPU ABI Implementation
8942 //===----------------------------------------------------------------------===//
8943 
8944 namespace {
8945 
8946 class AMDGPUABIInfo final : public DefaultABIInfo {
8947 private:
8948   static const unsigned MaxNumRegsForArgsRet = 16;
8949 
8950   unsigned numRegsForType(QualType Ty) const;
8951 
8952   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8953   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8954                                          uint64_t Members) const override;
8955 
8956   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8957   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8958                                        unsigned ToAS) const {
8959     // Single value types.
8960     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8961     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8962       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8963     return Ty;
8964   }
8965 
8966 public:
8967   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8968     DefaultABIInfo(CGT) {}
8969 
8970   ABIArgInfo classifyReturnType(QualType RetTy) const;
8971   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8972   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8973 
8974   void computeInfo(CGFunctionInfo &FI) const override;
8975   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8976                     QualType Ty) const override;
8977 };
8978 
8979 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8980   return true;
8981 }
8982 
8983 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8984   const Type *Base, uint64_t Members) const {
8985   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8986 
8987   // Homogeneous Aggregates may occupy at most 16 registers.
8988   return Members * NumRegs <= MaxNumRegsForArgsRet;
8989 }
8990 
8991 /// Estimate number of registers the type will use when passed in registers.
8992 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8993   unsigned NumRegs = 0;
8994 
8995   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8996     // Compute from the number of elements. The reported size is based on the
8997     // in-memory size, which includes the padding 4th element for 3-vectors.
8998     QualType EltTy = VT->getElementType();
8999     unsigned EltSize = getContext().getTypeSize(EltTy);
9000 
9001     // 16-bit element vectors should be passed as packed.
9002     if (EltSize == 16)
9003       return (VT->getNumElements() + 1) / 2;
9004 
9005     unsigned EltNumRegs = (EltSize + 31) / 32;
9006     return EltNumRegs * VT->getNumElements();
9007   }
9008 
9009   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9010     const RecordDecl *RD = RT->getDecl();
9011     assert(!RD->hasFlexibleArrayMember());
9012 
9013     for (const FieldDecl *Field : RD->fields()) {
9014       QualType FieldTy = Field->getType();
9015       NumRegs += numRegsForType(FieldTy);
9016     }
9017 
9018     return NumRegs;
9019   }
9020 
9021   return (getContext().getTypeSize(Ty) + 31) / 32;
9022 }
9023 
9024 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9025   llvm::CallingConv::ID CC = FI.getCallingConvention();
9026 
9027   if (!getCXXABI().classifyReturnType(FI))
9028     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9029 
9030   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9031   for (auto &Arg : FI.arguments()) {
9032     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9033       Arg.info = classifyKernelArgumentType(Arg.type);
9034     } else {
9035       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9036     }
9037   }
9038 }
9039 
9040 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9041                                  QualType Ty) const {
9042   llvm_unreachable("AMDGPU does not support varargs");
9043 }
9044 
9045 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9046   if (isAggregateTypeForABI(RetTy)) {
9047     // Records with non-trivial destructors/copy-constructors should not be
9048     // returned by value.
9049     if (!getRecordArgABI(RetTy, getCXXABI())) {
9050       // Ignore empty structs/unions.
9051       if (isEmptyRecord(getContext(), RetTy, true))
9052         return ABIArgInfo::getIgnore();
9053 
9054       // Lower single-element structs to just return a regular value.
9055       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9056         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9057 
9058       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9059         const RecordDecl *RD = RT->getDecl();
9060         if (RD->hasFlexibleArrayMember())
9061           return DefaultABIInfo::classifyReturnType(RetTy);
9062       }
9063 
9064       // Pack aggregates <= 4 bytes into single VGPR or pair.
9065       uint64_t Size = getContext().getTypeSize(RetTy);
9066       if (Size <= 16)
9067         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9068 
9069       if (Size <= 32)
9070         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9071 
9072       if (Size <= 64) {
9073         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9074         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9075       }
9076 
9077       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9078         return ABIArgInfo::getDirect();
9079     }
9080   }
9081 
9082   // Otherwise just do the default thing.
9083   return DefaultABIInfo::classifyReturnType(RetTy);
9084 }
9085 
9086 /// For kernels all parameters are really passed in a special buffer. It doesn't
9087 /// make sense to pass anything byval, so everything must be direct.
9088 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9089   Ty = useFirstFieldIfTransparentUnion(Ty);
9090 
9091   // TODO: Can we omit empty structs?
9092 
9093   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9094     Ty = QualType(SeltTy, 0);
9095 
9096   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9097   llvm::Type *LTy = OrigLTy;
9098   if (getContext().getLangOpts().HIP) {
9099     LTy = coerceKernelArgumentType(
9100         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9101         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9102   }
9103 
9104   // FIXME: Should also use this for OpenCL, but it requires addressing the
9105   // problem of kernels being called.
9106   //
9107   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9108   // to global address space when using byref. This would require implementing a
9109   // new kind of coercion of the in-memory type when for indirect arguments.
9110   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9111       isAggregateTypeForABI(Ty)) {
9112     return ABIArgInfo::getIndirectAliased(
9113         getContext().getTypeAlignInChars(Ty),
9114         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9115         false /*Realign*/, nullptr /*Padding*/);
9116   }
9117 
9118   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9119   // individual elements, which confuses the Clover OpenCL backend; therefore we
9120   // have to set it to false here. Other args of getDirect() are just defaults.
9121   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9122 }
9123 
9124 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9125                                                unsigned &NumRegsLeft) const {
9126   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9127 
9128   Ty = useFirstFieldIfTransparentUnion(Ty);
9129 
9130   if (isAggregateTypeForABI(Ty)) {
9131     // Records with non-trivial destructors/copy-constructors should not be
9132     // passed by value.
9133     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9134       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9135 
9136     // Ignore empty structs/unions.
9137     if (isEmptyRecord(getContext(), Ty, true))
9138       return ABIArgInfo::getIgnore();
9139 
9140     // Lower single-element structs to just pass a regular value. TODO: We
9141     // could do reasonable-size multiple-element structs too, using getExpand(),
9142     // though watch out for things like bitfields.
9143     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9144       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9145 
9146     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9147       const RecordDecl *RD = RT->getDecl();
9148       if (RD->hasFlexibleArrayMember())
9149         return DefaultABIInfo::classifyArgumentType(Ty);
9150     }
9151 
9152     // Pack aggregates <= 8 bytes into single VGPR or pair.
9153     uint64_t Size = getContext().getTypeSize(Ty);
9154     if (Size <= 64) {
9155       unsigned NumRegs = (Size + 31) / 32;
9156       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9157 
9158       if (Size <= 16)
9159         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9160 
9161       if (Size <= 32)
9162         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9163 
9164       // XXX: Should this be i64 instead, and should the limit increase?
9165       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9166       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9167     }
9168 
9169     if (NumRegsLeft > 0) {
9170       unsigned NumRegs = numRegsForType(Ty);
9171       if (NumRegsLeft >= NumRegs) {
9172         NumRegsLeft -= NumRegs;
9173         return ABIArgInfo::getDirect();
9174       }
9175     }
9176   }
9177 
9178   // Otherwise just do the default thing.
9179   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9180   if (!ArgInfo.isIndirect()) {
9181     unsigned NumRegs = numRegsForType(Ty);
9182     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9183   }
9184 
9185   return ArgInfo;
9186 }
9187 
9188 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9189 public:
9190   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9191       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9192 
9193   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9194                                  CodeGenModule &CGM) const;
9195 
9196   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9197                            CodeGen::CodeGenModule &M) const override;
9198   unsigned getOpenCLKernelCallingConv() const override;
9199 
9200   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9201       llvm::PointerType *T, QualType QT) const override;
9202 
9203   LangAS getASTAllocaAddressSpace() const override {
9204     return getLangASFromTargetAS(
9205         getABIInfo().getDataLayout().getAllocaAddrSpace());
9206   }
9207   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9208                                   const VarDecl *D) const override;
9209   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9210                                          SyncScope Scope,
9211                                          llvm::AtomicOrdering Ordering,
9212                                          llvm::LLVMContext &Ctx) const override;
9213   llvm::Function *
9214   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9215                             llvm::Function *BlockInvokeFunc,
9216                             llvm::Value *BlockLiteral) const override;
9217   bool shouldEmitStaticExternCAliases() const override;
9218   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9219 };
9220 }
9221 
9222 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9223                                               llvm::GlobalValue *GV) {
9224   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9225     return false;
9226 
9227   return D->hasAttr<OpenCLKernelAttr>() ||
9228          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9229          (isa<VarDecl>(D) &&
9230           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9231            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9232            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9233 }
9234 
9235 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9236     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9237   const auto *ReqdWGS =
9238       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9239   const bool IsOpenCLKernel =
9240       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9241   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9242 
9243   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9244   if (ReqdWGS || FlatWGS) {
9245     unsigned Min = 0;
9246     unsigned Max = 0;
9247     if (FlatWGS) {
9248       Min = FlatWGS->getMin()
9249                 ->EvaluateKnownConstInt(M.getContext())
9250                 .getExtValue();
9251       Max = FlatWGS->getMax()
9252                 ->EvaluateKnownConstInt(M.getContext())
9253                 .getExtValue();
9254     }
9255     if (ReqdWGS && Min == 0 && Max == 0)
9256       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9257 
9258     if (Min != 0) {
9259       assert(Min <= Max && "Min must be less than or equal Max");
9260 
9261       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9262       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9263     } else
9264       assert(Max == 0 && "Max must be zero");
9265   } else if (IsOpenCLKernel || IsHIPKernel) {
9266     // By default, restrict the maximum size to a value specified by
9267     // --gpu-max-threads-per-block=n or its default value for HIP.
9268     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9269     const unsigned DefaultMaxWorkGroupSize =
9270         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9271                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9272     std::string AttrVal =
9273         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9274     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9275   }
9276 
9277   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9278     unsigned Min =
9279         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9280     unsigned Max = Attr->getMax() ? Attr->getMax()
9281                                         ->EvaluateKnownConstInt(M.getContext())
9282                                         .getExtValue()
9283                                   : 0;
9284 
9285     if (Min != 0) {
9286       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9287 
9288       std::string AttrVal = llvm::utostr(Min);
9289       if (Max != 0)
9290         AttrVal = AttrVal + "," + llvm::utostr(Max);
9291       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9292     } else
9293       assert(Max == 0 && "Max must be zero");
9294   }
9295 
9296   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9297     unsigned NumSGPR = Attr->getNumSGPR();
9298 
9299     if (NumSGPR != 0)
9300       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9301   }
9302 
9303   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9304     uint32_t NumVGPR = Attr->getNumVGPR();
9305 
9306     if (NumVGPR != 0)
9307       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9308   }
9309 }
9310 
9311 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9312     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9313   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9314     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9315     GV->setDSOLocal(true);
9316   }
9317 
9318   if (GV->isDeclaration())
9319     return;
9320 
9321   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9322   if (!F)
9323     return;
9324 
9325   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9326   if (FD)
9327     setFunctionDeclAttributes(FD, F, M);
9328 
9329   const bool IsHIPKernel =
9330       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9331 
9332   if (IsHIPKernel)
9333     F->addFnAttr("uniform-work-group-size", "true");
9334 
9335   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9336     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9337 
9338   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9339     F->addFnAttr("amdgpu-ieee", "false");
9340 }
9341 
9342 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9343   return llvm::CallingConv::AMDGPU_KERNEL;
9344 }
9345 
9346 // Currently LLVM assumes null pointers always have value 0,
9347 // which results in incorrectly transformed IR. Therefore, instead of
9348 // emitting null pointers in private and local address spaces, a null
9349 // pointer in generic address space is emitted which is casted to a
9350 // pointer in local or private address space.
9351 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9352     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9353     QualType QT) const {
9354   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9355     return llvm::ConstantPointerNull::get(PT);
9356 
9357   auto &Ctx = CGM.getContext();
9358   auto NPT = llvm::PointerType::getWithSamePointeeType(
9359       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9360   return llvm::ConstantExpr::getAddrSpaceCast(
9361       llvm::ConstantPointerNull::get(NPT), PT);
9362 }
9363 
9364 LangAS
9365 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9366                                                   const VarDecl *D) const {
9367   assert(!CGM.getLangOpts().OpenCL &&
9368          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9369          "Address space agnostic languages only");
9370   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9371       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9372   if (!D)
9373     return DefaultGlobalAS;
9374 
9375   LangAS AddrSpace = D->getType().getAddressSpace();
9376   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9377   if (AddrSpace != LangAS::Default)
9378     return AddrSpace;
9379 
9380   // Only promote to address space 4 if VarDecl has constant initialization.
9381   if (CGM.isTypeConstant(D->getType(), false) &&
9382       D->hasConstantInitialization()) {
9383     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9384       return ConstAS.getValue();
9385   }
9386   return DefaultGlobalAS;
9387 }
9388 
9389 llvm::SyncScope::ID
9390 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9391                                             SyncScope Scope,
9392                                             llvm::AtomicOrdering Ordering,
9393                                             llvm::LLVMContext &Ctx) const {
9394   std::string Name;
9395   switch (Scope) {
9396   case SyncScope::HIPSingleThread:
9397     Name = "singlethread";
9398     break;
9399   case SyncScope::HIPWavefront:
9400   case SyncScope::OpenCLSubGroup:
9401     Name = "wavefront";
9402     break;
9403   case SyncScope::HIPWorkgroup:
9404   case SyncScope::OpenCLWorkGroup:
9405     Name = "workgroup";
9406     break;
9407   case SyncScope::HIPAgent:
9408   case SyncScope::OpenCLDevice:
9409     Name = "agent";
9410     break;
9411   case SyncScope::HIPSystem:
9412   case SyncScope::OpenCLAllSVMDevices:
9413     Name = "";
9414     break;
9415   }
9416 
9417   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9418     if (!Name.empty())
9419       Name = Twine(Twine(Name) + Twine("-")).str();
9420 
9421     Name = Twine(Twine(Name) + Twine("one-as")).str();
9422   }
9423 
9424   return Ctx.getOrInsertSyncScopeID(Name);
9425 }
9426 
9427 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9428   return false;
9429 }
9430 
9431 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9432     const FunctionType *&FT) const {
9433   FT = getABIInfo().getContext().adjustFunctionType(
9434       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9435 }
9436 
9437 //===----------------------------------------------------------------------===//
9438 // SPARC v8 ABI Implementation.
9439 // Based on the SPARC Compliance Definition version 2.4.1.
9440 //
9441 // Ensures that complex values are passed in registers.
9442 //
9443 namespace {
9444 class SparcV8ABIInfo : public DefaultABIInfo {
9445 public:
9446   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9447 
9448 private:
9449   ABIArgInfo classifyReturnType(QualType RetTy) const;
9450   void computeInfo(CGFunctionInfo &FI) const override;
9451 };
9452 } // end anonymous namespace
9453 
9454 
9455 ABIArgInfo
9456 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9457   if (Ty->isAnyComplexType()) {
9458     return ABIArgInfo::getDirect();
9459   }
9460   else {
9461     return DefaultABIInfo::classifyReturnType(Ty);
9462   }
9463 }
9464 
9465 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9466 
9467   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9468   for (auto &Arg : FI.arguments())
9469     Arg.info = classifyArgumentType(Arg.type);
9470 }
9471 
9472 namespace {
9473 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9474 public:
9475   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9476       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9477 
9478   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9479                                    llvm::Value *Address) const override {
9480     int Offset;
9481     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9482       Offset = 12;
9483     else
9484       Offset = 8;
9485     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9486                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9487   }
9488 
9489   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9490                                    llvm::Value *Address) const override {
9491     int Offset;
9492     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9493       Offset = -12;
9494     else
9495       Offset = -8;
9496     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9497                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9498   }
9499 };
9500 } // end anonymous namespace
9501 
9502 //===----------------------------------------------------------------------===//
9503 // SPARC v9 ABI Implementation.
9504 // Based on the SPARC Compliance Definition version 2.4.1.
9505 //
9506 // Function arguments a mapped to a nominal "parameter array" and promoted to
9507 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9508 // the array, structs larger than 16 bytes are passed indirectly.
9509 //
9510 // One case requires special care:
9511 //
9512 //   struct mixed {
9513 //     int i;
9514 //     float f;
9515 //   };
9516 //
9517 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9518 // parameter array, but the int is passed in an integer register, and the float
9519 // is passed in a floating point register. This is represented as two arguments
9520 // with the LLVM IR inreg attribute:
9521 //
9522 //   declare void f(i32 inreg %i, float inreg %f)
9523 //
9524 // The code generator will only allocate 4 bytes from the parameter array for
9525 // the inreg arguments. All other arguments are allocated a multiple of 8
9526 // bytes.
9527 //
9528 namespace {
9529 class SparcV9ABIInfo : public ABIInfo {
9530 public:
9531   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9532 
9533 private:
9534   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9535   void computeInfo(CGFunctionInfo &FI) const override;
9536   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9537                     QualType Ty) const override;
9538 
9539   // Coercion type builder for structs passed in registers. The coercion type
9540   // serves two purposes:
9541   //
9542   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9543   //    in registers.
9544   // 2. Expose aligned floating point elements as first-level elements, so the
9545   //    code generator knows to pass them in floating point registers.
9546   //
9547   // We also compute the InReg flag which indicates that the struct contains
9548   // aligned 32-bit floats.
9549   //
9550   struct CoerceBuilder {
9551     llvm::LLVMContext &Context;
9552     const llvm::DataLayout &DL;
9553     SmallVector<llvm::Type*, 8> Elems;
9554     uint64_t Size;
9555     bool InReg;
9556 
9557     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9558       : Context(c), DL(dl), Size(0), InReg(false) {}
9559 
9560     // Pad Elems with integers until Size is ToSize.
9561     void pad(uint64_t ToSize) {
9562       assert(ToSize >= Size && "Cannot remove elements");
9563       if (ToSize == Size)
9564         return;
9565 
9566       // Finish the current 64-bit word.
9567       uint64_t Aligned = llvm::alignTo(Size, 64);
9568       if (Aligned > Size && Aligned <= ToSize) {
9569         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9570         Size = Aligned;
9571       }
9572 
9573       // Add whole 64-bit words.
9574       while (Size + 64 <= ToSize) {
9575         Elems.push_back(llvm::Type::getInt64Ty(Context));
9576         Size += 64;
9577       }
9578 
9579       // Final in-word padding.
9580       if (Size < ToSize) {
9581         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9582         Size = ToSize;
9583       }
9584     }
9585 
9586     // Add a floating point element at Offset.
9587     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9588       // Unaligned floats are treated as integers.
9589       if (Offset % Bits)
9590         return;
9591       // The InReg flag is only required if there are any floats < 64 bits.
9592       if (Bits < 64)
9593         InReg = true;
9594       pad(Offset);
9595       Elems.push_back(Ty);
9596       Size = Offset + Bits;
9597     }
9598 
9599     // Add a struct type to the coercion type, starting at Offset (in bits).
9600     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9601       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9602       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9603         llvm::Type *ElemTy = StrTy->getElementType(i);
9604         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9605         switch (ElemTy->getTypeID()) {
9606         case llvm::Type::StructTyID:
9607           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9608           break;
9609         case llvm::Type::FloatTyID:
9610           addFloat(ElemOffset, ElemTy, 32);
9611           break;
9612         case llvm::Type::DoubleTyID:
9613           addFloat(ElemOffset, ElemTy, 64);
9614           break;
9615         case llvm::Type::FP128TyID:
9616           addFloat(ElemOffset, ElemTy, 128);
9617           break;
9618         case llvm::Type::PointerTyID:
9619           if (ElemOffset % 64 == 0) {
9620             pad(ElemOffset);
9621             Elems.push_back(ElemTy);
9622             Size += 64;
9623           }
9624           break;
9625         default:
9626           break;
9627         }
9628       }
9629     }
9630 
9631     // Check if Ty is a usable substitute for the coercion type.
9632     bool isUsableType(llvm::StructType *Ty) const {
9633       return llvm::makeArrayRef(Elems) == Ty->elements();
9634     }
9635 
9636     // Get the coercion type as a literal struct type.
9637     llvm::Type *getType() const {
9638       if (Elems.size() == 1)
9639         return Elems.front();
9640       else
9641         return llvm::StructType::get(Context, Elems);
9642     }
9643   };
9644 };
9645 } // end anonymous namespace
9646 
9647 ABIArgInfo
9648 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9649   if (Ty->isVoidType())
9650     return ABIArgInfo::getIgnore();
9651 
9652   uint64_t Size = getContext().getTypeSize(Ty);
9653 
9654   // Anything too big to fit in registers is passed with an explicit indirect
9655   // pointer / sret pointer.
9656   if (Size > SizeLimit)
9657     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9658 
9659   // Treat an enum type as its underlying type.
9660   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9661     Ty = EnumTy->getDecl()->getIntegerType();
9662 
9663   // Integer types smaller than a register are extended.
9664   if (Size < 64 && Ty->isIntegerType())
9665     return ABIArgInfo::getExtend(Ty);
9666 
9667   if (const auto *EIT = Ty->getAs<BitIntType>())
9668     if (EIT->getNumBits() < 64)
9669       return ABIArgInfo::getExtend(Ty);
9670 
9671   // Other non-aggregates go in registers.
9672   if (!isAggregateTypeForABI(Ty))
9673     return ABIArgInfo::getDirect();
9674 
9675   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9676   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9677   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9678     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9679 
9680   // This is a small aggregate type that should be passed in registers.
9681   // Build a coercion type from the LLVM struct type.
9682   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9683   if (!StrTy)
9684     return ABIArgInfo::getDirect();
9685 
9686   CoerceBuilder CB(getVMContext(), getDataLayout());
9687   CB.addStruct(0, StrTy);
9688   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9689 
9690   // Try to use the original type for coercion.
9691   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9692 
9693   if (CB.InReg)
9694     return ABIArgInfo::getDirectInReg(CoerceTy);
9695   else
9696     return ABIArgInfo::getDirect(CoerceTy);
9697 }
9698 
9699 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9700                                   QualType Ty) const {
9701   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9702   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9703   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9704     AI.setCoerceToType(ArgTy);
9705 
9706   CharUnits SlotSize = CharUnits::fromQuantity(8);
9707 
9708   CGBuilderTy &Builder = CGF.Builder;
9709   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9710   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9711 
9712   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9713 
9714   Address ArgAddr = Address::invalid();
9715   CharUnits Stride;
9716   switch (AI.getKind()) {
9717   case ABIArgInfo::Expand:
9718   case ABIArgInfo::CoerceAndExpand:
9719   case ABIArgInfo::InAlloca:
9720     llvm_unreachable("Unsupported ABI kind for va_arg");
9721 
9722   case ABIArgInfo::Extend: {
9723     Stride = SlotSize;
9724     CharUnits Offset = SlotSize - TypeInfo.Width;
9725     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9726     break;
9727   }
9728 
9729   case ABIArgInfo::Direct: {
9730     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9731     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9732     ArgAddr = Addr;
9733     break;
9734   }
9735 
9736   case ABIArgInfo::Indirect:
9737   case ABIArgInfo::IndirectAliased:
9738     Stride = SlotSize;
9739     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9740     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9741                       TypeInfo.Align);
9742     break;
9743 
9744   case ABIArgInfo::Ignore:
9745     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9746   }
9747 
9748   // Update VAList.
9749   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9750   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9751 
9752   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9753 }
9754 
9755 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9756   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9757   for (auto &I : FI.arguments())
9758     I.info = classifyType(I.type, 16 * 8);
9759 }
9760 
9761 namespace {
9762 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9763 public:
9764   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9765       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9766 
9767   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9768     return 14;
9769   }
9770 
9771   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9772                                llvm::Value *Address) const override;
9773 
9774   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9775                                    llvm::Value *Address) const override {
9776     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9777                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9778   }
9779 
9780   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9781                                    llvm::Value *Address) const override {
9782     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9783                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9784   }
9785 };
9786 } // end anonymous namespace
9787 
9788 bool
9789 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9790                                                 llvm::Value *Address) const {
9791   // This is calculated from the LLVM and GCC tables and verified
9792   // against gcc output.  AFAIK all ABIs use the same encoding.
9793 
9794   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9795 
9796   llvm::IntegerType *i8 = CGF.Int8Ty;
9797   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9798   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9799 
9800   // 0-31: the 8-byte general-purpose registers
9801   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9802 
9803   // 32-63: f0-31, the 4-byte floating-point registers
9804   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9805 
9806   //   Y   = 64
9807   //   PSR = 65
9808   //   WIM = 66
9809   //   TBR = 67
9810   //   PC  = 68
9811   //   NPC = 69
9812   //   FSR = 70
9813   //   CSR = 71
9814   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9815 
9816   // 72-87: d0-15, the 8-byte floating-point registers
9817   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9818 
9819   return false;
9820 }
9821 
9822 // ARC ABI implementation.
9823 namespace {
9824 
9825 class ARCABIInfo : public DefaultABIInfo {
9826 public:
9827   using DefaultABIInfo::DefaultABIInfo;
9828 
9829 private:
9830   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9831                     QualType Ty) const override;
9832 
9833   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9834     if (!State.FreeRegs)
9835       return;
9836     if (Info.isIndirect() && Info.getInReg())
9837       State.FreeRegs--;
9838     else if (Info.isDirect() && Info.getInReg()) {
9839       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9840       if (sz < State.FreeRegs)
9841         State.FreeRegs -= sz;
9842       else
9843         State.FreeRegs = 0;
9844     }
9845   }
9846 
9847   void computeInfo(CGFunctionInfo &FI) const override {
9848     CCState State(FI);
9849     // ARC uses 8 registers to pass arguments.
9850     State.FreeRegs = 8;
9851 
9852     if (!getCXXABI().classifyReturnType(FI))
9853       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9854     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9855     for (auto &I : FI.arguments()) {
9856       I.info = classifyArgumentType(I.type, State.FreeRegs);
9857       updateState(I.info, I.type, State);
9858     }
9859   }
9860 
9861   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9862   ABIArgInfo getIndirectByValue(QualType Ty) const;
9863   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9864   ABIArgInfo classifyReturnType(QualType RetTy) const;
9865 };
9866 
9867 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9868 public:
9869   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9870       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9871 };
9872 
9873 
9874 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9875   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9876                        getNaturalAlignIndirect(Ty, false);
9877 }
9878 
9879 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9880   // Compute the byval alignment.
9881   const unsigned MinABIStackAlignInBytes = 4;
9882   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9883   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9884                                  TypeAlign > MinABIStackAlignInBytes);
9885 }
9886 
9887 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9888                               QualType Ty) const {
9889   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9890                           getContext().getTypeInfoInChars(Ty),
9891                           CharUnits::fromQuantity(4), true);
9892 }
9893 
9894 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9895                                             uint8_t FreeRegs) const {
9896   // Handle the generic C++ ABI.
9897   const RecordType *RT = Ty->getAs<RecordType>();
9898   if (RT) {
9899     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9900     if (RAA == CGCXXABI::RAA_Indirect)
9901       return getIndirectByRef(Ty, FreeRegs > 0);
9902 
9903     if (RAA == CGCXXABI::RAA_DirectInMemory)
9904       return getIndirectByValue(Ty);
9905   }
9906 
9907   // Treat an enum type as its underlying type.
9908   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9909     Ty = EnumTy->getDecl()->getIntegerType();
9910 
9911   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9912 
9913   if (isAggregateTypeForABI(Ty)) {
9914     // Structures with flexible arrays are always indirect.
9915     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9916       return getIndirectByValue(Ty);
9917 
9918     // Ignore empty structs/unions.
9919     if (isEmptyRecord(getContext(), Ty, true))
9920       return ABIArgInfo::getIgnore();
9921 
9922     llvm::LLVMContext &LLVMContext = getVMContext();
9923 
9924     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9925     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9926     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9927 
9928     return FreeRegs >= SizeInRegs ?
9929         ABIArgInfo::getDirectInReg(Result) :
9930         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9931   }
9932 
9933   if (const auto *EIT = Ty->getAs<BitIntType>())
9934     if (EIT->getNumBits() > 64)
9935       return getIndirectByValue(Ty);
9936 
9937   return isPromotableIntegerTypeForABI(Ty)
9938              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9939                                        : ABIArgInfo::getExtend(Ty))
9940              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9941                                        : ABIArgInfo::getDirect());
9942 }
9943 
9944 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9945   if (RetTy->isAnyComplexType())
9946     return ABIArgInfo::getDirectInReg();
9947 
9948   // Arguments of size > 4 registers are indirect.
9949   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9950   if (RetSize > 4)
9951     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9952 
9953   return DefaultABIInfo::classifyReturnType(RetTy);
9954 }
9955 
9956 } // End anonymous namespace.
9957 
9958 //===----------------------------------------------------------------------===//
9959 // XCore ABI Implementation
9960 //===----------------------------------------------------------------------===//
9961 
9962 namespace {
9963 
9964 /// A SmallStringEnc instance is used to build up the TypeString by passing
9965 /// it by reference between functions that append to it.
9966 typedef llvm::SmallString<128> SmallStringEnc;
9967 
9968 /// TypeStringCache caches the meta encodings of Types.
9969 ///
9970 /// The reason for caching TypeStrings is two fold:
9971 ///   1. To cache a type's encoding for later uses;
9972 ///   2. As a means to break recursive member type inclusion.
9973 ///
9974 /// A cache Entry can have a Status of:
9975 ///   NonRecursive:   The type encoding is not recursive;
9976 ///   Recursive:      The type encoding is recursive;
9977 ///   Incomplete:     An incomplete TypeString;
9978 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9979 ///                   Recursive type encoding.
9980 ///
9981 /// A NonRecursive entry will have all of its sub-members expanded as fully
9982 /// as possible. Whilst it may contain types which are recursive, the type
9983 /// itself is not recursive and thus its encoding may be safely used whenever
9984 /// the type is encountered.
9985 ///
9986 /// A Recursive entry will have all of its sub-members expanded as fully as
9987 /// possible. The type itself is recursive and it may contain other types which
9988 /// are recursive. The Recursive encoding must not be used during the expansion
9989 /// of a recursive type's recursive branch. For simplicity the code uses
9990 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9991 ///
9992 /// An Incomplete entry is always a RecordType and only encodes its
9993 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9994 /// are placed into the cache during type expansion as a means to identify and
9995 /// handle recursive inclusion of types as sub-members. If there is recursion
9996 /// the entry becomes IncompleteUsed.
9997 ///
9998 /// During the expansion of a RecordType's members:
9999 ///
10000 ///   If the cache contains a NonRecursive encoding for the member type, the
10001 ///   cached encoding is used;
10002 ///
10003 ///   If the cache contains a Recursive encoding for the member type, the
10004 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10005 ///
10006 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10007 ///   cache to break potential recursive inclusion of itself as a sub-member;
10008 ///
10009 ///   Once a member RecordType has been expanded, its temporary incomplete
10010 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10011 ///   it is swapped back in;
10012 ///
10013 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10014 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10015 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10016 ///
10017 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10018 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10019 ///   Else the member is part of a recursive type and thus the recursion has
10020 ///   been exited too soon for the encoding to be correct for the member.
10021 ///
10022 class TypeStringCache {
10023   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10024   struct Entry {
10025     std::string Str;     // The encoded TypeString for the type.
10026     enum Status State;   // Information about the encoding in 'Str'.
10027     std::string Swapped; // A temporary place holder for a Recursive encoding
10028                          // during the expansion of RecordType's members.
10029   };
10030   std::map<const IdentifierInfo *, struct Entry> Map;
10031   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10032   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10033 public:
10034   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10035   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10036   bool removeIncomplete(const IdentifierInfo *ID);
10037   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10038                      bool IsRecursive);
10039   StringRef lookupStr(const IdentifierInfo *ID);
10040 };
10041 
10042 /// TypeString encodings for enum & union fields must be order.
10043 /// FieldEncoding is a helper for this ordering process.
10044 class FieldEncoding {
10045   bool HasName;
10046   std::string Enc;
10047 public:
10048   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10049   StringRef str() { return Enc; }
10050   bool operator<(const FieldEncoding &rhs) const {
10051     if (HasName != rhs.HasName) return HasName;
10052     return Enc < rhs.Enc;
10053   }
10054 };
10055 
10056 class XCoreABIInfo : public DefaultABIInfo {
10057 public:
10058   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10059   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10060                     QualType Ty) const override;
10061 };
10062 
10063 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10064   mutable TypeStringCache TSC;
10065   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10066                     const CodeGen::CodeGenModule &M) const;
10067 
10068 public:
10069   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10070       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10071   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10072                           const llvm::MapVector<GlobalDecl, StringRef>
10073                               &MangledDeclNames) const override;
10074 };
10075 
10076 } // End anonymous namespace.
10077 
10078 // TODO: this implementation is likely now redundant with the default
10079 // EmitVAArg.
10080 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10081                                 QualType Ty) const {
10082   CGBuilderTy &Builder = CGF.Builder;
10083 
10084   // Get the VAList.
10085   CharUnits SlotSize = CharUnits::fromQuantity(4);
10086   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
10087 
10088   // Handle the argument.
10089   ABIArgInfo AI = classifyArgumentType(Ty);
10090   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10091   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10092   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10093     AI.setCoerceToType(ArgTy);
10094   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10095 
10096   Address Val = Address::invalid();
10097   CharUnits ArgSize = CharUnits::Zero();
10098   switch (AI.getKind()) {
10099   case ABIArgInfo::Expand:
10100   case ABIArgInfo::CoerceAndExpand:
10101   case ABIArgInfo::InAlloca:
10102     llvm_unreachable("Unsupported ABI kind for va_arg");
10103   case ABIArgInfo::Ignore:
10104     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
10105     ArgSize = CharUnits::Zero();
10106     break;
10107   case ABIArgInfo::Extend:
10108   case ABIArgInfo::Direct:
10109     Val = Builder.CreateBitCast(AP, ArgPtrTy);
10110     ArgSize = CharUnits::fromQuantity(
10111                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10112     ArgSize = ArgSize.alignTo(SlotSize);
10113     break;
10114   case ABIArgInfo::Indirect:
10115   case ABIArgInfo::IndirectAliased:
10116     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10117     Val = Address(Builder.CreateLoad(Val), TypeAlign);
10118     ArgSize = SlotSize;
10119     break;
10120   }
10121 
10122   // Increment the VAList.
10123   if (!ArgSize.isZero()) {
10124     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10125     Builder.CreateStore(APN.getPointer(), VAListAddr);
10126   }
10127 
10128   return Val;
10129 }
10130 
10131 /// During the expansion of a RecordType, an incomplete TypeString is placed
10132 /// into the cache as a means to identify and break recursion.
10133 /// If there is a Recursive encoding in the cache, it is swapped out and will
10134 /// be reinserted by removeIncomplete().
10135 /// All other types of encoding should have been used rather than arriving here.
10136 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10137                                     std::string StubEnc) {
10138   if (!ID)
10139     return;
10140   Entry &E = Map[ID];
10141   assert( (E.Str.empty() || E.State == Recursive) &&
10142          "Incorrectly use of addIncomplete");
10143   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10144   E.Swapped.swap(E.Str); // swap out the Recursive
10145   E.Str.swap(StubEnc);
10146   E.State = Incomplete;
10147   ++IncompleteCount;
10148 }
10149 
10150 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10151 /// must be removed from the cache.
10152 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10153 /// Returns true if the RecordType was defined recursively.
10154 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10155   if (!ID)
10156     return false;
10157   auto I = Map.find(ID);
10158   assert(I != Map.end() && "Entry not present");
10159   Entry &E = I->second;
10160   assert( (E.State == Incomplete ||
10161            E.State == IncompleteUsed) &&
10162          "Entry must be an incomplete type");
10163   bool IsRecursive = false;
10164   if (E.State == IncompleteUsed) {
10165     // We made use of our Incomplete encoding, thus we are recursive.
10166     IsRecursive = true;
10167     --IncompleteUsedCount;
10168   }
10169   if (E.Swapped.empty())
10170     Map.erase(I);
10171   else {
10172     // Swap the Recursive back.
10173     E.Swapped.swap(E.Str);
10174     E.Swapped.clear();
10175     E.State = Recursive;
10176   }
10177   --IncompleteCount;
10178   return IsRecursive;
10179 }
10180 
10181 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10182 /// Recursive (viz: all sub-members were expanded as fully as possible).
10183 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10184                                     bool IsRecursive) {
10185   if (!ID || IncompleteUsedCount)
10186     return; // No key or it is is an incomplete sub-type so don't add.
10187   Entry &E = Map[ID];
10188   if (IsRecursive && !E.Str.empty()) {
10189     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10190            "This is not the same Recursive entry");
10191     // The parent container was not recursive after all, so we could have used
10192     // this Recursive sub-member entry after all, but we assumed the worse when
10193     // we started viz: IncompleteCount!=0.
10194     return;
10195   }
10196   assert(E.Str.empty() && "Entry already present");
10197   E.Str = Str.str();
10198   E.State = IsRecursive? Recursive : NonRecursive;
10199 }
10200 
10201 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10202 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10203 /// encoding is Recursive, return an empty StringRef.
10204 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10205   if (!ID)
10206     return StringRef();   // We have no key.
10207   auto I = Map.find(ID);
10208   if (I == Map.end())
10209     return StringRef();   // We have no encoding.
10210   Entry &E = I->second;
10211   if (E.State == Recursive && IncompleteCount)
10212     return StringRef();   // We don't use Recursive encodings for member types.
10213 
10214   if (E.State == Incomplete) {
10215     // The incomplete type is being used to break out of recursion.
10216     E.State = IncompleteUsed;
10217     ++IncompleteUsedCount;
10218   }
10219   return E.Str;
10220 }
10221 
10222 /// The XCore ABI includes a type information section that communicates symbol
10223 /// type information to the linker. The linker uses this information to verify
10224 /// safety/correctness of things such as array bound and pointers et al.
10225 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10226 /// This type information (TypeString) is emitted into meta data for all global
10227 /// symbols: definitions, declarations, functions & variables.
10228 ///
10229 /// The TypeString carries type, qualifier, name, size & value details.
10230 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10231 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10232 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10233 ///
10234 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10235                           const CodeGen::CodeGenModule &CGM,
10236                           TypeStringCache &TSC);
10237 
10238 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10239 void XCoreTargetCodeGenInfo::emitTargetMD(
10240     const Decl *D, llvm::GlobalValue *GV,
10241     const CodeGen::CodeGenModule &CGM) const {
10242   SmallStringEnc Enc;
10243   if (getTypeString(Enc, D, CGM, TSC)) {
10244     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10245     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10246                                 llvm::MDString::get(Ctx, Enc.str())};
10247     llvm::NamedMDNode *MD =
10248       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10249     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10250   }
10251 }
10252 
10253 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10254     CodeGen::CodeGenModule &CGM,
10255     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10256   // Warning, new MangledDeclNames may be appended within this loop.
10257   // We rely on MapVector insertions adding new elements to the end
10258   // of the container.
10259   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10260     auto Val = *(MangledDeclNames.begin() + I);
10261     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10262     if (GV) {
10263       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10264       emitTargetMD(D, GV, CGM);
10265     }
10266   }
10267 }
10268 
10269 //===----------------------------------------------------------------------===//
10270 // Base ABI and target codegen info implementation common between SPIR and
10271 // SPIR-V.
10272 //===----------------------------------------------------------------------===//
10273 
10274 namespace {
10275 class CommonSPIRABIInfo : public DefaultABIInfo {
10276 public:
10277   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10278 
10279 private:
10280   void setCCs();
10281 };
10282 
10283 class SPIRVABIInfo : public CommonSPIRABIInfo {
10284 public:
10285   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10286   void computeInfo(CGFunctionInfo &FI) const override;
10287 
10288 private:
10289   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10290 };
10291 } // end anonymous namespace
10292 namespace {
10293 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10294 public:
10295   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10296       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10297   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10298       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10299 
10300   LangAS getASTAllocaAddressSpace() const override {
10301     return getLangASFromTargetAS(
10302         getABIInfo().getDataLayout().getAllocaAddrSpace());
10303   }
10304 
10305   unsigned getOpenCLKernelCallingConv() const override;
10306 };
10307 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10308 public:
10309   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10310       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10311   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10312 };
10313 } // End anonymous namespace.
10314 
10315 void CommonSPIRABIInfo::setCCs() {
10316   assert(getRuntimeCC() == llvm::CallingConv::C);
10317   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10318 }
10319 
10320 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10321   if (getContext().getLangOpts().HIP) {
10322     // Coerce pointer arguments with default address space to CrossWorkGroup
10323     // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo
10324     // maps cuda_device to SPIR-V's CrossWorkGroup address space.
10325     llvm::Type *LTy = CGT.ConvertType(Ty);
10326     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10327     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10328     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10329     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10330       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10331       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10332     }
10333   }
10334   return classifyArgumentType(Ty);
10335 }
10336 
10337 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10338   // The logic is same as in DefaultABIInfo with an exception on the kernel
10339   // arguments handling.
10340   llvm::CallingConv::ID CC = FI.getCallingConvention();
10341 
10342   if (!getCXXABI().classifyReturnType(FI))
10343     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10344 
10345   for (auto &I : FI.arguments()) {
10346     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10347       I.info = classifyKernelArgumentType(I.type);
10348     } else {
10349       I.info = classifyArgumentType(I.type);
10350     }
10351   }
10352 }
10353 
10354 namespace clang {
10355 namespace CodeGen {
10356 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10357   if (CGM.getTarget().getTriple().isSPIRV())
10358     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10359   else
10360     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10361 }
10362 }
10363 }
10364 
10365 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10366   return llvm::CallingConv::SPIR_KERNEL;
10367 }
10368 
10369 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10370     const FunctionType *&FT) const {
10371   // Convert HIP kernels to SPIR-V kernels.
10372   if (getABIInfo().getContext().getLangOpts().HIP) {
10373     FT = getABIInfo().getContext().adjustFunctionType(
10374         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10375     return;
10376   }
10377 }
10378 
10379 static bool appendType(SmallStringEnc &Enc, QualType QType,
10380                        const CodeGen::CodeGenModule &CGM,
10381                        TypeStringCache &TSC);
10382 
10383 /// Helper function for appendRecordType().
10384 /// Builds a SmallVector containing the encoded field types in declaration
10385 /// order.
10386 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10387                              const RecordDecl *RD,
10388                              const CodeGen::CodeGenModule &CGM,
10389                              TypeStringCache &TSC) {
10390   for (const auto *Field : RD->fields()) {
10391     SmallStringEnc Enc;
10392     Enc += "m(";
10393     Enc += Field->getName();
10394     Enc += "){";
10395     if (Field->isBitField()) {
10396       Enc += "b(";
10397       llvm::raw_svector_ostream OS(Enc);
10398       OS << Field->getBitWidthValue(CGM.getContext());
10399       Enc += ':';
10400     }
10401     if (!appendType(Enc, Field->getType(), CGM, TSC))
10402       return false;
10403     if (Field->isBitField())
10404       Enc += ')';
10405     Enc += '}';
10406     FE.emplace_back(!Field->getName().empty(), Enc);
10407   }
10408   return true;
10409 }
10410 
10411 /// Appends structure and union types to Enc and adds encoding to cache.
10412 /// Recursively calls appendType (via extractFieldType) for each field.
10413 /// Union types have their fields ordered according to the ABI.
10414 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10415                              const CodeGen::CodeGenModule &CGM,
10416                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10417   // Append the cached TypeString if we have one.
10418   StringRef TypeString = TSC.lookupStr(ID);
10419   if (!TypeString.empty()) {
10420     Enc += TypeString;
10421     return true;
10422   }
10423 
10424   // Start to emit an incomplete TypeString.
10425   size_t Start = Enc.size();
10426   Enc += (RT->isUnionType()? 'u' : 's');
10427   Enc += '(';
10428   if (ID)
10429     Enc += ID->getName();
10430   Enc += "){";
10431 
10432   // We collect all encoded fields and order as necessary.
10433   bool IsRecursive = false;
10434   const RecordDecl *RD = RT->getDecl()->getDefinition();
10435   if (RD && !RD->field_empty()) {
10436     // An incomplete TypeString stub is placed in the cache for this RecordType
10437     // so that recursive calls to this RecordType will use it whilst building a
10438     // complete TypeString for this RecordType.
10439     SmallVector<FieldEncoding, 16> FE;
10440     std::string StubEnc(Enc.substr(Start).str());
10441     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10442     TSC.addIncomplete(ID, std::move(StubEnc));
10443     if (!extractFieldType(FE, RD, CGM, TSC)) {
10444       (void) TSC.removeIncomplete(ID);
10445       return false;
10446     }
10447     IsRecursive = TSC.removeIncomplete(ID);
10448     // The ABI requires unions to be sorted but not structures.
10449     // See FieldEncoding::operator< for sort algorithm.
10450     if (RT->isUnionType())
10451       llvm::sort(FE);
10452     // We can now complete the TypeString.
10453     unsigned E = FE.size();
10454     for (unsigned I = 0; I != E; ++I) {
10455       if (I)
10456         Enc += ',';
10457       Enc += FE[I].str();
10458     }
10459   }
10460   Enc += '}';
10461   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10462   return true;
10463 }
10464 
10465 /// Appends enum types to Enc and adds the encoding to the cache.
10466 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10467                            TypeStringCache &TSC,
10468                            const IdentifierInfo *ID) {
10469   // Append the cached TypeString if we have one.
10470   StringRef TypeString = TSC.lookupStr(ID);
10471   if (!TypeString.empty()) {
10472     Enc += TypeString;
10473     return true;
10474   }
10475 
10476   size_t Start = Enc.size();
10477   Enc += "e(";
10478   if (ID)
10479     Enc += ID->getName();
10480   Enc += "){";
10481 
10482   // We collect all encoded enumerations and order them alphanumerically.
10483   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10484     SmallVector<FieldEncoding, 16> FE;
10485     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10486          ++I) {
10487       SmallStringEnc EnumEnc;
10488       EnumEnc += "m(";
10489       EnumEnc += I->getName();
10490       EnumEnc += "){";
10491       I->getInitVal().toString(EnumEnc);
10492       EnumEnc += '}';
10493       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10494     }
10495     llvm::sort(FE);
10496     unsigned E = FE.size();
10497     for (unsigned I = 0; I != E; ++I) {
10498       if (I)
10499         Enc += ',';
10500       Enc += FE[I].str();
10501     }
10502   }
10503   Enc += '}';
10504   TSC.addIfComplete(ID, Enc.substr(Start), false);
10505   return true;
10506 }
10507 
10508 /// Appends type's qualifier to Enc.
10509 /// This is done prior to appending the type's encoding.
10510 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10511   // Qualifiers are emitted in alphabetical order.
10512   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10513   int Lookup = 0;
10514   if (QT.isConstQualified())
10515     Lookup += 1<<0;
10516   if (QT.isRestrictQualified())
10517     Lookup += 1<<1;
10518   if (QT.isVolatileQualified())
10519     Lookup += 1<<2;
10520   Enc += Table[Lookup];
10521 }
10522 
10523 /// Appends built-in types to Enc.
10524 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10525   const char *EncType;
10526   switch (BT->getKind()) {
10527     case BuiltinType::Void:
10528       EncType = "0";
10529       break;
10530     case BuiltinType::Bool:
10531       EncType = "b";
10532       break;
10533     case BuiltinType::Char_U:
10534       EncType = "uc";
10535       break;
10536     case BuiltinType::UChar:
10537       EncType = "uc";
10538       break;
10539     case BuiltinType::SChar:
10540       EncType = "sc";
10541       break;
10542     case BuiltinType::UShort:
10543       EncType = "us";
10544       break;
10545     case BuiltinType::Short:
10546       EncType = "ss";
10547       break;
10548     case BuiltinType::UInt:
10549       EncType = "ui";
10550       break;
10551     case BuiltinType::Int:
10552       EncType = "si";
10553       break;
10554     case BuiltinType::ULong:
10555       EncType = "ul";
10556       break;
10557     case BuiltinType::Long:
10558       EncType = "sl";
10559       break;
10560     case BuiltinType::ULongLong:
10561       EncType = "ull";
10562       break;
10563     case BuiltinType::LongLong:
10564       EncType = "sll";
10565       break;
10566     case BuiltinType::Float:
10567       EncType = "ft";
10568       break;
10569     case BuiltinType::Double:
10570       EncType = "d";
10571       break;
10572     case BuiltinType::LongDouble:
10573       EncType = "ld";
10574       break;
10575     default:
10576       return false;
10577   }
10578   Enc += EncType;
10579   return true;
10580 }
10581 
10582 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10583 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10584                               const CodeGen::CodeGenModule &CGM,
10585                               TypeStringCache &TSC) {
10586   Enc += "p(";
10587   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10588     return false;
10589   Enc += ')';
10590   return true;
10591 }
10592 
10593 /// Appends array encoding to Enc before calling appendType for the element.
10594 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10595                             const ArrayType *AT,
10596                             const CodeGen::CodeGenModule &CGM,
10597                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10598   if (AT->getSizeModifier() != ArrayType::Normal)
10599     return false;
10600   Enc += "a(";
10601   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10602     CAT->getSize().toStringUnsigned(Enc);
10603   else
10604     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10605   Enc += ':';
10606   // The Qualifiers should be attached to the type rather than the array.
10607   appendQualifier(Enc, QT);
10608   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10609     return false;
10610   Enc += ')';
10611   return true;
10612 }
10613 
10614 /// Appends a function encoding to Enc, calling appendType for the return type
10615 /// and the arguments.
10616 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10617                              const CodeGen::CodeGenModule &CGM,
10618                              TypeStringCache &TSC) {
10619   Enc += "f{";
10620   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10621     return false;
10622   Enc += "}(";
10623   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10624     // N.B. we are only interested in the adjusted param types.
10625     auto I = FPT->param_type_begin();
10626     auto E = FPT->param_type_end();
10627     if (I != E) {
10628       do {
10629         if (!appendType(Enc, *I, CGM, TSC))
10630           return false;
10631         ++I;
10632         if (I != E)
10633           Enc += ',';
10634       } while (I != E);
10635       if (FPT->isVariadic())
10636         Enc += ",va";
10637     } else {
10638       if (FPT->isVariadic())
10639         Enc += "va";
10640       else
10641         Enc += '0';
10642     }
10643   }
10644   Enc += ')';
10645   return true;
10646 }
10647 
10648 /// Handles the type's qualifier before dispatching a call to handle specific
10649 /// type encodings.
10650 static bool appendType(SmallStringEnc &Enc, QualType QType,
10651                        const CodeGen::CodeGenModule &CGM,
10652                        TypeStringCache &TSC) {
10653 
10654   QualType QT = QType.getCanonicalType();
10655 
10656   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10657     // The Qualifiers should be attached to the type rather than the array.
10658     // Thus we don't call appendQualifier() here.
10659     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10660 
10661   appendQualifier(Enc, QT);
10662 
10663   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10664     return appendBuiltinType(Enc, BT);
10665 
10666   if (const PointerType *PT = QT->getAs<PointerType>())
10667     return appendPointerType(Enc, PT, CGM, TSC);
10668 
10669   if (const EnumType *ET = QT->getAs<EnumType>())
10670     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10671 
10672   if (const RecordType *RT = QT->getAsStructureType())
10673     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10674 
10675   if (const RecordType *RT = QT->getAsUnionType())
10676     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10677 
10678   if (const FunctionType *FT = QT->getAs<FunctionType>())
10679     return appendFunctionType(Enc, FT, CGM, TSC);
10680 
10681   return false;
10682 }
10683 
10684 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10685                           const CodeGen::CodeGenModule &CGM,
10686                           TypeStringCache &TSC) {
10687   if (!D)
10688     return false;
10689 
10690   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10691     if (FD->getLanguageLinkage() != CLanguageLinkage)
10692       return false;
10693     return appendType(Enc, FD->getType(), CGM, TSC);
10694   }
10695 
10696   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10697     if (VD->getLanguageLinkage() != CLanguageLinkage)
10698       return false;
10699     QualType QT = VD->getType().getCanonicalType();
10700     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10701       // Global ArrayTypes are given a size of '*' if the size is unknown.
10702       // The Qualifiers should be attached to the type rather than the array.
10703       // Thus we don't call appendQualifier() here.
10704       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10705     }
10706     return appendType(Enc, QT, CGM, TSC);
10707   }
10708   return false;
10709 }
10710 
10711 //===----------------------------------------------------------------------===//
10712 // RISCV ABI Implementation
10713 //===----------------------------------------------------------------------===//
10714 
10715 namespace {
10716 class RISCVABIInfo : public DefaultABIInfo {
10717 private:
10718   // Size of the integer ('x') registers in bits.
10719   unsigned XLen;
10720   // Size of the floating point ('f') registers in bits. Note that the target
10721   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10722   // with soft float ABI has FLen==0).
10723   unsigned FLen;
10724   static const int NumArgGPRs = 8;
10725   static const int NumArgFPRs = 8;
10726   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10727                                       llvm::Type *&Field1Ty,
10728                                       CharUnits &Field1Off,
10729                                       llvm::Type *&Field2Ty,
10730                                       CharUnits &Field2Off) const;
10731 
10732 public:
10733   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10734       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10735 
10736   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10737   // non-virtual, but computeInfo is virtual, so we overload it.
10738   void computeInfo(CGFunctionInfo &FI) const override;
10739 
10740   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10741                                   int &ArgFPRsLeft) const;
10742   ABIArgInfo classifyReturnType(QualType RetTy) const;
10743 
10744   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10745                     QualType Ty) const override;
10746 
10747   ABIArgInfo extendType(QualType Ty) const;
10748 
10749   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10750                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10751                                 CharUnits &Field2Off, int &NeededArgGPRs,
10752                                 int &NeededArgFPRs) const;
10753   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10754                                                CharUnits Field1Off,
10755                                                llvm::Type *Field2Ty,
10756                                                CharUnits Field2Off) const;
10757 };
10758 } // end anonymous namespace
10759 
10760 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10761   QualType RetTy = FI.getReturnType();
10762   if (!getCXXABI().classifyReturnType(FI))
10763     FI.getReturnInfo() = classifyReturnType(RetTy);
10764 
10765   // IsRetIndirect is true if classifyArgumentType indicated the value should
10766   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10767   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10768   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10769   // list and pass indirectly on RV32.
10770   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10771   if (!IsRetIndirect && RetTy->isScalarType() &&
10772       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10773     if (RetTy->isComplexType() && FLen) {
10774       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10775       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10776     } else {
10777       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10778       IsRetIndirect = true;
10779     }
10780   }
10781 
10782   // We must track the number of GPRs used in order to conform to the RISC-V
10783   // ABI, as integer scalars passed in registers should have signext/zeroext
10784   // when promoted, but are anyext if passed on the stack. As GPR usage is
10785   // different for variadic arguments, we must also track whether we are
10786   // examining a vararg or not.
10787   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10788   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10789   int NumFixedArgs = FI.getNumRequiredArgs();
10790 
10791   int ArgNum = 0;
10792   for (auto &ArgInfo : FI.arguments()) {
10793     bool IsFixed = ArgNum < NumFixedArgs;
10794     ArgInfo.info =
10795         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10796     ArgNum++;
10797   }
10798 }
10799 
10800 // Returns true if the struct is a potential candidate for the floating point
10801 // calling convention. If this function returns true, the caller is
10802 // responsible for checking that if there is only a single field then that
10803 // field is a float.
10804 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10805                                                   llvm::Type *&Field1Ty,
10806                                                   CharUnits &Field1Off,
10807                                                   llvm::Type *&Field2Ty,
10808                                                   CharUnits &Field2Off) const {
10809   bool IsInt = Ty->isIntegralOrEnumerationType();
10810   bool IsFloat = Ty->isRealFloatingType();
10811 
10812   if (IsInt || IsFloat) {
10813     uint64_t Size = getContext().getTypeSize(Ty);
10814     if (IsInt && Size > XLen)
10815       return false;
10816     // Can't be eligible if larger than the FP registers. Half precision isn't
10817     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10818     // default to the integer ABI in that case.
10819     if (IsFloat && (Size > FLen || Size < 32))
10820       return false;
10821     // Can't be eligible if an integer type was already found (int+int pairs
10822     // are not eligible).
10823     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10824       return false;
10825     if (!Field1Ty) {
10826       Field1Ty = CGT.ConvertType(Ty);
10827       Field1Off = CurOff;
10828       return true;
10829     }
10830     if (!Field2Ty) {
10831       Field2Ty = CGT.ConvertType(Ty);
10832       Field2Off = CurOff;
10833       return true;
10834     }
10835     return false;
10836   }
10837 
10838   if (auto CTy = Ty->getAs<ComplexType>()) {
10839     if (Field1Ty)
10840       return false;
10841     QualType EltTy = CTy->getElementType();
10842     if (getContext().getTypeSize(EltTy) > FLen)
10843       return false;
10844     Field1Ty = CGT.ConvertType(EltTy);
10845     Field1Off = CurOff;
10846     Field2Ty = Field1Ty;
10847     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10848     return true;
10849   }
10850 
10851   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10852     uint64_t ArraySize = ATy->getSize().getZExtValue();
10853     QualType EltTy = ATy->getElementType();
10854     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10855     for (uint64_t i = 0; i < ArraySize; ++i) {
10856       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10857                                                 Field1Off, Field2Ty, Field2Off);
10858       if (!Ret)
10859         return false;
10860       CurOff += EltSize;
10861     }
10862     return true;
10863   }
10864 
10865   if (const auto *RTy = Ty->getAs<RecordType>()) {
10866     // Structures with either a non-trivial destructor or a non-trivial
10867     // copy constructor are not eligible for the FP calling convention.
10868     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10869       return false;
10870     if (isEmptyRecord(getContext(), Ty, true))
10871       return true;
10872     const RecordDecl *RD = RTy->getDecl();
10873     // Unions aren't eligible unless they're empty (which is caught above).
10874     if (RD->isUnion())
10875       return false;
10876     int ZeroWidthBitFieldCount = 0;
10877     for (const FieldDecl *FD : RD->fields()) {
10878       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10879       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10880       QualType QTy = FD->getType();
10881       if (FD->isBitField()) {
10882         unsigned BitWidth = FD->getBitWidthValue(getContext());
10883         // Allow a bitfield with a type greater than XLen as long as the
10884         // bitwidth is XLen or less.
10885         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10886           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10887         if (BitWidth == 0) {
10888           ZeroWidthBitFieldCount++;
10889           continue;
10890         }
10891       }
10892 
10893       bool Ret = detectFPCCEligibleStructHelper(
10894           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10895           Field1Ty, Field1Off, Field2Ty, Field2Off);
10896       if (!Ret)
10897         return false;
10898 
10899       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10900       // or int+fp structs, but are ignored for a struct with an fp field and
10901       // any number of zero-width bitfields.
10902       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10903         return false;
10904     }
10905     return Field1Ty != nullptr;
10906   }
10907 
10908   return false;
10909 }
10910 
10911 // Determine if a struct is eligible for passing according to the floating
10912 // point calling convention (i.e., when flattened it contains a single fp
10913 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10914 // NeededArgGPRs are incremented appropriately.
10915 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10916                                             CharUnits &Field1Off,
10917                                             llvm::Type *&Field2Ty,
10918                                             CharUnits &Field2Off,
10919                                             int &NeededArgGPRs,
10920                                             int &NeededArgFPRs) const {
10921   Field1Ty = nullptr;
10922   Field2Ty = nullptr;
10923   NeededArgGPRs = 0;
10924   NeededArgFPRs = 0;
10925   bool IsCandidate = detectFPCCEligibleStructHelper(
10926       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10927   // Not really a candidate if we have a single int but no float.
10928   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10929     return false;
10930   if (!IsCandidate)
10931     return false;
10932   if (Field1Ty && Field1Ty->isFloatingPointTy())
10933     NeededArgFPRs++;
10934   else if (Field1Ty)
10935     NeededArgGPRs++;
10936   if (Field2Ty && Field2Ty->isFloatingPointTy())
10937     NeededArgFPRs++;
10938   else if (Field2Ty)
10939     NeededArgGPRs++;
10940   return true;
10941 }
10942 
10943 // Call getCoerceAndExpand for the two-element flattened struct described by
10944 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10945 // appropriate coerceToType and unpaddedCoerceToType.
10946 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10947     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10948     CharUnits Field2Off) const {
10949   SmallVector<llvm::Type *, 3> CoerceElts;
10950   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10951   if (!Field1Off.isZero())
10952     CoerceElts.push_back(llvm::ArrayType::get(
10953         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10954 
10955   CoerceElts.push_back(Field1Ty);
10956   UnpaddedCoerceElts.push_back(Field1Ty);
10957 
10958   if (!Field2Ty) {
10959     return ABIArgInfo::getCoerceAndExpand(
10960         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10961         UnpaddedCoerceElts[0]);
10962   }
10963 
10964   CharUnits Field2Align =
10965       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10966   CharUnits Field1End = Field1Off +
10967       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10968   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10969 
10970   CharUnits Padding = CharUnits::Zero();
10971   if (Field2Off > Field2OffNoPadNoPack)
10972     Padding = Field2Off - Field2OffNoPadNoPack;
10973   else if (Field2Off != Field2Align && Field2Off > Field1End)
10974     Padding = Field2Off - Field1End;
10975 
10976   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10977 
10978   if (!Padding.isZero())
10979     CoerceElts.push_back(llvm::ArrayType::get(
10980         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10981 
10982   CoerceElts.push_back(Field2Ty);
10983   UnpaddedCoerceElts.push_back(Field2Ty);
10984 
10985   auto CoerceToType =
10986       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10987   auto UnpaddedCoerceToType =
10988       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10989 
10990   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10991 }
10992 
10993 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10994                                               int &ArgGPRsLeft,
10995                                               int &ArgFPRsLeft) const {
10996   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10997   Ty = useFirstFieldIfTransparentUnion(Ty);
10998 
10999   // Structures with either a non-trivial destructor or a non-trivial
11000   // copy constructor are always passed indirectly.
11001   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11002     if (ArgGPRsLeft)
11003       ArgGPRsLeft -= 1;
11004     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11005                                            CGCXXABI::RAA_DirectInMemory);
11006   }
11007 
11008   // Ignore empty structs/unions.
11009   if (isEmptyRecord(getContext(), Ty, true))
11010     return ABIArgInfo::getIgnore();
11011 
11012   uint64_t Size = getContext().getTypeSize(Ty);
11013 
11014   // Pass floating point values via FPRs if possible.
11015   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11016       FLen >= Size && ArgFPRsLeft) {
11017     ArgFPRsLeft--;
11018     return ABIArgInfo::getDirect();
11019   }
11020 
11021   // Complex types for the hard float ABI must be passed direct rather than
11022   // using CoerceAndExpand.
11023   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11024     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11025     if (getContext().getTypeSize(EltTy) <= FLen) {
11026       ArgFPRsLeft -= 2;
11027       return ABIArgInfo::getDirect();
11028     }
11029   }
11030 
11031   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11032     llvm::Type *Field1Ty = nullptr;
11033     llvm::Type *Field2Ty = nullptr;
11034     CharUnits Field1Off = CharUnits::Zero();
11035     CharUnits Field2Off = CharUnits::Zero();
11036     int NeededArgGPRs = 0;
11037     int NeededArgFPRs = 0;
11038     bool IsCandidate =
11039         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11040                                  NeededArgGPRs, NeededArgFPRs);
11041     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11042         NeededArgFPRs <= ArgFPRsLeft) {
11043       ArgGPRsLeft -= NeededArgGPRs;
11044       ArgFPRsLeft -= NeededArgFPRs;
11045       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11046                                                Field2Off);
11047     }
11048   }
11049 
11050   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11051   bool MustUseStack = false;
11052   // Determine the number of GPRs needed to pass the current argument
11053   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11054   // register pairs, so may consume 3 registers.
11055   int NeededArgGPRs = 1;
11056   if (!IsFixed && NeededAlign == 2 * XLen)
11057     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11058   else if (Size > XLen && Size <= 2 * XLen)
11059     NeededArgGPRs = 2;
11060 
11061   if (NeededArgGPRs > ArgGPRsLeft) {
11062     MustUseStack = true;
11063     NeededArgGPRs = ArgGPRsLeft;
11064   }
11065 
11066   ArgGPRsLeft -= NeededArgGPRs;
11067 
11068   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11069     // Treat an enum type as its underlying type.
11070     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11071       Ty = EnumTy->getDecl()->getIntegerType();
11072 
11073     // All integral types are promoted to XLen width, unless passed on the
11074     // stack.
11075     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11076       return extendType(Ty);
11077     }
11078 
11079     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11080       if (EIT->getNumBits() < XLen && !MustUseStack)
11081         return extendType(Ty);
11082       if (EIT->getNumBits() > 128 ||
11083           (!getContext().getTargetInfo().hasInt128Type() &&
11084            EIT->getNumBits() > 64))
11085         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11086     }
11087 
11088     return ABIArgInfo::getDirect();
11089   }
11090 
11091   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11092   // so coerce to integers.
11093   if (Size <= 2 * XLen) {
11094     unsigned Alignment = getContext().getTypeAlign(Ty);
11095 
11096     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11097     // required, and a 2-element XLen array if only XLen alignment is required.
11098     if (Size <= XLen) {
11099       return ABIArgInfo::getDirect(
11100           llvm::IntegerType::get(getVMContext(), XLen));
11101     } else if (Alignment == 2 * XLen) {
11102       return ABIArgInfo::getDirect(
11103           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11104     } else {
11105       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11106           llvm::IntegerType::get(getVMContext(), XLen), 2));
11107     }
11108   }
11109   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11110 }
11111 
11112 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11113   if (RetTy->isVoidType())
11114     return ABIArgInfo::getIgnore();
11115 
11116   int ArgGPRsLeft = 2;
11117   int ArgFPRsLeft = FLen ? 2 : 0;
11118 
11119   // The rules for return and argument types are the same, so defer to
11120   // classifyArgumentType.
11121   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11122                               ArgFPRsLeft);
11123 }
11124 
11125 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11126                                 QualType Ty) const {
11127   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11128 
11129   // Empty records are ignored for parameter passing purposes.
11130   if (isEmptyRecord(getContext(), Ty, true)) {
11131     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
11132     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11133     return Addr;
11134   }
11135 
11136   auto TInfo = getContext().getTypeInfoInChars(Ty);
11137 
11138   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11139   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11140 
11141   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11142                           SlotSize, /*AllowHigherAlign=*/true);
11143 }
11144 
11145 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11146   int TySize = getContext().getTypeSize(Ty);
11147   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11148   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11149     return ABIArgInfo::getSignExtend(Ty);
11150   return ABIArgInfo::getExtend(Ty);
11151 }
11152 
11153 namespace {
11154 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11155 public:
11156   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11157                          unsigned FLen)
11158       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11159 
11160   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11161                            CodeGen::CodeGenModule &CGM) const override {
11162     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11163     if (!FD) return;
11164 
11165     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11166     if (!Attr)
11167       return;
11168 
11169     const char *Kind;
11170     switch (Attr->getInterrupt()) {
11171     case RISCVInterruptAttr::user: Kind = "user"; break;
11172     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11173     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11174     }
11175 
11176     auto *Fn = cast<llvm::Function>(GV);
11177 
11178     Fn->addFnAttr("interrupt", Kind);
11179   }
11180 };
11181 } // namespace
11182 
11183 //===----------------------------------------------------------------------===//
11184 // VE ABI Implementation.
11185 //
11186 namespace {
11187 class VEABIInfo : public DefaultABIInfo {
11188 public:
11189   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11190 
11191 private:
11192   ABIArgInfo classifyReturnType(QualType RetTy) const;
11193   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11194   void computeInfo(CGFunctionInfo &FI) const override;
11195 };
11196 } // end anonymous namespace
11197 
11198 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11199   if (Ty->isAnyComplexType())
11200     return ABIArgInfo::getDirect();
11201   uint64_t Size = getContext().getTypeSize(Ty);
11202   if (Size < 64 && Ty->isIntegerType())
11203     return ABIArgInfo::getExtend(Ty);
11204   return DefaultABIInfo::classifyReturnType(Ty);
11205 }
11206 
11207 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11208   if (Ty->isAnyComplexType())
11209     return ABIArgInfo::getDirect();
11210   uint64_t Size = getContext().getTypeSize(Ty);
11211   if (Size < 64 && Ty->isIntegerType())
11212     return ABIArgInfo::getExtend(Ty);
11213   return DefaultABIInfo::classifyArgumentType(Ty);
11214 }
11215 
11216 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11217   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11218   for (auto &Arg : FI.arguments())
11219     Arg.info = classifyArgumentType(Arg.type);
11220 }
11221 
11222 namespace {
11223 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11224 public:
11225   VETargetCodeGenInfo(CodeGenTypes &CGT)
11226       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11227   // VE ABI requires the arguments of variadic and prototype-less functions
11228   // are passed in both registers and memory.
11229   bool isNoProtoCallVariadic(const CallArgList &args,
11230                              const FunctionNoProtoType *fnType) const override {
11231     return true;
11232   }
11233 };
11234 } // end anonymous namespace
11235 
11236 //===----------------------------------------------------------------------===//
11237 // Driver code
11238 //===----------------------------------------------------------------------===//
11239 
11240 bool CodeGenModule::supportsCOMDAT() const {
11241   return getTriple().supportsCOMDAT();
11242 }
11243 
11244 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11245   if (TheTargetCodeGenInfo)
11246     return *TheTargetCodeGenInfo;
11247 
11248   // Helper to set the unique_ptr while still keeping the return value.
11249   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11250     this->TheTargetCodeGenInfo.reset(P);
11251     return *P;
11252   };
11253 
11254   const llvm::Triple &Triple = getTarget().getTriple();
11255   switch (Triple.getArch()) {
11256   default:
11257     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11258 
11259   case llvm::Triple::le32:
11260     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11261   case llvm::Triple::m68k:
11262     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11263   case llvm::Triple::mips:
11264   case llvm::Triple::mipsel:
11265     if (Triple.getOS() == llvm::Triple::NaCl)
11266       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11267     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11268 
11269   case llvm::Triple::mips64:
11270   case llvm::Triple::mips64el:
11271     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11272 
11273   case llvm::Triple::avr:
11274     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11275 
11276   case llvm::Triple::aarch64:
11277   case llvm::Triple::aarch64_32:
11278   case llvm::Triple::aarch64_be: {
11279     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11280     if (getTarget().getABI() == "darwinpcs")
11281       Kind = AArch64ABIInfo::DarwinPCS;
11282     else if (Triple.isOSWindows())
11283       return SetCGInfo(
11284           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11285 
11286     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11287   }
11288 
11289   case llvm::Triple::wasm32:
11290   case llvm::Triple::wasm64: {
11291     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11292     if (getTarget().getABI() == "experimental-mv")
11293       Kind = WebAssemblyABIInfo::ExperimentalMV;
11294     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11295   }
11296 
11297   case llvm::Triple::arm:
11298   case llvm::Triple::armeb:
11299   case llvm::Triple::thumb:
11300   case llvm::Triple::thumbeb: {
11301     if (Triple.getOS() == llvm::Triple::Win32) {
11302       return SetCGInfo(
11303           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11304     }
11305 
11306     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11307     StringRef ABIStr = getTarget().getABI();
11308     if (ABIStr == "apcs-gnu")
11309       Kind = ARMABIInfo::APCS;
11310     else if (ABIStr == "aapcs16")
11311       Kind = ARMABIInfo::AAPCS16_VFP;
11312     else if (CodeGenOpts.FloatABI == "hard" ||
11313              (CodeGenOpts.FloatABI != "soft" &&
11314               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11315                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11316                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11317       Kind = ARMABIInfo::AAPCS_VFP;
11318 
11319     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11320   }
11321 
11322   case llvm::Triple::ppc: {
11323     if (Triple.isOSAIX())
11324       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11325 
11326     bool IsSoftFloat =
11327         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11328     bool RetSmallStructInRegABI =
11329         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11330     return SetCGInfo(
11331         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11332   }
11333   case llvm::Triple::ppcle: {
11334     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11335     bool RetSmallStructInRegABI =
11336         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11337     return SetCGInfo(
11338         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11339   }
11340   case llvm::Triple::ppc64:
11341     if (Triple.isOSAIX())
11342       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11343 
11344     if (Triple.isOSBinFormatELF()) {
11345       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11346       if (getTarget().getABI() == "elfv2")
11347         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11348       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11349 
11350       return SetCGInfo(
11351           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11352     }
11353     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11354   case llvm::Triple::ppc64le: {
11355     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11356     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11357     if (getTarget().getABI() == "elfv1")
11358       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11359     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11360 
11361     return SetCGInfo(
11362         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11363   }
11364 
11365   case llvm::Triple::nvptx:
11366   case llvm::Triple::nvptx64:
11367     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11368 
11369   case llvm::Triple::msp430:
11370     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11371 
11372   case llvm::Triple::riscv32:
11373   case llvm::Triple::riscv64: {
11374     StringRef ABIStr = getTarget().getABI();
11375     unsigned XLen = getTarget().getPointerWidth(0);
11376     unsigned ABIFLen = 0;
11377     if (ABIStr.endswith("f"))
11378       ABIFLen = 32;
11379     else if (ABIStr.endswith("d"))
11380       ABIFLen = 64;
11381     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11382   }
11383 
11384   case llvm::Triple::systemz: {
11385     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11386     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11387     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11388   }
11389 
11390   case llvm::Triple::tce:
11391   case llvm::Triple::tcele:
11392     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11393 
11394   case llvm::Triple::x86: {
11395     bool IsDarwinVectorABI = Triple.isOSDarwin();
11396     bool RetSmallStructInRegABI =
11397         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11398     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11399 
11400     if (Triple.getOS() == llvm::Triple::Win32) {
11401       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11402           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11403           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11404     } else {
11405       return SetCGInfo(new X86_32TargetCodeGenInfo(
11406           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11407           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11408           CodeGenOpts.FloatABI == "soft"));
11409     }
11410   }
11411 
11412   case llvm::Triple::x86_64: {
11413     StringRef ABI = getTarget().getABI();
11414     X86AVXABILevel AVXLevel =
11415         (ABI == "avx512"
11416              ? X86AVXABILevel::AVX512
11417              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11418 
11419     switch (Triple.getOS()) {
11420     case llvm::Triple::Win32:
11421       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11422     default:
11423       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11424     }
11425   }
11426   case llvm::Triple::hexagon:
11427     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11428   case llvm::Triple::lanai:
11429     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11430   case llvm::Triple::r600:
11431     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11432   case llvm::Triple::amdgcn:
11433     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11434   case llvm::Triple::sparc:
11435     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11436   case llvm::Triple::sparcv9:
11437     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11438   case llvm::Triple::xcore:
11439     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11440   case llvm::Triple::arc:
11441     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11442   case llvm::Triple::spir:
11443   case llvm::Triple::spir64:
11444     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11445   case llvm::Triple::spirv32:
11446   case llvm::Triple::spirv64:
11447     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11448   case llvm::Triple::ve:
11449     return SetCGInfo(new VETargetCodeGenInfo(Types));
11450   }
11451 }
11452 
11453 /// Create an OpenCL kernel for an enqueued block.
11454 ///
11455 /// The kernel has the same function type as the block invoke function. Its
11456 /// name is the name of the block invoke function postfixed with "_kernel".
11457 /// It simply calls the block invoke function then returns.
11458 llvm::Function *
11459 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11460                                              llvm::Function *Invoke,
11461                                              llvm::Value *BlockLiteral) const {
11462   auto *InvokeFT = Invoke->getFunctionType();
11463   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11464   for (auto &P : InvokeFT->params())
11465     ArgTys.push_back(P);
11466   auto &C = CGF.getLLVMContext();
11467   std::string Name = Invoke->getName().str() + "_kernel";
11468   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11469   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11470                                    &CGF.CGM.getModule());
11471   auto IP = CGF.Builder.saveIP();
11472   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11473   auto &Builder = CGF.Builder;
11474   Builder.SetInsertPoint(BB);
11475   llvm::SmallVector<llvm::Value *, 2> Args;
11476   for (auto &A : F->args())
11477     Args.push_back(&A);
11478   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11479   call->setCallingConv(Invoke->getCallingConv());
11480   Builder.CreateRetVoid();
11481   Builder.restoreIP(IP);
11482   return F;
11483 }
11484 
11485 /// Create an OpenCL kernel for an enqueued block.
11486 ///
11487 /// The type of the first argument (the block literal) is the struct type
11488 /// of the block literal instead of a pointer type. The first argument
11489 /// (block literal) is passed directly by value to the kernel. The kernel
11490 /// allocates the same type of struct on stack and stores the block literal
11491 /// to it and passes its pointer to the block invoke function. The kernel
11492 /// has "enqueued-block" function attribute and kernel argument metadata.
11493 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11494     CodeGenFunction &CGF, llvm::Function *Invoke,
11495     llvm::Value *BlockLiteral) const {
11496   auto &Builder = CGF.Builder;
11497   auto &C = CGF.getLLVMContext();
11498 
11499   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11500   auto *InvokeFT = Invoke->getFunctionType();
11501   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11502   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11503   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11504   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11505   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11506   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11507   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11508 
11509   ArgTys.push_back(BlockTy);
11510   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11511   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11512   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11513   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11514   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11515   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11516   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11517     ArgTys.push_back(InvokeFT->getParamType(I));
11518     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11519     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11520     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11521     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11522     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11523     ArgNames.push_back(
11524         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11525   }
11526   std::string Name = Invoke->getName().str() + "_kernel";
11527   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11528   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11529                                    &CGF.CGM.getModule());
11530   F->addFnAttr("enqueued-block");
11531   auto IP = CGF.Builder.saveIP();
11532   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11533   Builder.SetInsertPoint(BB);
11534   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11535   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11536   BlockPtr->setAlignment(BlockAlign);
11537   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11538   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11539   llvm::SmallVector<llvm::Value *, 2> Args;
11540   Args.push_back(Cast);
11541   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11542     Args.push_back(I);
11543   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11544   call->setCallingConv(Invoke->getCallingConv());
11545   Builder.CreateRetVoid();
11546   Builder.restoreIP(IP);
11547 
11548   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11549   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11550   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11551   F->setMetadata("kernel_arg_base_type",
11552                  llvm::MDNode::get(C, ArgBaseTypeNames));
11553   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11554   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11555     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11556 
11557   return F;
11558 }
11559