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