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