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