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