1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TargetInfo.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGValue.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "clang/CodeGen/SwiftCallingConv.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IntrinsicsNVPTX.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm> // std::sort
35 
36 using namespace clang;
37 using namespace CodeGen;
38 
39 // Helper for coercing an aggregate argument or return value into an integer
40 // array of the same size (including padding) and alignment.  This alternate
41 // coercion happens only for the RenderScript ABI and can be removed after
42 // runtimes that rely on it are no longer supported.
43 //
44 // RenderScript assumes that the size of the argument / return value in the IR
45 // is the same as the size of the corresponding qualified type. This helper
46 // coerces the aggregate type into an array of the same size (including
47 // padding).  This coercion is used in lieu of expansion of struct members or
48 // other canonical coercions that return a coerced-type of larger size.
49 //
50 // Ty          - The argument / return value type
51 // Context     - The associated ASTContext
52 // LLVMContext - The associated LLVMContext
53 static ABIArgInfo coerceToIntArray(QualType Ty,
54                                    ASTContext &Context,
55                                    llvm::LLVMContext &LLVMContext) {
56   // Alignment and Size are measured in bits.
57   const uint64_t Size = Context.getTypeSize(Ty);
58   const uint64_t Alignment = Context.getTypeAlign(Ty);
59   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
60   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
61   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
62 }
63 
64 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
65                                llvm::Value *Array,
66                                llvm::Value *Value,
67                                unsigned FirstIndex,
68                                unsigned LastIndex) {
69   // Alternatively, we could emit this as a loop in the source.
70   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
71     llvm::Value *Cell =
72         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
73     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
74   }
75 }
76 
77 static bool isAggregateTypeForABI(QualType T) {
78   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
79          T->isMemberFunctionPointerType();
80 }
81 
82 ABIArgInfo
83 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
84                                  llvm::Type *Padding) const {
85   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
86                                  ByRef, Realign, Padding);
87 }
88 
89 ABIArgInfo
90 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
91   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
92                                       /*ByRef*/ false, Realign);
93 }
94 
95 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
96                              QualType Ty) const {
97   return Address::invalid();
98 }
99 
100 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
101   if (Ty->isPromotableIntegerType())
102     return true;
103 
104   if (const auto *EIT = Ty->getAs<ExtIntType>())
105     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
106       return true;
107 
108   return false;
109 }
110 
111 ABIInfo::~ABIInfo() {}
112 
113 /// Does the given lowering require more than the given number of
114 /// registers when expanded?
115 ///
116 /// This is intended to be the basis of a reasonable basic implementation
117 /// of should{Pass,Return}IndirectlyForSwift.
118 ///
119 /// For most targets, a limit of four total registers is reasonable; this
120 /// limits the amount of code required in order to move around the value
121 /// in case it wasn't produced immediately prior to the call by the caller
122 /// (or wasn't produced in exactly the right registers) or isn't used
123 /// immediately within the callee.  But some targets may need to further
124 /// limit the register count due to an inability to support that many
125 /// return registers.
126 static bool occupiesMoreThan(CodeGenTypes &cgt,
127                              ArrayRef<llvm::Type*> scalarTypes,
128                              unsigned maxAllRegisters) {
129   unsigned intCount = 0, fpCount = 0;
130   for (llvm::Type *type : scalarTypes) {
131     if (type->isPointerTy()) {
132       intCount++;
133     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
134       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
135       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
136     } else {
137       assert(type->isVectorTy() || type->isFloatingPointTy());
138       fpCount++;
139     }
140   }
141 
142   return (intCount + fpCount > maxAllRegisters);
143 }
144 
145 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
146                                              llvm::Type *eltTy,
147                                              unsigned numElts) const {
148   // The default implementation of this assumes that the target guarantees
149   // 128-bit SIMD support but nothing more.
150   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
151 }
152 
153 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
154                                               CGCXXABI &CXXABI) {
155   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
156   if (!RD) {
157     if (!RT->getDecl()->canPassInRegisters())
158       return CGCXXABI::RAA_Indirect;
159     return CGCXXABI::RAA_Default;
160   }
161   return CXXABI.getRecordArgABI(RD);
162 }
163 
164 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
165                                               CGCXXABI &CXXABI) {
166   const RecordType *RT = T->getAs<RecordType>();
167   if (!RT)
168     return CGCXXABI::RAA_Default;
169   return getRecordArgABI(RT, CXXABI);
170 }
171 
172 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
173                                const ABIInfo &Info) {
174   QualType Ty = FI.getReturnType();
175 
176   if (const auto *RT = Ty->getAs<RecordType>())
177     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
178         !RT->getDecl()->canPassInRegisters()) {
179       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
180       return true;
181     }
182 
183   return CXXABI.classifyReturnType(FI);
184 }
185 
186 /// Pass transparent unions as if they were the type of the first element. Sema
187 /// should ensure that all elements of the union have the same "machine type".
188 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
189   if (const RecordType *UT = Ty->getAsUnionType()) {
190     const RecordDecl *UD = UT->getDecl();
191     if (UD->hasAttr<TransparentUnionAttr>()) {
192       assert(!UD->field_empty() && "sema created an empty transparent union");
193       return UD->field_begin()->getType();
194     }
195   }
196   return Ty;
197 }
198 
199 CGCXXABI &ABIInfo::getCXXABI() const {
200   return CGT.getCXXABI();
201 }
202 
203 ASTContext &ABIInfo::getContext() const {
204   return CGT.getContext();
205 }
206 
207 llvm::LLVMContext &ABIInfo::getVMContext() const {
208   return CGT.getLLVMContext();
209 }
210 
211 const llvm::DataLayout &ABIInfo::getDataLayout() const {
212   return CGT.getDataLayout();
213 }
214 
215 const TargetInfo &ABIInfo::getTarget() const {
216   return CGT.getTarget();
217 }
218 
219 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
220   return CGT.getCodeGenOpts();
221 }
222 
223 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
224 
225 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
226   return false;
227 }
228 
229 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
230                                                 uint64_t Members) const {
231   return false;
232 }
233 
234 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
235   raw_ostream &OS = llvm::errs();
236   OS << "(ABIArgInfo Kind=";
237   switch (TheKind) {
238   case Direct:
239     OS << "Direct Type=";
240     if (llvm::Type *Ty = getCoerceToType())
241       Ty->print(OS);
242     else
243       OS << "null";
244     break;
245   case Extend:
246     OS << "Extend";
247     break;
248   case Ignore:
249     OS << "Ignore";
250     break;
251   case InAlloca:
252     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
253     break;
254   case Indirect:
255     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
256        << " ByVal=" << getIndirectByVal()
257        << " Realign=" << getIndirectRealign();
258     break;
259   case Expand:
260     OS << "Expand";
261     break;
262   case CoerceAndExpand:
263     OS << "CoerceAndExpand Type=";
264     getCoerceAndExpandType()->print(OS);
265     break;
266   }
267   OS << ")\n";
268 }
269 
270 // Dynamically round a pointer up to a multiple of the given alignment.
271 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
272                                                   llvm::Value *Ptr,
273                                                   CharUnits Align) {
274   llvm::Value *PtrAsInt = Ptr;
275   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
276   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
277   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
278         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
279   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
280            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
281   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
282                                         Ptr->getType(),
283                                         Ptr->getName() + ".aligned");
284   return PtrAsInt;
285 }
286 
287 /// Emit va_arg for a platform using the common void* representation,
288 /// where arguments are simply emitted in an array of slots on the stack.
289 ///
290 /// This version implements the core direct-value passing rules.
291 ///
292 /// \param SlotSize - The size and alignment of a stack slot.
293 ///   Each argument will be allocated to a multiple of this number of
294 ///   slots, and all the slots will be aligned to this value.
295 /// \param AllowHigherAlign - The slot alignment is not a cap;
296 ///   an argument type with an alignment greater than the slot size
297 ///   will be emitted on a higher-alignment address, potentially
298 ///   leaving one or more empty slots behind as padding.  If this
299 ///   is false, the returned address might be less-aligned than
300 ///   DirectAlign.
301 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
302                                       Address VAListAddr,
303                                       llvm::Type *DirectTy,
304                                       CharUnits DirectSize,
305                                       CharUnits DirectAlign,
306                                       CharUnits SlotSize,
307                                       bool AllowHigherAlign) {
308   // Cast the element type to i8* if necessary.  Some platforms define
309   // va_list as a struct containing an i8* instead of just an i8*.
310   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
311     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
312 
313   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
314 
315   // If the CC aligns values higher than the slot size, do so if needed.
316   Address Addr = Address::invalid();
317   if (AllowHigherAlign && DirectAlign > SlotSize) {
318     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
319                                                  DirectAlign);
320   } else {
321     Addr = Address(Ptr, SlotSize);
322   }
323 
324   // Advance the pointer past the argument, then store that back.
325   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
326   Address NextPtr =
327       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
328   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
329 
330   // If the argument is smaller than a slot, and this is a big-endian
331   // target, the argument will be right-adjusted in its slot.
332   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
333       !DirectTy->isStructTy()) {
334     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
335   }
336 
337   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
338   return Addr;
339 }
340 
341 /// Emit va_arg for a platform using the common void* representation,
342 /// where arguments are simply emitted in an array of slots on the stack.
343 ///
344 /// \param IsIndirect - Values of this type are passed indirectly.
345 /// \param ValueInfo - The size and alignment of this type, generally
346 ///   computed with getContext().getTypeInfoInChars(ValueTy).
347 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
348 ///   Each argument will be allocated to a multiple of this number of
349 ///   slots, and all the slots will be aligned to this value.
350 /// \param AllowHigherAlign - The slot alignment is not a cap;
351 ///   an argument type with an alignment greater than the slot size
352 ///   will be emitted on a higher-alignment address, potentially
353 ///   leaving one or more empty slots behind as padding.
354 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
355                                 QualType ValueTy, bool IsIndirect,
356                                 std::pair<CharUnits, CharUnits> ValueInfo,
357                                 CharUnits SlotSizeAndAlign,
358                                 bool AllowHigherAlign) {
359   // The size and alignment of the value that was passed directly.
360   CharUnits DirectSize, DirectAlign;
361   if (IsIndirect) {
362     DirectSize = CGF.getPointerSize();
363     DirectAlign = CGF.getPointerAlign();
364   } else {
365     DirectSize = ValueInfo.first;
366     DirectAlign = ValueInfo.second;
367   }
368 
369   // Cast the address we've calculated to the right type.
370   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
371   if (IsIndirect)
372     DirectTy = DirectTy->getPointerTo(0);
373 
374   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
375                                         DirectSize, DirectAlign,
376                                         SlotSizeAndAlign,
377                                         AllowHigherAlign);
378 
379   if (IsIndirect) {
380     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
381   }
382 
383   return Addr;
384 
385 }
386 
387 static Address emitMergePHI(CodeGenFunction &CGF,
388                             Address Addr1, llvm::BasicBlock *Block1,
389                             Address Addr2, llvm::BasicBlock *Block2,
390                             const llvm::Twine &Name = "") {
391   assert(Addr1.getType() == Addr2.getType());
392   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
393   PHI->addIncoming(Addr1.getPointer(), Block1);
394   PHI->addIncoming(Addr2.getPointer(), Block2);
395   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
396   return Address(PHI, Align);
397 }
398 
399 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
400 
401 // If someone can figure out a general rule for this, that would be great.
402 // It's probably just doomed to be platform-dependent, though.
403 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
404   // Verified for:
405   //   x86-64     FreeBSD, Linux, Darwin
406   //   x86-32     FreeBSD, Linux, Darwin
407   //   PowerPC    Linux, Darwin
408   //   ARM        Darwin (*not* EABI)
409   //   AArch64    Linux
410   return 32;
411 }
412 
413 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
414                                      const FunctionNoProtoType *fnType) const {
415   // The following conventions are known to require this to be false:
416   //   x86_stdcall
417   //   MIPS
418   // For everything else, we just prefer false unless we opt out.
419   return false;
420 }
421 
422 void
423 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
424                                              llvm::SmallString<24> &Opt) const {
425   // This assumes the user is passing a library name like "rt" instead of a
426   // filename like "librt.a/so", and that they don't care whether it's static or
427   // dynamic.
428   Opt = "-l";
429   Opt += Lib;
430 }
431 
432 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
433   // OpenCL kernels are called via an explicit runtime API with arguments
434   // set with clSetKernelArg(), not as normal sub-functions.
435   // Return SPIR_KERNEL by default as the kernel calling convention to
436   // ensure the fingerprint is fixed such way that each OpenCL argument
437   // gets one matching argument in the produced kernel function argument
438   // list to enable feasible implementation of clSetKernelArg() with
439   // aggregates etc. In case we would use the default C calling conv here,
440   // clSetKernelArg() might break depending on the target-specific
441   // conventions; different targets might split structs passed as values
442   // to multiple function arguments etc.
443   return llvm::CallingConv::SPIR_KERNEL;
444 }
445 
446 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
447     llvm::PointerType *T, QualType QT) const {
448   return llvm::ConstantPointerNull::get(T);
449 }
450 
451 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
452                                                    const VarDecl *D) const {
453   assert(!CGM.getLangOpts().OpenCL &&
454          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
455          "Address space agnostic languages only");
456   return D ? D->getType().getAddressSpace() : LangAS::Default;
457 }
458 
459 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
460     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
461     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) 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   if (auto *C = dyn_cast<llvm::Constant>(Src))
465     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
466   // Try to preserve the source's name to make IR more readable.
467   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
468       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
469 }
470 
471 llvm::Constant *
472 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
473                                         LangAS SrcAddr, LangAS DestAddr,
474                                         llvm::Type *DestTy) const {
475   // Since target may map different address spaces in AST to the same address
476   // space, an address space conversion may end up as a bitcast.
477   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
478 }
479 
480 llvm::SyncScope::ID
481 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
482                                       SyncScope Scope,
483                                       llvm::AtomicOrdering Ordering,
484                                       llvm::LLVMContext &Ctx) const {
485   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
486 }
487 
488 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
489 
490 /// isEmptyField - Return true iff a the field is "empty", that is it
491 /// is an unnamed bit-field or an (array of) empty record(s).
492 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
493                          bool AllowArrays) {
494   if (FD->isUnnamedBitfield())
495     return true;
496 
497   QualType FT = FD->getType();
498 
499   // Constant arrays of empty records count as empty, strip them off.
500   // Constant arrays of zero length always count as empty.
501   if (AllowArrays)
502     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
503       if (AT->getSize() == 0)
504         return true;
505       FT = AT->getElementType();
506     }
507 
508   const RecordType *RT = FT->getAs<RecordType>();
509   if (!RT)
510     return false;
511 
512   // C++ record fields are never empty, at least in the Itanium ABI.
513   //
514   // FIXME: We should use a predicate for whether this behavior is true in the
515   // current ABI.
516   if (isa<CXXRecordDecl>(RT->getDecl()))
517     return false;
518 
519   return isEmptyRecord(Context, FT, AllowArrays);
520 }
521 
522 /// isEmptyRecord - Return true iff a structure contains only empty
523 /// fields. Note that a structure with a flexible array member is not
524 /// considered empty.
525 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
526   const RecordType *RT = T->getAs<RecordType>();
527   if (!RT)
528     return false;
529   const RecordDecl *RD = RT->getDecl();
530   if (RD->hasFlexibleArrayMember())
531     return false;
532 
533   // If this is a C++ record, check the bases first.
534   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
535     for (const auto &I : CXXRD->bases())
536       if (!isEmptyRecord(Context, I.getType(), true))
537         return false;
538 
539   for (const auto *I : RD->fields())
540     if (!isEmptyField(Context, I, AllowArrays))
541       return false;
542   return true;
543 }
544 
545 /// isSingleElementStruct - Determine if a structure is a "single
546 /// element struct", i.e. it has exactly one non-empty field or
547 /// exactly one field which is itself a single element
548 /// struct. Structures with flexible array members are never
549 /// considered single element structs.
550 ///
551 /// \return The field declaration for the single non-empty field, if
552 /// it exists.
553 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
554   const RecordType *RT = T->getAs<RecordType>();
555   if (!RT)
556     return nullptr;
557 
558   const RecordDecl *RD = RT->getDecl();
559   if (RD->hasFlexibleArrayMember())
560     return nullptr;
561 
562   const Type *Found = nullptr;
563 
564   // If this is a C++ record, check the bases first.
565   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
566     for (const auto &I : CXXRD->bases()) {
567       // Ignore empty records.
568       if (isEmptyRecord(Context, I.getType(), true))
569         continue;
570 
571       // If we already found an element then this isn't a single-element struct.
572       if (Found)
573         return nullptr;
574 
575       // If this is non-empty and not a single element struct, the composite
576       // cannot be a single element struct.
577       Found = isSingleElementStruct(I.getType(), Context);
578       if (!Found)
579         return nullptr;
580     }
581   }
582 
583   // Check for single element.
584   for (const auto *FD : RD->fields()) {
585     QualType FT = FD->getType();
586 
587     // Ignore empty fields.
588     if (isEmptyField(Context, FD, true))
589       continue;
590 
591     // If we already found an element then this isn't a single-element
592     // struct.
593     if (Found)
594       return nullptr;
595 
596     // Treat single element arrays as the element.
597     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
598       if (AT->getSize().getZExtValue() != 1)
599         break;
600       FT = AT->getElementType();
601     }
602 
603     if (!isAggregateTypeForABI(FT)) {
604       Found = FT.getTypePtr();
605     } else {
606       Found = isSingleElementStruct(FT, Context);
607       if (!Found)
608         return nullptr;
609     }
610   }
611 
612   // We don't consider a struct a single-element struct if it has
613   // padding beyond the element type.
614   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
615     return nullptr;
616 
617   return Found;
618 }
619 
620 namespace {
621 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
622                        const ABIArgInfo &AI) {
623   // This default implementation defers to the llvm backend's va_arg
624   // instruction. It can handle only passing arguments directly
625   // (typically only handled in the backend for primitive types), or
626   // aggregates passed indirectly by pointer (NOTE: if the "byval"
627   // flag has ABI impact in the callee, this implementation cannot
628   // work.)
629 
630   // Only a few cases are covered here at the moment -- those needed
631   // by the default abi.
632   llvm::Value *Val;
633 
634   if (AI.isIndirect()) {
635     assert(!AI.getPaddingType() &&
636            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
637     assert(
638         !AI.getIndirectRealign() &&
639         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
640 
641     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
642     CharUnits TyAlignForABI = TyInfo.second;
643 
644     llvm::Type *BaseTy =
645         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
646     llvm::Value *Addr =
647         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
648     return Address(Addr, TyAlignForABI);
649   } else {
650     assert((AI.isDirect() || AI.isExtend()) &&
651            "Unexpected ArgInfo Kind in generic VAArg emitter!");
652 
653     assert(!AI.getInReg() &&
654            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
655     assert(!AI.getPaddingType() &&
656            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
657     assert(!AI.getDirectOffset() &&
658            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
659     assert(!AI.getCoerceToType() &&
660            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
661 
662     Address Temp = CGF.CreateMemTemp(Ty, "varet");
663     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
664     CGF.Builder.CreateStore(Val, Temp);
665     return Temp;
666   }
667 }
668 
669 /// DefaultABIInfo - The default implementation for ABI specific
670 /// details. This implementation provides information which results in
671 /// self-consistent and sensible LLVM IR generation, but does not
672 /// conform to any particular ABI.
673 class DefaultABIInfo : public ABIInfo {
674 public:
675   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
676 
677   ABIArgInfo classifyReturnType(QualType RetTy) const;
678   ABIArgInfo classifyArgumentType(QualType RetTy) const;
679 
680   void computeInfo(CGFunctionInfo &FI) const override {
681     if (!getCXXABI().classifyReturnType(FI))
682       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
683     for (auto &I : FI.arguments())
684       I.info = classifyArgumentType(I.type);
685   }
686 
687   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
688                     QualType Ty) const override {
689     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
690   }
691 };
692 
693 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
694 public:
695   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
696       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
697 };
698 
699 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
700   Ty = useFirstFieldIfTransparentUnion(Ty);
701 
702   if (isAggregateTypeForABI(Ty)) {
703     // Records with non-trivial destructors/copy-constructors should not be
704     // passed by value.
705     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
706       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
707 
708     return getNaturalAlignIndirect(Ty);
709   }
710 
711   // Treat an enum type as its underlying type.
712   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
713     Ty = EnumTy->getDecl()->getIntegerType();
714 
715   ASTContext &Context = getContext();
716   if (const auto *EIT = Ty->getAs<ExtIntType>())
717     if (EIT->getNumBits() >
718         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
719                                 ? Context.Int128Ty
720                                 : Context.LongLongTy))
721       return getNaturalAlignIndirect(Ty);
722 
723   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
724                                             : ABIArgInfo::getDirect());
725 }
726 
727 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
728   if (RetTy->isVoidType())
729     return ABIArgInfo::getIgnore();
730 
731   if (isAggregateTypeForABI(RetTy))
732     return getNaturalAlignIndirect(RetTy);
733 
734   // Treat an enum type as its underlying type.
735   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
736     RetTy = EnumTy->getDecl()->getIntegerType();
737 
738   if (const auto *EIT = RetTy->getAs<ExtIntType>())
739     if (EIT->getNumBits() >
740         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
741                                      ? getContext().Int128Ty
742                                      : getContext().LongLongTy))
743       return getNaturalAlignIndirect(RetTy);
744 
745   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
746                                                : ABIArgInfo::getDirect());
747 }
748 
749 //===----------------------------------------------------------------------===//
750 // WebAssembly ABI Implementation
751 //
752 // This is a very simple ABI that relies a lot on DefaultABIInfo.
753 //===----------------------------------------------------------------------===//
754 
755 class WebAssemblyABIInfo final : public SwiftABIInfo {
756 public:
757   enum ABIKind {
758     MVP = 0,
759     ExperimentalMV = 1,
760   };
761 
762 private:
763   DefaultABIInfo defaultInfo;
764   ABIKind Kind;
765 
766 public:
767   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
768       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
769 
770 private:
771   ABIArgInfo classifyReturnType(QualType RetTy) const;
772   ABIArgInfo classifyArgumentType(QualType Ty) const;
773 
774   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
775   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
776   // overload them.
777   void computeInfo(CGFunctionInfo &FI) const override {
778     if (!getCXXABI().classifyReturnType(FI))
779       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
780     for (auto &Arg : FI.arguments())
781       Arg.info = classifyArgumentType(Arg.type);
782   }
783 
784   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
785                     QualType Ty) const override;
786 
787   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
788                                     bool asReturnValue) const override {
789     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
790   }
791 
792   bool isSwiftErrorInRegister() const override {
793     return false;
794   }
795 };
796 
797 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
798 public:
799   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
800                                         WebAssemblyABIInfo::ABIKind K)
801       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
802 
803   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
804                            CodeGen::CodeGenModule &CGM) const override {
805     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
806     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
807       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
808         llvm::Function *Fn = cast<llvm::Function>(GV);
809         llvm::AttrBuilder B;
810         B.addAttribute("wasm-import-module", Attr->getImportModule());
811         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
812       }
813       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
814         llvm::Function *Fn = cast<llvm::Function>(GV);
815         llvm::AttrBuilder B;
816         B.addAttribute("wasm-import-name", Attr->getImportName());
817         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
818       }
819       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
820         llvm::Function *Fn = cast<llvm::Function>(GV);
821         llvm::AttrBuilder B;
822         B.addAttribute("wasm-export-name", Attr->getExportName());
823         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
824       }
825     }
826 
827     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
828       llvm::Function *Fn = cast<llvm::Function>(GV);
829       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
830         Fn->addFnAttr("no-prototype");
831     }
832   }
833 };
834 
835 /// Classify argument of given type \p Ty.
836 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
837   Ty = useFirstFieldIfTransparentUnion(Ty);
838 
839   if (isAggregateTypeForABI(Ty)) {
840     // Records with non-trivial destructors/copy-constructors should not be
841     // passed by value.
842     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
843       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
844     // Ignore empty structs/unions.
845     if (isEmptyRecord(getContext(), Ty, true))
846       return ABIArgInfo::getIgnore();
847     // Lower single-element structs to just pass a regular value. TODO: We
848     // could do reasonable-size multiple-element structs too, using getExpand(),
849     // though watch out for things like bitfields.
850     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
851       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
852     // For the experimental multivalue ABI, fully expand all other aggregates
853     if (Kind == ABIKind::ExperimentalMV) {
854       const RecordType *RT = Ty->getAs<RecordType>();
855       assert(RT);
856       bool HasBitField = false;
857       for (auto *Field : RT->getDecl()->fields()) {
858         if (Field->isBitField()) {
859           HasBitField = true;
860           break;
861         }
862       }
863       if (!HasBitField)
864         return ABIArgInfo::getExpand();
865     }
866   }
867 
868   // Otherwise just do the default thing.
869   return defaultInfo.classifyArgumentType(Ty);
870 }
871 
872 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
873   if (isAggregateTypeForABI(RetTy)) {
874     // Records with non-trivial destructors/copy-constructors should not be
875     // returned by value.
876     if (!getRecordArgABI(RetTy, getCXXABI())) {
877       // Ignore empty structs/unions.
878       if (isEmptyRecord(getContext(), RetTy, true))
879         return ABIArgInfo::getIgnore();
880       // Lower single-element structs to just return a regular value. TODO: We
881       // could do reasonable-size multiple-element structs too, using
882       // ABIArgInfo::getDirect().
883       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
884         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
885       // For the experimental multivalue ABI, return all other aggregates
886       if (Kind == ABIKind::ExperimentalMV)
887         return ABIArgInfo::getDirect();
888     }
889   }
890 
891   // Otherwise just do the default thing.
892   return defaultInfo.classifyReturnType(RetTy);
893 }
894 
895 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
896                                       QualType Ty) const {
897   bool IsIndirect = isAggregateTypeForABI(Ty) &&
898                     !isEmptyRecord(getContext(), Ty, true) &&
899                     !isSingleElementStruct(Ty, getContext());
900   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
901                           getContext().getTypeInfoInChars(Ty),
902                           CharUnits::fromQuantity(4),
903                           /*AllowHigherAlign=*/true);
904 }
905 
906 //===----------------------------------------------------------------------===//
907 // le32/PNaCl bitcode ABI Implementation
908 //
909 // This is a simplified version of the x86_32 ABI.  Arguments and return values
910 // are always passed on the stack.
911 //===----------------------------------------------------------------------===//
912 
913 class PNaClABIInfo : public ABIInfo {
914  public:
915   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
916 
917   ABIArgInfo classifyReturnType(QualType RetTy) const;
918   ABIArgInfo classifyArgumentType(QualType RetTy) const;
919 
920   void computeInfo(CGFunctionInfo &FI) const override;
921   Address EmitVAArg(CodeGenFunction &CGF,
922                     Address VAListAddr, QualType Ty) const override;
923 };
924 
925 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
926  public:
927    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
928        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
929 };
930 
931 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
932   if (!getCXXABI().classifyReturnType(FI))
933     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
934 
935   for (auto &I : FI.arguments())
936     I.info = classifyArgumentType(I.type);
937 }
938 
939 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
940                                 QualType Ty) const {
941   // The PNaCL ABI is a bit odd, in that varargs don't use normal
942   // function classification. Structs get passed directly for varargs
943   // functions, through a rewriting transform in
944   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
945   // this target to actually support a va_arg instructions with an
946   // aggregate type, unlike other targets.
947   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
948 }
949 
950 /// Classify argument of given type \p Ty.
951 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
952   if (isAggregateTypeForABI(Ty)) {
953     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
954       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
955     return getNaturalAlignIndirect(Ty);
956   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
957     // Treat an enum type as its underlying type.
958     Ty = EnumTy->getDecl()->getIntegerType();
959   } else if (Ty->isFloatingType()) {
960     // Floating-point types don't go inreg.
961     return ABIArgInfo::getDirect();
962   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
963     // Treat extended integers as integers if <=64, otherwise pass indirectly.
964     if (EIT->getNumBits() > 64)
965       return getNaturalAlignIndirect(Ty);
966     return ABIArgInfo::getDirect();
967   }
968 
969   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
970                                             : ABIArgInfo::getDirect());
971 }
972 
973 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
974   if (RetTy->isVoidType())
975     return ABIArgInfo::getIgnore();
976 
977   // In the PNaCl ABI we always return records/structures on the stack.
978   if (isAggregateTypeForABI(RetTy))
979     return getNaturalAlignIndirect(RetTy);
980 
981   // Treat extended integers as integers if <=64, otherwise pass indirectly.
982   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
983     if (EIT->getNumBits() > 64)
984       return getNaturalAlignIndirect(RetTy);
985     return ABIArgInfo::getDirect();
986   }
987 
988   // Treat an enum type as its underlying type.
989   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
990     RetTy = EnumTy->getDecl()->getIntegerType();
991 
992   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
993                                                : ABIArgInfo::getDirect());
994 }
995 
996 /// IsX86_MMXType - Return true if this is an MMX type.
997 bool IsX86_MMXType(llvm::Type *IRType) {
998   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
999   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1000     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1001     IRType->getScalarSizeInBits() != 64;
1002 }
1003 
1004 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1005                                           StringRef Constraint,
1006                                           llvm::Type* Ty) {
1007   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1008                      .Cases("y", "&y", "^Ym", true)
1009                      .Default(false);
1010   if (IsMMXCons && Ty->isVectorTy()) {
1011     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1012         64) {
1013       // Invalid MMX constraint
1014       return nullptr;
1015     }
1016 
1017     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1018   }
1019 
1020   // No operation needed
1021   return Ty;
1022 }
1023 
1024 /// Returns true if this type can be passed in SSE registers with the
1025 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1026 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1027   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1028     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1029       if (BT->getKind() == BuiltinType::LongDouble) {
1030         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1031             &llvm::APFloat::x87DoubleExtended())
1032           return false;
1033       }
1034       return true;
1035     }
1036   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1037     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1038     // registers specially.
1039     unsigned VecSize = Context.getTypeSize(VT);
1040     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1041       return true;
1042   }
1043   return false;
1044 }
1045 
1046 /// Returns true if this aggregate is small enough to be passed in SSE registers
1047 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1048 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1049   return NumMembers <= 4;
1050 }
1051 
1052 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1053 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1054   auto AI = ABIArgInfo::getDirect(T);
1055   AI.setInReg(true);
1056   AI.setCanBeFlattened(false);
1057   return AI;
1058 }
1059 
1060 //===----------------------------------------------------------------------===//
1061 // X86-32 ABI Implementation
1062 //===----------------------------------------------------------------------===//
1063 
1064 /// Similar to llvm::CCState, but for Clang.
1065 struct CCState {
1066   CCState(CGFunctionInfo &FI)
1067       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1068 
1069   llvm::SmallBitVector IsPreassigned;
1070   unsigned CC = CallingConv::CC_C;
1071   unsigned FreeRegs = 0;
1072   unsigned FreeSSERegs = 0;
1073 };
1074 
1075 enum {
1076   // Vectorcall only allows the first 6 parameters to be passed in registers.
1077   VectorcallMaxParamNumAsReg = 6
1078 };
1079 
1080 /// X86_32ABIInfo - The X86-32 ABI information.
1081 class X86_32ABIInfo : public SwiftABIInfo {
1082   enum Class {
1083     Integer,
1084     Float
1085   };
1086 
1087   static const unsigned MinABIStackAlignInBytes = 4;
1088 
1089   bool IsDarwinVectorABI;
1090   bool IsRetSmallStructInRegABI;
1091   bool IsWin32StructABI;
1092   bool IsSoftFloatABI;
1093   bool IsMCUABI;
1094   unsigned DefaultNumRegisterParameters;
1095 
1096   static bool isRegisterSize(unsigned Size) {
1097     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1098   }
1099 
1100   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1101     // FIXME: Assumes vectorcall is in use.
1102     return isX86VectorTypeForVectorCall(getContext(), Ty);
1103   }
1104 
1105   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1106                                          uint64_t NumMembers) const override {
1107     // FIXME: Assumes vectorcall is in use.
1108     return isX86VectorCallAggregateSmallEnough(NumMembers);
1109   }
1110 
1111   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1112 
1113   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1114   /// such that the argument will be passed in memory.
1115   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1116 
1117   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1118 
1119   /// Return the alignment to use for the given type on the stack.
1120   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1121 
1122   Class classify(QualType Ty) const;
1123   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1124   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1125 
1126   /// Updates the number of available free registers, returns
1127   /// true if any registers were allocated.
1128   bool updateFreeRegs(QualType Ty, CCState &State) const;
1129 
1130   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1131                                 bool &NeedsPadding) const;
1132   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1133 
1134   bool canExpandIndirectArgument(QualType Ty) const;
1135 
1136   /// Rewrite the function info so that all memory arguments use
1137   /// inalloca.
1138   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1139 
1140   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1141                            CharUnits &StackOffset, ABIArgInfo &Info,
1142                            QualType Type) const;
1143   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1144 
1145 public:
1146 
1147   void computeInfo(CGFunctionInfo &FI) const override;
1148   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1149                     QualType Ty) const override;
1150 
1151   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1152                 bool RetSmallStructInRegABI, bool Win32StructABI,
1153                 unsigned NumRegisterParameters, bool SoftFloatABI)
1154     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1155       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1156       IsWin32StructABI(Win32StructABI),
1157       IsSoftFloatABI(SoftFloatABI),
1158       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1159       DefaultNumRegisterParameters(NumRegisterParameters) {}
1160 
1161   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1162                                     bool asReturnValue) const override {
1163     // LLVM's x86-32 lowering currently only assigns up to three
1164     // integer registers and three fp registers.  Oddly, it'll use up to
1165     // four vector registers for vectors, but those can overlap with the
1166     // scalar registers.
1167     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1168   }
1169 
1170   bool isSwiftErrorInRegister() const override {
1171     // x86-32 lowering does not support passing swifterror in a register.
1172     return false;
1173   }
1174 };
1175 
1176 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1177 public:
1178   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1179                           bool RetSmallStructInRegABI, bool Win32StructABI,
1180                           unsigned NumRegisterParameters, bool SoftFloatABI)
1181       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1182             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1183             NumRegisterParameters, SoftFloatABI)) {}
1184 
1185   static bool isStructReturnInRegABI(
1186       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1187 
1188   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1189                            CodeGen::CodeGenModule &CGM) const override;
1190 
1191   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1192     // Darwin uses different dwarf register numbers for EH.
1193     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1194     return 4;
1195   }
1196 
1197   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1198                                llvm::Value *Address) const override;
1199 
1200   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1201                                   StringRef Constraint,
1202                                   llvm::Type* Ty) const override {
1203     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1204   }
1205 
1206   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1207                                 std::string &Constraints,
1208                                 std::vector<llvm::Type *> &ResultRegTypes,
1209                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1210                                 std::vector<LValue> &ResultRegDests,
1211                                 std::string &AsmString,
1212                                 unsigned NumOutputs) const override;
1213 
1214   llvm::Constant *
1215   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1216     unsigned Sig = (0xeb << 0) |  // jmp rel8
1217                    (0x06 << 8) |  //           .+0x08
1218                    ('v' << 16) |
1219                    ('2' << 24);
1220     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1221   }
1222 
1223   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1224     return "movl\t%ebp, %ebp"
1225            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1226   }
1227 };
1228 
1229 }
1230 
1231 /// Rewrite input constraint references after adding some output constraints.
1232 /// In the case where there is one output and one input and we add one output,
1233 /// we need to replace all operand references greater than or equal to 1:
1234 ///     mov $0, $1
1235 ///     mov eax, $1
1236 /// The result will be:
1237 ///     mov $0, $2
1238 ///     mov eax, $2
1239 static void rewriteInputConstraintReferences(unsigned FirstIn,
1240                                              unsigned NumNewOuts,
1241                                              std::string &AsmString) {
1242   std::string Buf;
1243   llvm::raw_string_ostream OS(Buf);
1244   size_t Pos = 0;
1245   while (Pos < AsmString.size()) {
1246     size_t DollarStart = AsmString.find('$', Pos);
1247     if (DollarStart == std::string::npos)
1248       DollarStart = AsmString.size();
1249     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1250     if (DollarEnd == std::string::npos)
1251       DollarEnd = AsmString.size();
1252     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1253     Pos = DollarEnd;
1254     size_t NumDollars = DollarEnd - DollarStart;
1255     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1256       // We have an operand reference.
1257       size_t DigitStart = Pos;
1258       if (AsmString[DigitStart] == '{') {
1259         OS << '{';
1260         ++DigitStart;
1261       }
1262       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1263       if (DigitEnd == std::string::npos)
1264         DigitEnd = AsmString.size();
1265       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1266       unsigned OperandIndex;
1267       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1268         if (OperandIndex >= FirstIn)
1269           OperandIndex += NumNewOuts;
1270         OS << OperandIndex;
1271       } else {
1272         OS << OperandStr;
1273       }
1274       Pos = DigitEnd;
1275     }
1276   }
1277   AsmString = std::move(OS.str());
1278 }
1279 
1280 /// Add output constraints for EAX:EDX because they are return registers.
1281 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1282     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1283     std::vector<llvm::Type *> &ResultRegTypes,
1284     std::vector<llvm::Type *> &ResultTruncRegTypes,
1285     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1286     unsigned NumOutputs) const {
1287   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1288 
1289   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1290   // larger.
1291   if (!Constraints.empty())
1292     Constraints += ',';
1293   if (RetWidth <= 32) {
1294     Constraints += "={eax}";
1295     ResultRegTypes.push_back(CGF.Int32Ty);
1296   } else {
1297     // Use the 'A' constraint for EAX:EDX.
1298     Constraints += "=A";
1299     ResultRegTypes.push_back(CGF.Int64Ty);
1300   }
1301 
1302   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1303   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1304   ResultTruncRegTypes.push_back(CoerceTy);
1305 
1306   // Coerce the integer by bitcasting the return slot pointer.
1307   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1308                                                   CoerceTy->getPointerTo()));
1309   ResultRegDests.push_back(ReturnSlot);
1310 
1311   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1312 }
1313 
1314 /// shouldReturnTypeInRegister - Determine if the given type should be
1315 /// returned in a register (for the Darwin and MCU ABI).
1316 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1317                                                ASTContext &Context) const {
1318   uint64_t Size = Context.getTypeSize(Ty);
1319 
1320   // For i386, type must be register sized.
1321   // For the MCU ABI, it only needs to be <= 8-byte
1322   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1323    return false;
1324 
1325   if (Ty->isVectorType()) {
1326     // 64- and 128- bit vectors inside structures are not returned in
1327     // registers.
1328     if (Size == 64 || Size == 128)
1329       return false;
1330 
1331     return true;
1332   }
1333 
1334   // If this is a builtin, pointer, enum, complex type, member pointer, or
1335   // member function pointer it is ok.
1336   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1337       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1338       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1339     return true;
1340 
1341   // Arrays are treated like records.
1342   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1343     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1344 
1345   // Otherwise, it must be a record type.
1346   const RecordType *RT = Ty->getAs<RecordType>();
1347   if (!RT) return false;
1348 
1349   // FIXME: Traverse bases here too.
1350 
1351   // Structure types are passed in register if all fields would be
1352   // passed in a register.
1353   for (const auto *FD : RT->getDecl()->fields()) {
1354     // Empty fields are ignored.
1355     if (isEmptyField(Context, FD, true))
1356       continue;
1357 
1358     // Check fields recursively.
1359     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1360       return false;
1361   }
1362   return true;
1363 }
1364 
1365 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1366   // Treat complex types as the element type.
1367   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1368     Ty = CTy->getElementType();
1369 
1370   // Check for a type which we know has a simple scalar argument-passing
1371   // convention without any padding.  (We're specifically looking for 32
1372   // and 64-bit integer and integer-equivalents, float, and double.)
1373   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1374       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1375     return false;
1376 
1377   uint64_t Size = Context.getTypeSize(Ty);
1378   return Size == 32 || Size == 64;
1379 }
1380 
1381 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1382                           uint64_t &Size) {
1383   for (const auto *FD : RD->fields()) {
1384     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1385     // argument is smaller than 32-bits, expanding the struct will create
1386     // alignment padding.
1387     if (!is32Or64BitBasicType(FD->getType(), Context))
1388       return false;
1389 
1390     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1391     // how to expand them yet, and the predicate for telling if a bitfield still
1392     // counts as "basic" is more complicated than what we were doing previously.
1393     if (FD->isBitField())
1394       return false;
1395 
1396     Size += Context.getTypeSize(FD->getType());
1397   }
1398   return true;
1399 }
1400 
1401 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1402                                  uint64_t &Size) {
1403   // Don't do this if there are any non-empty bases.
1404   for (const CXXBaseSpecifier &Base : RD->bases()) {
1405     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1406                               Size))
1407       return false;
1408   }
1409   if (!addFieldSizes(Context, RD, Size))
1410     return false;
1411   return true;
1412 }
1413 
1414 /// Test whether an argument type which is to be passed indirectly (on the
1415 /// stack) would have the equivalent layout if it was expanded into separate
1416 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1417 /// optimizations.
1418 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1419   // We can only expand structure types.
1420   const RecordType *RT = Ty->getAs<RecordType>();
1421   if (!RT)
1422     return false;
1423   const RecordDecl *RD = RT->getDecl();
1424   uint64_t Size = 0;
1425   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1426     if (!IsWin32StructABI) {
1427       // On non-Windows, we have to conservatively match our old bitcode
1428       // prototypes in order to be ABI-compatible at the bitcode level.
1429       if (!CXXRD->isCLike())
1430         return false;
1431     } else {
1432       // Don't do this for dynamic classes.
1433       if (CXXRD->isDynamicClass())
1434         return false;
1435     }
1436     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1437       return false;
1438   } else {
1439     if (!addFieldSizes(getContext(), RD, Size))
1440       return false;
1441   }
1442 
1443   // We can do this if there was no alignment padding.
1444   return Size == getContext().getTypeSize(Ty);
1445 }
1446 
1447 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1448   // If the return value is indirect, then the hidden argument is consuming one
1449   // integer register.
1450   if (State.FreeRegs) {
1451     --State.FreeRegs;
1452     if (!IsMCUABI)
1453       return getNaturalAlignIndirectInReg(RetTy);
1454   }
1455   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1456 }
1457 
1458 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1459                                              CCState &State) const {
1460   if (RetTy->isVoidType())
1461     return ABIArgInfo::getIgnore();
1462 
1463   const Type *Base = nullptr;
1464   uint64_t NumElts = 0;
1465   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1466        State.CC == llvm::CallingConv::X86_RegCall) &&
1467       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1468     // The LLVM struct type for such an aggregate should lower properly.
1469     return ABIArgInfo::getDirect();
1470   }
1471 
1472   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1473     // On Darwin, some vectors are returned in registers.
1474     if (IsDarwinVectorABI) {
1475       uint64_t Size = getContext().getTypeSize(RetTy);
1476 
1477       // 128-bit vectors are a special case; they are returned in
1478       // registers and we need to make sure to pick a type the LLVM
1479       // backend will like.
1480       if (Size == 128)
1481         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1482             llvm::Type::getInt64Ty(getVMContext()), 2));
1483 
1484       // Always return in register if it fits in a general purpose
1485       // register, or if it is 64 bits and has a single element.
1486       if ((Size == 8 || Size == 16 || Size == 32) ||
1487           (Size == 64 && VT->getNumElements() == 1))
1488         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1489                                                             Size));
1490 
1491       return getIndirectReturnResult(RetTy, State);
1492     }
1493 
1494     return ABIArgInfo::getDirect();
1495   }
1496 
1497   if (isAggregateTypeForABI(RetTy)) {
1498     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1499       // Structures with flexible arrays are always indirect.
1500       if (RT->getDecl()->hasFlexibleArrayMember())
1501         return getIndirectReturnResult(RetTy, State);
1502     }
1503 
1504     // If specified, structs and unions are always indirect.
1505     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1506       return getIndirectReturnResult(RetTy, State);
1507 
1508     // Ignore empty structs/unions.
1509     if (isEmptyRecord(getContext(), RetTy, true))
1510       return ABIArgInfo::getIgnore();
1511 
1512     // Small structures which are register sized are generally returned
1513     // in a register.
1514     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1515       uint64_t Size = getContext().getTypeSize(RetTy);
1516 
1517       // As a special-case, if the struct is a "single-element" struct, and
1518       // the field is of type "float" or "double", return it in a
1519       // floating-point register. (MSVC does not apply this special case.)
1520       // We apply a similar transformation for pointer types to improve the
1521       // quality of the generated IR.
1522       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1523         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1524             || SeltTy->hasPointerRepresentation())
1525           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1526 
1527       // FIXME: We should be able to narrow this integer in cases with dead
1528       // padding.
1529       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1530     }
1531 
1532     return getIndirectReturnResult(RetTy, State);
1533   }
1534 
1535   // Treat an enum type as its underlying type.
1536   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1537     RetTy = EnumTy->getDecl()->getIntegerType();
1538 
1539   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1540     if (EIT->getNumBits() > 64)
1541       return getIndirectReturnResult(RetTy, State);
1542 
1543   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1544                                                : ABIArgInfo::getDirect());
1545 }
1546 
1547 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1548   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1549 }
1550 
1551 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1552   const RecordType *RT = Ty->getAs<RecordType>();
1553   if (!RT)
1554     return 0;
1555   const RecordDecl *RD = RT->getDecl();
1556 
1557   // If this is a C++ record, check the bases first.
1558   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1559     for (const auto &I : CXXRD->bases())
1560       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1561         return false;
1562 
1563   for (const auto *i : RD->fields()) {
1564     QualType FT = i->getType();
1565 
1566     if (isSIMDVectorType(Context, FT))
1567       return true;
1568 
1569     if (isRecordWithSIMDVectorType(Context, FT))
1570       return true;
1571   }
1572 
1573   return false;
1574 }
1575 
1576 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1577                                                  unsigned Align) const {
1578   // Otherwise, if the alignment is less than or equal to the minimum ABI
1579   // alignment, just use the default; the backend will handle this.
1580   if (Align <= MinABIStackAlignInBytes)
1581     return 0; // Use default alignment.
1582 
1583   // On non-Darwin, the stack type alignment is always 4.
1584   if (!IsDarwinVectorABI) {
1585     // Set explicit alignment, since we may need to realign the top.
1586     return MinABIStackAlignInBytes;
1587   }
1588 
1589   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1590   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1591                       isRecordWithSIMDVectorType(getContext(), Ty)))
1592     return 16;
1593 
1594   return MinABIStackAlignInBytes;
1595 }
1596 
1597 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1598                                             CCState &State) const {
1599   if (!ByVal) {
1600     if (State.FreeRegs) {
1601       --State.FreeRegs; // Non-byval indirects just use one pointer.
1602       if (!IsMCUABI)
1603         return getNaturalAlignIndirectInReg(Ty);
1604     }
1605     return getNaturalAlignIndirect(Ty, false);
1606   }
1607 
1608   // Compute the byval alignment.
1609   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1610   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1611   if (StackAlign == 0)
1612     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1613 
1614   // If the stack alignment is less than the type alignment, realign the
1615   // argument.
1616   bool Realign = TypeAlign > StackAlign;
1617   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1618                                  /*ByVal=*/true, Realign);
1619 }
1620 
1621 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1622   const Type *T = isSingleElementStruct(Ty, getContext());
1623   if (!T)
1624     T = Ty.getTypePtr();
1625 
1626   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1627     BuiltinType::Kind K = BT->getKind();
1628     if (K == BuiltinType::Float || K == BuiltinType::Double)
1629       return Float;
1630   }
1631   return Integer;
1632 }
1633 
1634 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1635   if (!IsSoftFloatABI) {
1636     Class C = classify(Ty);
1637     if (C == Float)
1638       return false;
1639   }
1640 
1641   unsigned Size = getContext().getTypeSize(Ty);
1642   unsigned SizeInRegs = (Size + 31) / 32;
1643 
1644   if (SizeInRegs == 0)
1645     return false;
1646 
1647   if (!IsMCUABI) {
1648     if (SizeInRegs > State.FreeRegs) {
1649       State.FreeRegs = 0;
1650       return false;
1651     }
1652   } else {
1653     // The MCU psABI allows passing parameters in-reg even if there are
1654     // earlier parameters that are passed on the stack. Also,
1655     // it does not allow passing >8-byte structs in-register,
1656     // even if there are 3 free registers available.
1657     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1658       return false;
1659   }
1660 
1661   State.FreeRegs -= SizeInRegs;
1662   return true;
1663 }
1664 
1665 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1666                                              bool &InReg,
1667                                              bool &NeedsPadding) const {
1668   // On Windows, aggregates other than HFAs are never passed in registers, and
1669   // they do not consume register slots. Homogenous floating-point aggregates
1670   // (HFAs) have already been dealt with at this point.
1671   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1672     return false;
1673 
1674   NeedsPadding = false;
1675   InReg = !IsMCUABI;
1676 
1677   if (!updateFreeRegs(Ty, State))
1678     return false;
1679 
1680   if (IsMCUABI)
1681     return true;
1682 
1683   if (State.CC == llvm::CallingConv::X86_FastCall ||
1684       State.CC == llvm::CallingConv::X86_VectorCall ||
1685       State.CC == llvm::CallingConv::X86_RegCall) {
1686     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1687       NeedsPadding = true;
1688 
1689     return false;
1690   }
1691 
1692   return true;
1693 }
1694 
1695 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1696   if (!updateFreeRegs(Ty, State))
1697     return false;
1698 
1699   if (IsMCUABI)
1700     return false;
1701 
1702   if (State.CC == llvm::CallingConv::X86_FastCall ||
1703       State.CC == llvm::CallingConv::X86_VectorCall ||
1704       State.CC == llvm::CallingConv::X86_RegCall) {
1705     if (getContext().getTypeSize(Ty) > 32)
1706       return false;
1707 
1708     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1709         Ty->isReferenceType());
1710   }
1711 
1712   return true;
1713 }
1714 
1715 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1716   // Vectorcall x86 works subtly different than in x64, so the format is
1717   // a bit different than the x64 version.  First, all vector types (not HVAs)
1718   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1719   // This differs from the x64 implementation, where the first 6 by INDEX get
1720   // registers.
1721   // In the second pass over the arguments, HVAs are passed in the remaining
1722   // vector registers if possible, or indirectly by address. The address will be
1723   // passed in ECX/EDX if available. Any other arguments are passed according to
1724   // the usual fastcall rules.
1725   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1726   for (int I = 0, E = Args.size(); I < E; ++I) {
1727     const Type *Base = nullptr;
1728     uint64_t NumElts = 0;
1729     const QualType &Ty = Args[I].type;
1730     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1731         isHomogeneousAggregate(Ty, Base, NumElts)) {
1732       if (State.FreeSSERegs >= NumElts) {
1733         State.FreeSSERegs -= NumElts;
1734         Args[I].info = ABIArgInfo::getDirectInReg();
1735         State.IsPreassigned.set(I);
1736       }
1737     }
1738   }
1739 }
1740 
1741 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1742                                                CCState &State) const {
1743   // FIXME: Set alignment on indirect arguments.
1744   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1745   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1746   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1747 
1748   Ty = useFirstFieldIfTransparentUnion(Ty);
1749   TypeInfo TI = getContext().getTypeInfo(Ty);
1750 
1751   // Check with the C++ ABI first.
1752   const RecordType *RT = Ty->getAs<RecordType>();
1753   if (RT) {
1754     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1755     if (RAA == CGCXXABI::RAA_Indirect) {
1756       return getIndirectResult(Ty, false, State);
1757     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1758       // The field index doesn't matter, we'll fix it up later.
1759       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1760     }
1761   }
1762 
1763   // Regcall uses the concept of a homogenous vector aggregate, similar
1764   // to other targets.
1765   const Type *Base = nullptr;
1766   uint64_t NumElts = 0;
1767   if ((IsRegCall || IsVectorCall) &&
1768       isHomogeneousAggregate(Ty, Base, NumElts)) {
1769     if (State.FreeSSERegs >= NumElts) {
1770       State.FreeSSERegs -= NumElts;
1771 
1772       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1773       // does.
1774       if (IsVectorCall)
1775         return getDirectX86Hva();
1776 
1777       if (Ty->isBuiltinType() || Ty->isVectorType())
1778         return ABIArgInfo::getDirect();
1779       return ABIArgInfo::getExpand();
1780     }
1781     return getIndirectResult(Ty, /*ByVal=*/false, State);
1782   }
1783 
1784   if (isAggregateTypeForABI(Ty)) {
1785     // Structures with flexible arrays are always indirect.
1786     // FIXME: This should not be byval!
1787     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1788       return getIndirectResult(Ty, true, State);
1789 
1790     // Ignore empty structs/unions on non-Windows.
1791     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1792       return ABIArgInfo::getIgnore();
1793 
1794     llvm::LLVMContext &LLVMContext = getVMContext();
1795     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1796     bool NeedsPadding = false;
1797     bool InReg;
1798     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1799       unsigned SizeInRegs = (TI.Width + 31) / 32;
1800       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1801       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1802       if (InReg)
1803         return ABIArgInfo::getDirectInReg(Result);
1804       else
1805         return ABIArgInfo::getDirect(Result);
1806     }
1807     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1808 
1809     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1810     // added in MSVC 2015.
1811     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1812       return getIndirectResult(Ty, /*ByVal=*/false, State);
1813 
1814     // Expand small (<= 128-bit) record types when we know that the stack layout
1815     // of those arguments will match the struct. This is important because the
1816     // LLVM backend isn't smart enough to remove byval, which inhibits many
1817     // optimizations.
1818     // Don't do this for the MCU if there are still free integer registers
1819     // (see X86_64 ABI for full explanation).
1820     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1821         canExpandIndirectArgument(Ty))
1822       return ABIArgInfo::getExpandWithPadding(
1823           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1824 
1825     return getIndirectResult(Ty, true, State);
1826   }
1827 
1828   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1829     // On Windows, vectors are passed directly if registers are available, or
1830     // indirectly if not. This avoids the need to align argument memory. Pass
1831     // user-defined vector types larger than 512 bits indirectly for simplicity.
1832     if (IsWin32StructABI) {
1833       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1834         --State.FreeSSERegs;
1835         return ABIArgInfo::getDirectInReg();
1836       }
1837       return getIndirectResult(Ty, /*ByVal=*/false, State);
1838     }
1839 
1840     // On Darwin, some vectors are passed in memory, we handle this by passing
1841     // it as an i8/i16/i32/i64.
1842     if (IsDarwinVectorABI) {
1843       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1844           (TI.Width == 64 && VT->getNumElements() == 1))
1845         return ABIArgInfo::getDirect(
1846             llvm::IntegerType::get(getVMContext(), TI.Width));
1847     }
1848 
1849     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1850       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1851 
1852     return ABIArgInfo::getDirect();
1853   }
1854 
1855 
1856   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1857     Ty = EnumTy->getDecl()->getIntegerType();
1858 
1859   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1860 
1861   if (isPromotableIntegerTypeForABI(Ty)) {
1862     if (InReg)
1863       return ABIArgInfo::getExtendInReg(Ty);
1864     return ABIArgInfo::getExtend(Ty);
1865   }
1866 
1867   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1868     if (EIT->getNumBits() <= 64) {
1869       if (InReg)
1870         return ABIArgInfo::getDirectInReg();
1871       return ABIArgInfo::getDirect();
1872     }
1873     return getIndirectResult(Ty, /*ByVal=*/false, State);
1874   }
1875 
1876   if (InReg)
1877     return ABIArgInfo::getDirectInReg();
1878   return ABIArgInfo::getDirect();
1879 }
1880 
1881 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1882   CCState State(FI);
1883   if (IsMCUABI)
1884     State.FreeRegs = 3;
1885   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1886     State.FreeRegs = 2;
1887     State.FreeSSERegs = 3;
1888   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1889     State.FreeRegs = 2;
1890     State.FreeSSERegs = 6;
1891   } else if (FI.getHasRegParm())
1892     State.FreeRegs = FI.getRegParm();
1893   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1894     State.FreeRegs = 5;
1895     State.FreeSSERegs = 8;
1896   } else if (IsWin32StructABI) {
1897     // Since MSVC 2015, the first three SSE vectors have been passed in
1898     // registers. The rest are passed indirectly.
1899     State.FreeRegs = DefaultNumRegisterParameters;
1900     State.FreeSSERegs = 3;
1901   } else
1902     State.FreeRegs = DefaultNumRegisterParameters;
1903 
1904   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1905     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1906   } else if (FI.getReturnInfo().isIndirect()) {
1907     // The C++ ABI is not aware of register usage, so we have to check if the
1908     // return value was sret and put it in a register ourselves if appropriate.
1909     if (State.FreeRegs) {
1910       --State.FreeRegs;  // The sret parameter consumes a register.
1911       if (!IsMCUABI)
1912         FI.getReturnInfo().setInReg(true);
1913     }
1914   }
1915 
1916   // The chain argument effectively gives us another free register.
1917   if (FI.isChainCall())
1918     ++State.FreeRegs;
1919 
1920   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1921   // arguments to XMM registers as available.
1922   if (State.CC == llvm::CallingConv::X86_VectorCall)
1923     runVectorCallFirstPass(FI, State);
1924 
1925   bool UsedInAlloca = false;
1926   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1927   for (int I = 0, E = Args.size(); I < E; ++I) {
1928     // Skip arguments that have already been assigned.
1929     if (State.IsPreassigned.test(I))
1930       continue;
1931 
1932     Args[I].info = classifyArgumentType(Args[I].type, State);
1933     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1934   }
1935 
1936   // If we needed to use inalloca for any argument, do a second pass and rewrite
1937   // all the memory arguments to use inalloca.
1938   if (UsedInAlloca)
1939     rewriteWithInAlloca(FI);
1940 }
1941 
1942 void
1943 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1944                                    CharUnits &StackOffset, ABIArgInfo &Info,
1945                                    QualType Type) const {
1946   // Arguments are always 4-byte-aligned.
1947   CharUnits WordSize = CharUnits::fromQuantity(4);
1948   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1949 
1950   // sret pointers and indirect things will require an extra pointer
1951   // indirection, unless they are byval. Most things are byval, and will not
1952   // require this indirection.
1953   bool IsIndirect = false;
1954   if (Info.isIndirect() && !Info.getIndirectByVal())
1955     IsIndirect = true;
1956   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1957   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1958   if (IsIndirect)
1959     LLTy = LLTy->getPointerTo(0);
1960   FrameFields.push_back(LLTy);
1961   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1962 
1963   // Insert padding bytes to respect alignment.
1964   CharUnits FieldEnd = StackOffset;
1965   StackOffset = FieldEnd.alignTo(WordSize);
1966   if (StackOffset != FieldEnd) {
1967     CharUnits NumBytes = StackOffset - FieldEnd;
1968     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1969     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1970     FrameFields.push_back(Ty);
1971   }
1972 }
1973 
1974 static bool isArgInAlloca(const ABIArgInfo &Info) {
1975   // Leave ignored and inreg arguments alone.
1976   switch (Info.getKind()) {
1977   case ABIArgInfo::InAlloca:
1978     return true;
1979   case ABIArgInfo::Ignore:
1980     return false;
1981   case ABIArgInfo::Indirect:
1982   case ABIArgInfo::Direct:
1983   case ABIArgInfo::Extend:
1984     return !Info.getInReg();
1985   case ABIArgInfo::Expand:
1986   case ABIArgInfo::CoerceAndExpand:
1987     // These are aggregate types which are never passed in registers when
1988     // inalloca is involved.
1989     return true;
1990   }
1991   llvm_unreachable("invalid enum");
1992 }
1993 
1994 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1995   assert(IsWin32StructABI && "inalloca only supported on win32");
1996 
1997   // Build a packed struct type for all of the arguments in memory.
1998   SmallVector<llvm::Type *, 6> FrameFields;
1999 
2000   // The stack alignment is always 4.
2001   CharUnits StackAlign = CharUnits::fromQuantity(4);
2002 
2003   CharUnits StackOffset;
2004   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2005 
2006   // Put 'this' into the struct before 'sret', if necessary.
2007   bool IsThisCall =
2008       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2009   ABIArgInfo &Ret = FI.getReturnInfo();
2010   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2011       isArgInAlloca(I->info)) {
2012     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2013     ++I;
2014   }
2015 
2016   // Put the sret parameter into the inalloca struct if it's in memory.
2017   if (Ret.isIndirect() && !Ret.getInReg()) {
2018     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2019     // On Windows, the hidden sret parameter is always returned in eax.
2020     Ret.setInAllocaSRet(IsWin32StructABI);
2021   }
2022 
2023   // Skip the 'this' parameter in ecx.
2024   if (IsThisCall)
2025     ++I;
2026 
2027   // Put arguments passed in memory into the struct.
2028   for (; I != E; ++I) {
2029     if (isArgInAlloca(I->info))
2030       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2031   }
2032 
2033   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2034                                         /*isPacked=*/true),
2035                   StackAlign);
2036 }
2037 
2038 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2039                                  Address VAListAddr, QualType Ty) const {
2040 
2041   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2042 
2043   // x86-32 changes the alignment of certain arguments on the stack.
2044   //
2045   // Just messing with TypeInfo like this works because we never pass
2046   // anything indirectly.
2047   TypeInfo.second = CharUnits::fromQuantity(
2048                 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
2049 
2050   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2051                           TypeInfo, CharUnits::fromQuantity(4),
2052                           /*AllowHigherAlign*/ true);
2053 }
2054 
2055 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2056     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2057   assert(Triple.getArch() == llvm::Triple::x86);
2058 
2059   switch (Opts.getStructReturnConvention()) {
2060   case CodeGenOptions::SRCK_Default:
2061     break;
2062   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2063     return false;
2064   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2065     return true;
2066   }
2067 
2068   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2069     return true;
2070 
2071   switch (Triple.getOS()) {
2072   case llvm::Triple::DragonFly:
2073   case llvm::Triple::FreeBSD:
2074   case llvm::Triple::OpenBSD:
2075   case llvm::Triple::Win32:
2076     return true;
2077   default:
2078     return false;
2079   }
2080 }
2081 
2082 void X86_32TargetCodeGenInfo::setTargetAttributes(
2083     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2084   if (GV->isDeclaration())
2085     return;
2086   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2087     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2088       llvm::Function *Fn = cast<llvm::Function>(GV);
2089       Fn->addFnAttr("stackrealign");
2090     }
2091     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2092       llvm::Function *Fn = cast<llvm::Function>(GV);
2093       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2094     }
2095   }
2096 }
2097 
2098 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2099                                                CodeGen::CodeGenFunction &CGF,
2100                                                llvm::Value *Address) const {
2101   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2102 
2103   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2104 
2105   // 0-7 are the eight integer registers;  the order is different
2106   //   on Darwin (for EH), but the range is the same.
2107   // 8 is %eip.
2108   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2109 
2110   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2111     // 12-16 are st(0..4).  Not sure why we stop at 4.
2112     // These have size 16, which is sizeof(long double) on
2113     // platforms with 8-byte alignment for that type.
2114     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2115     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2116 
2117   } else {
2118     // 9 is %eflags, which doesn't get a size on Darwin for some
2119     // reason.
2120     Builder.CreateAlignedStore(
2121         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2122                                CharUnits::One());
2123 
2124     // 11-16 are st(0..5).  Not sure why we stop at 5.
2125     // These have size 12, which is sizeof(long double) on
2126     // platforms with 4-byte alignment for that type.
2127     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2128     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2129   }
2130 
2131   return false;
2132 }
2133 
2134 //===----------------------------------------------------------------------===//
2135 // X86-64 ABI Implementation
2136 //===----------------------------------------------------------------------===//
2137 
2138 
2139 namespace {
2140 /// The AVX ABI level for X86 targets.
2141 enum class X86AVXABILevel {
2142   None,
2143   AVX,
2144   AVX512
2145 };
2146 
2147 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2148 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2149   switch (AVXLevel) {
2150   case X86AVXABILevel::AVX512:
2151     return 512;
2152   case X86AVXABILevel::AVX:
2153     return 256;
2154   case X86AVXABILevel::None:
2155     return 128;
2156   }
2157   llvm_unreachable("Unknown AVXLevel");
2158 }
2159 
2160 /// X86_64ABIInfo - The X86_64 ABI information.
2161 class X86_64ABIInfo : public SwiftABIInfo {
2162   enum Class {
2163     Integer = 0,
2164     SSE,
2165     SSEUp,
2166     X87,
2167     X87Up,
2168     ComplexX87,
2169     NoClass,
2170     Memory
2171   };
2172 
2173   /// merge - Implement the X86_64 ABI merging algorithm.
2174   ///
2175   /// Merge an accumulating classification \arg Accum with a field
2176   /// classification \arg Field.
2177   ///
2178   /// \param Accum - The accumulating classification. This should
2179   /// always be either NoClass or the result of a previous merge
2180   /// call. In addition, this should never be Memory (the caller
2181   /// should just return Memory for the aggregate).
2182   static Class merge(Class Accum, Class Field);
2183 
2184   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2185   ///
2186   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2187   /// final MEMORY or SSE classes when necessary.
2188   ///
2189   /// \param AggregateSize - The size of the current aggregate in
2190   /// the classification process.
2191   ///
2192   /// \param Lo - The classification for the parts of the type
2193   /// residing in the low word of the containing object.
2194   ///
2195   /// \param Hi - The classification for the parts of the type
2196   /// residing in the higher words of the containing object.
2197   ///
2198   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2199 
2200   /// classify - Determine the x86_64 register classes in which the
2201   /// given type T should be passed.
2202   ///
2203   /// \param Lo - The classification for the parts of the type
2204   /// residing in the low word of the containing object.
2205   ///
2206   /// \param Hi - The classification for the parts of the type
2207   /// residing in the high word of the containing object.
2208   ///
2209   /// \param OffsetBase - The bit offset of this type in the
2210   /// containing object.  Some parameters are classified different
2211   /// depending on whether they straddle an eightbyte boundary.
2212   ///
2213   /// \param isNamedArg - Whether the argument in question is a "named"
2214   /// argument, as used in AMD64-ABI 3.5.7.
2215   ///
2216   /// If a word is unused its result will be NoClass; if a type should
2217   /// be passed in Memory then at least the classification of \arg Lo
2218   /// will be Memory.
2219   ///
2220   /// The \arg Lo class will be NoClass iff the argument is ignored.
2221   ///
2222   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2223   /// also be ComplexX87.
2224   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2225                 bool isNamedArg) const;
2226 
2227   llvm::Type *GetByteVectorType(QualType Ty) const;
2228   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2229                                  unsigned IROffset, QualType SourceTy,
2230                                  unsigned SourceOffset) const;
2231   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2232                                      unsigned IROffset, QualType SourceTy,
2233                                      unsigned SourceOffset) const;
2234 
2235   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2236   /// such that the argument will be returned in memory.
2237   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2238 
2239   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2240   /// such that the argument will be passed in memory.
2241   ///
2242   /// \param freeIntRegs - The number of free integer registers remaining
2243   /// available.
2244   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2245 
2246   ABIArgInfo classifyReturnType(QualType RetTy) const;
2247 
2248   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2249                                   unsigned &neededInt, unsigned &neededSSE,
2250                                   bool isNamedArg) const;
2251 
2252   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2253                                        unsigned &NeededSSE) const;
2254 
2255   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2256                                            unsigned &NeededSSE) const;
2257 
2258   bool IsIllegalVectorType(QualType Ty) const;
2259 
2260   /// The 0.98 ABI revision clarified a lot of ambiguities,
2261   /// unfortunately in ways that were not always consistent with
2262   /// certain previous compilers.  In particular, platforms which
2263   /// required strict binary compatibility with older versions of GCC
2264   /// may need to exempt themselves.
2265   bool honorsRevision0_98() const {
2266     return !getTarget().getTriple().isOSDarwin();
2267   }
2268 
2269   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2270   /// classify it as INTEGER (for compatibility with older clang compilers).
2271   bool classifyIntegerMMXAsSSE() const {
2272     // Clang <= 3.8 did not do this.
2273     if (getContext().getLangOpts().getClangABICompat() <=
2274         LangOptions::ClangABI::Ver3_8)
2275       return false;
2276 
2277     const llvm::Triple &Triple = getTarget().getTriple();
2278     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2279       return false;
2280     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2281       return false;
2282     return true;
2283   }
2284 
2285   // GCC classifies vectors of __int128 as memory.
2286   bool passInt128VectorsInMem() const {
2287     // Clang <= 9.0 did not do this.
2288     if (getContext().getLangOpts().getClangABICompat() <=
2289         LangOptions::ClangABI::Ver9)
2290       return false;
2291 
2292     const llvm::Triple &T = getTarget().getTriple();
2293     return T.isOSLinux() || T.isOSNetBSD();
2294   }
2295 
2296   X86AVXABILevel AVXLevel;
2297   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2298   // 64-bit hardware.
2299   bool Has64BitPointers;
2300 
2301 public:
2302   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2303       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2304       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2305   }
2306 
2307   bool isPassedUsingAVXType(QualType type) const {
2308     unsigned neededInt, neededSSE;
2309     // The freeIntRegs argument doesn't matter here.
2310     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2311                                            /*isNamedArg*/true);
2312     if (info.isDirect()) {
2313       llvm::Type *ty = info.getCoerceToType();
2314       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2315         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2316     }
2317     return false;
2318   }
2319 
2320   void computeInfo(CGFunctionInfo &FI) const override;
2321 
2322   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2323                     QualType Ty) const override;
2324   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2325                       QualType Ty) const override;
2326 
2327   bool has64BitPointers() const {
2328     return Has64BitPointers;
2329   }
2330 
2331   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2332                                     bool asReturnValue) const override {
2333     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2334   }
2335   bool isSwiftErrorInRegister() const override {
2336     return true;
2337   }
2338 };
2339 
2340 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2341 class WinX86_64ABIInfo : public SwiftABIInfo {
2342 public:
2343   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2344       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2345         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2346 
2347   void computeInfo(CGFunctionInfo &FI) const override;
2348 
2349   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2350                     QualType Ty) const override;
2351 
2352   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2353     // FIXME: Assumes vectorcall is in use.
2354     return isX86VectorTypeForVectorCall(getContext(), Ty);
2355   }
2356 
2357   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2358                                          uint64_t NumMembers) const override {
2359     // FIXME: Assumes vectorcall is in use.
2360     return isX86VectorCallAggregateSmallEnough(NumMembers);
2361   }
2362 
2363   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2364                                     bool asReturnValue) const override {
2365     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2366   }
2367 
2368   bool isSwiftErrorInRegister() const override {
2369     return true;
2370   }
2371 
2372 private:
2373   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2374                       bool IsVectorCall, bool IsRegCall) const;
2375   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2376                                       const ABIArgInfo &current) const;
2377   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2378                              bool IsVectorCall, bool IsRegCall) const;
2379 
2380   X86AVXABILevel AVXLevel;
2381 
2382   bool IsMingw64;
2383 };
2384 
2385 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2386 public:
2387   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2388       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2389 
2390   const X86_64ABIInfo &getABIInfo() const {
2391     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2392   }
2393 
2394   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2395   /// the autoreleaseRV/retainRV optimization.
2396   bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2397     return true;
2398   }
2399 
2400   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2401     return 7;
2402   }
2403 
2404   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2405                                llvm::Value *Address) const override {
2406     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2407 
2408     // 0-15 are the 16 integer registers.
2409     // 16 is %rip.
2410     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2411     return false;
2412   }
2413 
2414   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2415                                   StringRef Constraint,
2416                                   llvm::Type* Ty) const override {
2417     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2418   }
2419 
2420   bool isNoProtoCallVariadic(const CallArgList &args,
2421                              const FunctionNoProtoType *fnType) const override {
2422     // The default CC on x86-64 sets %al to the number of SSA
2423     // registers used, and GCC sets this when calling an unprototyped
2424     // function, so we override the default behavior.  However, don't do
2425     // that when AVX types are involved: the ABI explicitly states it is
2426     // undefined, and it doesn't work in practice because of how the ABI
2427     // defines varargs anyway.
2428     if (fnType->getCallConv() == CC_C) {
2429       bool HasAVXType = false;
2430       for (CallArgList::const_iterator
2431              it = args.begin(), ie = args.end(); it != ie; ++it) {
2432         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2433           HasAVXType = true;
2434           break;
2435         }
2436       }
2437 
2438       if (!HasAVXType)
2439         return true;
2440     }
2441 
2442     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2443   }
2444 
2445   llvm::Constant *
2446   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2447     unsigned Sig = (0xeb << 0) | // jmp rel8
2448                    (0x06 << 8) | //           .+0x08
2449                    ('v' << 16) |
2450                    ('2' << 24);
2451     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2452   }
2453 
2454   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2455                            CodeGen::CodeGenModule &CGM) const override {
2456     if (GV->isDeclaration())
2457       return;
2458     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2459       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2460         llvm::Function *Fn = cast<llvm::Function>(GV);
2461         Fn->addFnAttr("stackrealign");
2462       }
2463       if (FD->hasAttr<AnyX86InterruptAttr>()) {
2464         llvm::Function *Fn = cast<llvm::Function>(GV);
2465         Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2466       }
2467     }
2468   }
2469 };
2470 
2471 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2472   // If the argument does not end in .lib, automatically add the suffix.
2473   // If the argument contains a space, enclose it in quotes.
2474   // This matches the behavior of MSVC.
2475   bool Quote = (Lib.find(" ") != StringRef::npos);
2476   std::string ArgStr = Quote ? "\"" : "";
2477   ArgStr += Lib;
2478   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2479     ArgStr += ".lib";
2480   ArgStr += Quote ? "\"" : "";
2481   return ArgStr;
2482 }
2483 
2484 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2485 public:
2486   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2487         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2488         unsigned NumRegisterParameters)
2489     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2490         Win32StructABI, NumRegisterParameters, false) {}
2491 
2492   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2493                            CodeGen::CodeGenModule &CGM) const override;
2494 
2495   void getDependentLibraryOption(llvm::StringRef Lib,
2496                                  llvm::SmallString<24> &Opt) const override {
2497     Opt = "/DEFAULTLIB:";
2498     Opt += qualifyWindowsLibrary(Lib);
2499   }
2500 
2501   void getDetectMismatchOption(llvm::StringRef Name,
2502                                llvm::StringRef Value,
2503                                llvm::SmallString<32> &Opt) const override {
2504     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2505   }
2506 };
2507 
2508 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2509                                           CodeGen::CodeGenModule &CGM) {
2510   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2511 
2512     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2513       Fn->addFnAttr("stack-probe-size",
2514                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2515     if (CGM.getCodeGenOpts().NoStackArgProbe)
2516       Fn->addFnAttr("no-stack-arg-probe");
2517   }
2518 }
2519 
2520 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2521     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2522   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2523   if (GV->isDeclaration())
2524     return;
2525   addStackProbeTargetAttributes(D, GV, CGM);
2526 }
2527 
2528 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2529 public:
2530   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2531                              X86AVXABILevel AVXLevel)
2532       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2533 
2534   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2535                            CodeGen::CodeGenModule &CGM) const override;
2536 
2537   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2538     return 7;
2539   }
2540 
2541   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2542                                llvm::Value *Address) const override {
2543     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2544 
2545     // 0-15 are the 16 integer registers.
2546     // 16 is %rip.
2547     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2548     return false;
2549   }
2550 
2551   void getDependentLibraryOption(llvm::StringRef Lib,
2552                                  llvm::SmallString<24> &Opt) const override {
2553     Opt = "/DEFAULTLIB:";
2554     Opt += qualifyWindowsLibrary(Lib);
2555   }
2556 
2557   void getDetectMismatchOption(llvm::StringRef Name,
2558                                llvm::StringRef Value,
2559                                llvm::SmallString<32> &Opt) const override {
2560     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2561   }
2562 };
2563 
2564 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2565     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2566   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2567   if (GV->isDeclaration())
2568     return;
2569   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2570     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2571       llvm::Function *Fn = cast<llvm::Function>(GV);
2572       Fn->addFnAttr("stackrealign");
2573     }
2574     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2575       llvm::Function *Fn = cast<llvm::Function>(GV);
2576       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2577     }
2578   }
2579 
2580   addStackProbeTargetAttributes(D, GV, CGM);
2581 }
2582 }
2583 
2584 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2585                               Class &Hi) const {
2586   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2587   //
2588   // (a) If one of the classes is Memory, the whole argument is passed in
2589   //     memory.
2590   //
2591   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2592   //     memory.
2593   //
2594   // (c) If the size of the aggregate exceeds two eightbytes and the first
2595   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2596   //     argument is passed in memory. NOTE: This is necessary to keep the
2597   //     ABI working for processors that don't support the __m256 type.
2598   //
2599   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2600   //
2601   // Some of these are enforced by the merging logic.  Others can arise
2602   // only with unions; for example:
2603   //   union { _Complex double; unsigned; }
2604   //
2605   // Note that clauses (b) and (c) were added in 0.98.
2606   //
2607   if (Hi == Memory)
2608     Lo = Memory;
2609   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2610     Lo = Memory;
2611   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2612     Lo = Memory;
2613   if (Hi == SSEUp && Lo != SSE)
2614     Hi = SSE;
2615 }
2616 
2617 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2618   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2619   // classified recursively so that always two fields are
2620   // considered. The resulting class is calculated according to
2621   // the classes of the fields in the eightbyte:
2622   //
2623   // (a) If both classes are equal, this is the resulting class.
2624   //
2625   // (b) If one of the classes is NO_CLASS, the resulting class is
2626   // the other class.
2627   //
2628   // (c) If one of the classes is MEMORY, the result is the MEMORY
2629   // class.
2630   //
2631   // (d) If one of the classes is INTEGER, the result is the
2632   // INTEGER.
2633   //
2634   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2635   // MEMORY is used as class.
2636   //
2637   // (f) Otherwise class SSE is used.
2638 
2639   // Accum should never be memory (we should have returned) or
2640   // ComplexX87 (because this cannot be passed in a structure).
2641   assert((Accum != Memory && Accum != ComplexX87) &&
2642          "Invalid accumulated classification during merge.");
2643   if (Accum == Field || Field == NoClass)
2644     return Accum;
2645   if (Field == Memory)
2646     return Memory;
2647   if (Accum == NoClass)
2648     return Field;
2649   if (Accum == Integer || Field == Integer)
2650     return Integer;
2651   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2652       Accum == X87 || Accum == X87Up)
2653     return Memory;
2654   return SSE;
2655 }
2656 
2657 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2658                              Class &Lo, Class &Hi, bool isNamedArg) const {
2659   // FIXME: This code can be simplified by introducing a simple value class for
2660   // Class pairs with appropriate constructor methods for the various
2661   // situations.
2662 
2663   // FIXME: Some of the split computations are wrong; unaligned vectors
2664   // shouldn't be passed in registers for example, so there is no chance they
2665   // can straddle an eightbyte. Verify & simplify.
2666 
2667   Lo = Hi = NoClass;
2668 
2669   Class &Current = OffsetBase < 64 ? Lo : Hi;
2670   Current = Memory;
2671 
2672   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2673     BuiltinType::Kind k = BT->getKind();
2674 
2675     if (k == BuiltinType::Void) {
2676       Current = NoClass;
2677     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2678       Lo = Integer;
2679       Hi = Integer;
2680     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2681       Current = Integer;
2682     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2683       Current = SSE;
2684     } else if (k == BuiltinType::LongDouble) {
2685       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2686       if (LDF == &llvm::APFloat::IEEEquad()) {
2687         Lo = SSE;
2688         Hi = SSEUp;
2689       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2690         Lo = X87;
2691         Hi = X87Up;
2692       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2693         Current = SSE;
2694       } else
2695         llvm_unreachable("unexpected long double representation!");
2696     }
2697     // FIXME: _Decimal32 and _Decimal64 are SSE.
2698     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2699     return;
2700   }
2701 
2702   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2703     // Classify the underlying integer type.
2704     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2705     return;
2706   }
2707 
2708   if (Ty->hasPointerRepresentation()) {
2709     Current = Integer;
2710     return;
2711   }
2712 
2713   if (Ty->isMemberPointerType()) {
2714     if (Ty->isMemberFunctionPointerType()) {
2715       if (Has64BitPointers) {
2716         // If Has64BitPointers, this is an {i64, i64}, so classify both
2717         // Lo and Hi now.
2718         Lo = Hi = Integer;
2719       } else {
2720         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2721         // straddles an eightbyte boundary, Hi should be classified as well.
2722         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2723         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2724         if (EB_FuncPtr != EB_ThisAdj) {
2725           Lo = Hi = Integer;
2726         } else {
2727           Current = Integer;
2728         }
2729       }
2730     } else {
2731       Current = Integer;
2732     }
2733     return;
2734   }
2735 
2736   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2737     uint64_t Size = getContext().getTypeSize(VT);
2738     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2739       // gcc passes the following as integer:
2740       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2741       // 2 bytes - <2 x char>, <1 x short>
2742       // 1 byte  - <1 x char>
2743       Current = Integer;
2744 
2745       // If this type crosses an eightbyte boundary, it should be
2746       // split.
2747       uint64_t EB_Lo = (OffsetBase) / 64;
2748       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2749       if (EB_Lo != EB_Hi)
2750         Hi = Lo;
2751     } else if (Size == 64) {
2752       QualType ElementType = VT->getElementType();
2753 
2754       // gcc passes <1 x double> in memory. :(
2755       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2756         return;
2757 
2758       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2759       // pass them as integer.  For platforms where clang is the de facto
2760       // platform compiler, we must continue to use integer.
2761       if (!classifyIntegerMMXAsSSE() &&
2762           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2763            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2764            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2765            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2766         Current = Integer;
2767       else
2768         Current = SSE;
2769 
2770       // If this type crosses an eightbyte boundary, it should be
2771       // split.
2772       if (OffsetBase && OffsetBase != 64)
2773         Hi = Lo;
2774     } else if (Size == 128 ||
2775                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2776       QualType ElementType = VT->getElementType();
2777 
2778       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2779       if (passInt128VectorsInMem() && Size != 128 &&
2780           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2781            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2782         return;
2783 
2784       // Arguments of 256-bits are split into four eightbyte chunks. The
2785       // least significant one belongs to class SSE and all the others to class
2786       // SSEUP. The original Lo and Hi design considers that types can't be
2787       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2788       // This design isn't correct for 256-bits, but since there're no cases
2789       // where the upper parts would need to be inspected, avoid adding
2790       // complexity and just consider Hi to match the 64-256 part.
2791       //
2792       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2793       // registers if they are "named", i.e. not part of the "..." of a
2794       // variadic function.
2795       //
2796       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2797       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2798       Lo = SSE;
2799       Hi = SSEUp;
2800     }
2801     return;
2802   }
2803 
2804   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2805     QualType ET = getContext().getCanonicalType(CT->getElementType());
2806 
2807     uint64_t Size = getContext().getTypeSize(Ty);
2808     if (ET->isIntegralOrEnumerationType()) {
2809       if (Size <= 64)
2810         Current = Integer;
2811       else if (Size <= 128)
2812         Lo = Hi = Integer;
2813     } else if (ET == getContext().FloatTy) {
2814       Current = SSE;
2815     } else if (ET == getContext().DoubleTy) {
2816       Lo = Hi = SSE;
2817     } else if (ET == getContext().LongDoubleTy) {
2818       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2819       if (LDF == &llvm::APFloat::IEEEquad())
2820         Current = Memory;
2821       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2822         Current = ComplexX87;
2823       else if (LDF == &llvm::APFloat::IEEEdouble())
2824         Lo = Hi = SSE;
2825       else
2826         llvm_unreachable("unexpected long double representation!");
2827     }
2828 
2829     // If this complex type crosses an eightbyte boundary then it
2830     // should be split.
2831     uint64_t EB_Real = (OffsetBase) / 64;
2832     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2833     if (Hi == NoClass && EB_Real != EB_Imag)
2834       Hi = Lo;
2835 
2836     return;
2837   }
2838 
2839   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2840     if (EITy->getNumBits() <= 64)
2841       Current = Integer;
2842     else if (EITy->getNumBits() <= 128)
2843       Lo = Hi = Integer;
2844     // Larger values need to get passed in memory.
2845     return;
2846   }
2847 
2848   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2849     // Arrays are treated like structures.
2850 
2851     uint64_t Size = getContext().getTypeSize(Ty);
2852 
2853     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2854     // than eight eightbytes, ..., it has class MEMORY.
2855     if (Size > 512)
2856       return;
2857 
2858     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2859     // fields, it has class MEMORY.
2860     //
2861     // Only need to check alignment of array base.
2862     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2863       return;
2864 
2865     // Otherwise implement simplified merge. We could be smarter about
2866     // this, but it isn't worth it and would be harder to verify.
2867     Current = NoClass;
2868     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2869     uint64_t ArraySize = AT->getSize().getZExtValue();
2870 
2871     // The only case a 256-bit wide vector could be used is when the array
2872     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2873     // to work for sizes wider than 128, early check and fallback to memory.
2874     //
2875     if (Size > 128 &&
2876         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2877       return;
2878 
2879     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2880       Class FieldLo, FieldHi;
2881       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2882       Lo = merge(Lo, FieldLo);
2883       Hi = merge(Hi, FieldHi);
2884       if (Lo == Memory || Hi == Memory)
2885         break;
2886     }
2887 
2888     postMerge(Size, Lo, Hi);
2889     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2890     return;
2891   }
2892 
2893   if (const RecordType *RT = Ty->getAs<RecordType>()) {
2894     uint64_t Size = getContext().getTypeSize(Ty);
2895 
2896     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2897     // than eight eightbytes, ..., it has class MEMORY.
2898     if (Size > 512)
2899       return;
2900 
2901     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2902     // copy constructor or a non-trivial destructor, it is passed by invisible
2903     // reference.
2904     if (getRecordArgABI(RT, getCXXABI()))
2905       return;
2906 
2907     const RecordDecl *RD = RT->getDecl();
2908 
2909     // Assume variable sized types are passed in memory.
2910     if (RD->hasFlexibleArrayMember())
2911       return;
2912 
2913     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2914 
2915     // Reset Lo class, this will be recomputed.
2916     Current = NoClass;
2917 
2918     // If this is a C++ record, classify the bases first.
2919     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2920       for (const auto &I : CXXRD->bases()) {
2921         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2922                "Unexpected base class!");
2923         const auto *Base =
2924             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2925 
2926         // Classify this field.
2927         //
2928         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2929         // single eightbyte, each is classified separately. Each eightbyte gets
2930         // initialized to class NO_CLASS.
2931         Class FieldLo, FieldHi;
2932         uint64_t Offset =
2933           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2934         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2935         Lo = merge(Lo, FieldLo);
2936         Hi = merge(Hi, FieldHi);
2937         if (Lo == Memory || Hi == Memory) {
2938           postMerge(Size, Lo, Hi);
2939           return;
2940         }
2941       }
2942     }
2943 
2944     // Classify the fields one at a time, merging the results.
2945     unsigned idx = 0;
2946     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2947            i != e; ++i, ++idx) {
2948       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2949       bool BitField = i->isBitField();
2950 
2951       // Ignore padding bit-fields.
2952       if (BitField && i->isUnnamedBitfield())
2953         continue;
2954 
2955       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2956       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2957       //
2958       // The only case a 256-bit wide vector could be used is when the struct
2959       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2960       // to work for sizes wider than 128, early check and fallback to memory.
2961       //
2962       if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2963                          Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2964         Lo = Memory;
2965         postMerge(Size, Lo, Hi);
2966         return;
2967       }
2968       // Note, skip this test for bit-fields, see below.
2969       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2970         Lo = Memory;
2971         postMerge(Size, Lo, Hi);
2972         return;
2973       }
2974 
2975       // Classify this field.
2976       //
2977       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2978       // exceeds a single eightbyte, each is classified
2979       // separately. Each eightbyte gets initialized to class
2980       // NO_CLASS.
2981       Class FieldLo, FieldHi;
2982 
2983       // Bit-fields require special handling, they do not force the
2984       // structure to be passed in memory even if unaligned, and
2985       // therefore they can straddle an eightbyte.
2986       if (BitField) {
2987         assert(!i->isUnnamedBitfield());
2988         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2989         uint64_t Size = i->getBitWidthValue(getContext());
2990 
2991         uint64_t EB_Lo = Offset / 64;
2992         uint64_t EB_Hi = (Offset + Size - 1) / 64;
2993 
2994         if (EB_Lo) {
2995           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2996           FieldLo = NoClass;
2997           FieldHi = Integer;
2998         } else {
2999           FieldLo = Integer;
3000           FieldHi = EB_Hi ? Integer : NoClass;
3001         }
3002       } else
3003         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3004       Lo = merge(Lo, FieldLo);
3005       Hi = merge(Hi, FieldHi);
3006       if (Lo == Memory || Hi == Memory)
3007         break;
3008     }
3009 
3010     postMerge(Size, Lo, Hi);
3011   }
3012 }
3013 
3014 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3015   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3016   // place naturally.
3017   if (!isAggregateTypeForABI(Ty)) {
3018     // Treat an enum type as its underlying type.
3019     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3020       Ty = EnumTy->getDecl()->getIntegerType();
3021 
3022     if (Ty->isExtIntType())
3023       return getNaturalAlignIndirect(Ty);
3024 
3025     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3026                                               : ABIArgInfo::getDirect());
3027   }
3028 
3029   return getNaturalAlignIndirect(Ty);
3030 }
3031 
3032 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3033   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3034     uint64_t Size = getContext().getTypeSize(VecTy);
3035     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3036     if (Size <= 64 || Size > LargestVector)
3037       return true;
3038     QualType EltTy = VecTy->getElementType();
3039     if (passInt128VectorsInMem() &&
3040         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3041          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3042       return true;
3043   }
3044 
3045   return false;
3046 }
3047 
3048 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3049                                             unsigned freeIntRegs) const {
3050   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3051   // place naturally.
3052   //
3053   // This assumption is optimistic, as there could be free registers available
3054   // when we need to pass this argument in memory, and LLVM could try to pass
3055   // the argument in the free register. This does not seem to happen currently,
3056   // but this code would be much safer if we could mark the argument with
3057   // 'onstack'. See PR12193.
3058   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3059       !Ty->isExtIntType()) {
3060     // Treat an enum type as its underlying type.
3061     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3062       Ty = EnumTy->getDecl()->getIntegerType();
3063 
3064     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3065                                               : ABIArgInfo::getDirect());
3066   }
3067 
3068   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3069     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3070 
3071   // Compute the byval alignment. We specify the alignment of the byval in all
3072   // cases so that the mid-level optimizer knows the alignment of the byval.
3073   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3074 
3075   // Attempt to avoid passing indirect results using byval when possible. This
3076   // is important for good codegen.
3077   //
3078   // We do this by coercing the value into a scalar type which the backend can
3079   // handle naturally (i.e., without using byval).
3080   //
3081   // For simplicity, we currently only do this when we have exhausted all of the
3082   // free integer registers. Doing this when there are free integer registers
3083   // would require more care, as we would have to ensure that the coerced value
3084   // did not claim the unused register. That would require either reording the
3085   // arguments to the function (so that any subsequent inreg values came first),
3086   // or only doing this optimization when there were no following arguments that
3087   // might be inreg.
3088   //
3089   // We currently expect it to be rare (particularly in well written code) for
3090   // arguments to be passed on the stack when there are still free integer
3091   // registers available (this would typically imply large structs being passed
3092   // by value), so this seems like a fair tradeoff for now.
3093   //
3094   // We can revisit this if the backend grows support for 'onstack' parameter
3095   // attributes. See PR12193.
3096   if (freeIntRegs == 0) {
3097     uint64_t Size = getContext().getTypeSize(Ty);
3098 
3099     // If this type fits in an eightbyte, coerce it into the matching integral
3100     // type, which will end up on the stack (with alignment 8).
3101     if (Align == 8 && Size <= 64)
3102       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3103                                                           Size));
3104   }
3105 
3106   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3107 }
3108 
3109 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3110 /// register. Pick an LLVM IR type that will be passed as a vector register.
3111 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3112   // Wrapper structs/arrays that only contain vectors are passed just like
3113   // vectors; strip them off if present.
3114   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3115     Ty = QualType(InnerTy, 0);
3116 
3117   llvm::Type *IRType = CGT.ConvertType(Ty);
3118   if (isa<llvm::VectorType>(IRType)) {
3119     // Don't pass vXi128 vectors in their native type, the backend can't
3120     // legalize them.
3121     if (passInt128VectorsInMem() &&
3122         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3123       // Use a vXi64 vector.
3124       uint64_t Size = getContext().getTypeSize(Ty);
3125       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3126                                         Size / 64);
3127     }
3128 
3129     return IRType;
3130   }
3131 
3132   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3133     return IRType;
3134 
3135   // We couldn't find the preferred IR vector type for 'Ty'.
3136   uint64_t Size = getContext().getTypeSize(Ty);
3137   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3138 
3139 
3140   // Return a LLVM IR vector type based on the size of 'Ty'.
3141   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3142                                     Size / 64);
3143 }
3144 
3145 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3146 /// is known to either be off the end of the specified type or being in
3147 /// alignment padding.  The user type specified is known to be at most 128 bits
3148 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3149 /// classification that put one of the two halves in the INTEGER class.
3150 ///
3151 /// It is conservatively correct to return false.
3152 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3153                                   unsigned EndBit, ASTContext &Context) {
3154   // If the bytes being queried are off the end of the type, there is no user
3155   // data hiding here.  This handles analysis of builtins, vectors and other
3156   // types that don't contain interesting padding.
3157   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3158   if (TySize <= StartBit)
3159     return true;
3160 
3161   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3162     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3163     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3164 
3165     // Check each element to see if the element overlaps with the queried range.
3166     for (unsigned i = 0; i != NumElts; ++i) {
3167       // If the element is after the span we care about, then we're done..
3168       unsigned EltOffset = i*EltSize;
3169       if (EltOffset >= EndBit) break;
3170 
3171       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3172       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3173                                  EndBit-EltOffset, Context))
3174         return false;
3175     }
3176     // If it overlaps no elements, then it is safe to process as padding.
3177     return true;
3178   }
3179 
3180   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3181     const RecordDecl *RD = RT->getDecl();
3182     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3183 
3184     // If this is a C++ record, check the bases first.
3185     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3186       for (const auto &I : CXXRD->bases()) {
3187         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3188                "Unexpected base class!");
3189         const auto *Base =
3190             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3191 
3192         // If the base is after the span we care about, ignore it.
3193         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3194         if (BaseOffset >= EndBit) continue;
3195 
3196         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3197         if (!BitsContainNoUserData(I.getType(), BaseStart,
3198                                    EndBit-BaseOffset, Context))
3199           return false;
3200       }
3201     }
3202 
3203     // Verify that no field has data that overlaps the region of interest.  Yes
3204     // this could be sped up a lot by being smarter about queried fields,
3205     // however we're only looking at structs up to 16 bytes, so we don't care
3206     // much.
3207     unsigned idx = 0;
3208     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3209          i != e; ++i, ++idx) {
3210       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3211 
3212       // If we found a field after the region we care about, then we're done.
3213       if (FieldOffset >= EndBit) break;
3214 
3215       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3216       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3217                                  Context))
3218         return false;
3219     }
3220 
3221     // If nothing in this record overlapped the area of interest, then we're
3222     // clean.
3223     return true;
3224   }
3225 
3226   return false;
3227 }
3228 
3229 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3230 /// float member at the specified offset.  For example, {int,{float}} has a
3231 /// float at offset 4.  It is conservatively correct for this routine to return
3232 /// false.
3233 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3234                                   const llvm::DataLayout &TD) {
3235   // Base case if we find a float.
3236   if (IROffset == 0 && IRType->isFloatTy())
3237     return true;
3238 
3239   // If this is a struct, recurse into the field at the specified offset.
3240   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3241     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3242     unsigned Elt = SL->getElementContainingOffset(IROffset);
3243     IROffset -= SL->getElementOffset(Elt);
3244     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3245   }
3246 
3247   // If this is an array, recurse into the field at the specified offset.
3248   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3249     llvm::Type *EltTy = ATy->getElementType();
3250     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3251     IROffset -= IROffset/EltSize*EltSize;
3252     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3253   }
3254 
3255   return false;
3256 }
3257 
3258 
3259 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3260 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3261 llvm::Type *X86_64ABIInfo::
3262 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3263                    QualType SourceTy, unsigned SourceOffset) const {
3264   // The only three choices we have are either double, <2 x float>, or float. We
3265   // pass as float if the last 4 bytes is just padding.  This happens for
3266   // structs that contain 3 floats.
3267   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3268                             SourceOffset*8+64, getContext()))
3269     return llvm::Type::getFloatTy(getVMContext());
3270 
3271   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3272   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3273   // case.
3274   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3275       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3276     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3277                                       2);
3278 
3279   return llvm::Type::getDoubleTy(getVMContext());
3280 }
3281 
3282 
3283 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3284 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3285 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3286 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3287 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3288 /// etc).
3289 ///
3290 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3291 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3292 /// the 8-byte value references.  PrefType may be null.
3293 ///
3294 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3295 /// an offset into this that we're processing (which is always either 0 or 8).
3296 ///
3297 llvm::Type *X86_64ABIInfo::
3298 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3299                        QualType SourceTy, unsigned SourceOffset) const {
3300   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3301   // returning an 8-byte unit starting with it.  See if we can safely use it.
3302   if (IROffset == 0) {
3303     // Pointers and int64's always fill the 8-byte unit.
3304     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3305         IRType->isIntegerTy(64))
3306       return IRType;
3307 
3308     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3309     // goodness in the source type is just tail padding.  This is allowed to
3310     // kick in for struct {double,int} on the int, but not on
3311     // struct{double,int,int} because we wouldn't return the second int.  We
3312     // have to do this analysis on the source type because we can't depend on
3313     // unions being lowered a specific way etc.
3314     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3315         IRType->isIntegerTy(32) ||
3316         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3317       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3318           cast<llvm::IntegerType>(IRType)->getBitWidth();
3319 
3320       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3321                                 SourceOffset*8+64, getContext()))
3322         return IRType;
3323     }
3324   }
3325 
3326   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3327     // If this is a struct, recurse into the field at the specified offset.
3328     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3329     if (IROffset < SL->getSizeInBytes()) {
3330       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3331       IROffset -= SL->getElementOffset(FieldIdx);
3332 
3333       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3334                                     SourceTy, SourceOffset);
3335     }
3336   }
3337 
3338   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3339     llvm::Type *EltTy = ATy->getElementType();
3340     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3341     unsigned EltOffset = IROffset/EltSize*EltSize;
3342     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3343                                   SourceOffset);
3344   }
3345 
3346   // Okay, we don't have any better idea of what to pass, so we pass this in an
3347   // integer register that isn't too big to fit the rest of the struct.
3348   unsigned TySizeInBytes =
3349     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3350 
3351   assert(TySizeInBytes != SourceOffset && "Empty field?");
3352 
3353   // It is always safe to classify this as an integer type up to i64 that
3354   // isn't larger than the structure.
3355   return llvm::IntegerType::get(getVMContext(),
3356                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3357 }
3358 
3359 
3360 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3361 /// be used as elements of a two register pair to pass or return, return a
3362 /// first class aggregate to represent them.  For example, if the low part of
3363 /// a by-value argument should be passed as i32* and the high part as float,
3364 /// return {i32*, float}.
3365 static llvm::Type *
3366 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3367                            const llvm::DataLayout &TD) {
3368   // In order to correctly satisfy the ABI, we need to the high part to start
3369   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3370   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3371   // the second element at offset 8.  Check for this:
3372   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3373   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3374   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3375   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3376 
3377   // To handle this, we have to increase the size of the low part so that the
3378   // second element will start at an 8 byte offset.  We can't increase the size
3379   // of the second element because it might make us access off the end of the
3380   // struct.
3381   if (HiStart != 8) {
3382     // There are usually two sorts of types the ABI generation code can produce
3383     // for the low part of a pair that aren't 8 bytes in size: float or
3384     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3385     // NaCl).
3386     // Promote these to a larger type.
3387     if (Lo->isFloatTy())
3388       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3389     else {
3390       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3391              && "Invalid/unknown lo type");
3392       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3393     }
3394   }
3395 
3396   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3397 
3398   // Verify that the second element is at an 8-byte offset.
3399   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3400          "Invalid x86-64 argument pair!");
3401   return Result;
3402 }
3403 
3404 ABIArgInfo X86_64ABIInfo::
3405 classifyReturnType(QualType RetTy) const {
3406   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3407   // classification algorithm.
3408   X86_64ABIInfo::Class Lo, Hi;
3409   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3410 
3411   // Check some invariants.
3412   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3413   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3414 
3415   llvm::Type *ResType = nullptr;
3416   switch (Lo) {
3417   case NoClass:
3418     if (Hi == NoClass)
3419       return ABIArgInfo::getIgnore();
3420     // If the low part is just padding, it takes no register, leave ResType
3421     // null.
3422     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3423            "Unknown missing lo part");
3424     break;
3425 
3426   case SSEUp:
3427   case X87Up:
3428     llvm_unreachable("Invalid classification for lo word.");
3429 
3430     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3431     // hidden argument.
3432   case Memory:
3433     return getIndirectReturnResult(RetTy);
3434 
3435     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3436     // available register of the sequence %rax, %rdx is used.
3437   case Integer:
3438     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3439 
3440     // If we have a sign or zero extended integer, make sure to return Extend
3441     // so that the parameter gets the right LLVM IR attributes.
3442     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3443       // Treat an enum type as its underlying type.
3444       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3445         RetTy = EnumTy->getDecl()->getIntegerType();
3446 
3447       if (RetTy->isIntegralOrEnumerationType() &&
3448           isPromotableIntegerTypeForABI(RetTy))
3449         return ABIArgInfo::getExtend(RetTy);
3450     }
3451     break;
3452 
3453     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3454     // available SSE register of the sequence %xmm0, %xmm1 is used.
3455   case SSE:
3456     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3457     break;
3458 
3459     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3460     // returned on the X87 stack in %st0 as 80-bit x87 number.
3461   case X87:
3462     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3463     break;
3464 
3465     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3466     // part of the value is returned in %st0 and the imaginary part in
3467     // %st1.
3468   case ComplexX87:
3469     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3470     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3471                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3472     break;
3473   }
3474 
3475   llvm::Type *HighPart = nullptr;
3476   switch (Hi) {
3477     // Memory was handled previously and X87 should
3478     // never occur as a hi class.
3479   case Memory:
3480   case X87:
3481     llvm_unreachable("Invalid classification for hi word.");
3482 
3483   case ComplexX87: // Previously handled.
3484   case NoClass:
3485     break;
3486 
3487   case Integer:
3488     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3489     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3490       return ABIArgInfo::getDirect(HighPart, 8);
3491     break;
3492   case SSE:
3493     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3494     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3495       return ABIArgInfo::getDirect(HighPart, 8);
3496     break;
3497 
3498     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3499     // is passed in the next available eightbyte chunk if the last used
3500     // vector register.
3501     //
3502     // SSEUP should always be preceded by SSE, just widen.
3503   case SSEUp:
3504     assert(Lo == SSE && "Unexpected SSEUp classification.");
3505     ResType = GetByteVectorType(RetTy);
3506     break;
3507 
3508     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3509     // returned together with the previous X87 value in %st0.
3510   case X87Up:
3511     // If X87Up is preceded by X87, we don't need to do
3512     // anything. However, in some cases with unions it may not be
3513     // preceded by X87. In such situations we follow gcc and pass the
3514     // extra bits in an SSE reg.
3515     if (Lo != X87) {
3516       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3517       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3518         return ABIArgInfo::getDirect(HighPart, 8);
3519     }
3520     break;
3521   }
3522 
3523   // If a high part was specified, merge it together with the low part.  It is
3524   // known to pass in the high eightbyte of the result.  We do this by forming a
3525   // first class struct aggregate with the high and low part: {low, high}
3526   if (HighPart)
3527     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3528 
3529   return ABIArgInfo::getDirect(ResType);
3530 }
3531 
3532 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3533   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3534   bool isNamedArg)
3535   const
3536 {
3537   Ty = useFirstFieldIfTransparentUnion(Ty);
3538 
3539   X86_64ABIInfo::Class Lo, Hi;
3540   classify(Ty, 0, Lo, Hi, isNamedArg);
3541 
3542   // Check some invariants.
3543   // FIXME: Enforce these by construction.
3544   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3545   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3546 
3547   neededInt = 0;
3548   neededSSE = 0;
3549   llvm::Type *ResType = nullptr;
3550   switch (Lo) {
3551   case NoClass:
3552     if (Hi == NoClass)
3553       return ABIArgInfo::getIgnore();
3554     // If the low part is just padding, it takes no register, leave ResType
3555     // null.
3556     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3557            "Unknown missing lo part");
3558     break;
3559 
3560     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3561     // on the stack.
3562   case Memory:
3563 
3564     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3565     // COMPLEX_X87, it is passed in memory.
3566   case X87:
3567   case ComplexX87:
3568     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3569       ++neededInt;
3570     return getIndirectResult(Ty, freeIntRegs);
3571 
3572   case SSEUp:
3573   case X87Up:
3574     llvm_unreachable("Invalid classification for lo word.");
3575 
3576     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3577     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3578     // and %r9 is used.
3579   case Integer:
3580     ++neededInt;
3581 
3582     // Pick an 8-byte type based on the preferred type.
3583     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3584 
3585     // If we have a sign or zero extended integer, make sure to return Extend
3586     // so that the parameter gets the right LLVM IR attributes.
3587     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3588       // Treat an enum type as its underlying type.
3589       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3590         Ty = EnumTy->getDecl()->getIntegerType();
3591 
3592       if (Ty->isIntegralOrEnumerationType() &&
3593           isPromotableIntegerTypeForABI(Ty))
3594         return ABIArgInfo::getExtend(Ty);
3595     }
3596 
3597     break;
3598 
3599     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3600     // available SSE register is used, the registers are taken in the
3601     // order from %xmm0 to %xmm7.
3602   case SSE: {
3603     llvm::Type *IRType = CGT.ConvertType(Ty);
3604     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3605     ++neededSSE;
3606     break;
3607   }
3608   }
3609 
3610   llvm::Type *HighPart = nullptr;
3611   switch (Hi) {
3612     // Memory was handled previously, ComplexX87 and X87 should
3613     // never occur as hi classes, and X87Up must be preceded by X87,
3614     // which is passed in memory.
3615   case Memory:
3616   case X87:
3617   case ComplexX87:
3618     llvm_unreachable("Invalid classification for hi word.");
3619 
3620   case NoClass: break;
3621 
3622   case Integer:
3623     ++neededInt;
3624     // Pick an 8-byte type based on the preferred type.
3625     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3626 
3627     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3628       return ABIArgInfo::getDirect(HighPart, 8);
3629     break;
3630 
3631     // X87Up generally doesn't occur here (long double is passed in
3632     // memory), except in situations involving unions.
3633   case X87Up:
3634   case SSE:
3635     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3636 
3637     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3638       return ABIArgInfo::getDirect(HighPart, 8);
3639 
3640     ++neededSSE;
3641     break;
3642 
3643     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3644     // eightbyte is passed in the upper half of the last used SSE
3645     // register.  This only happens when 128-bit vectors are passed.
3646   case SSEUp:
3647     assert(Lo == SSE && "Unexpected SSEUp classification");
3648     ResType = GetByteVectorType(Ty);
3649     break;
3650   }
3651 
3652   // If a high part was specified, merge it together with the low part.  It is
3653   // known to pass in the high eightbyte of the result.  We do this by forming a
3654   // first class struct aggregate with the high and low part: {low, high}
3655   if (HighPart)
3656     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3657 
3658   return ABIArgInfo::getDirect(ResType);
3659 }
3660 
3661 ABIArgInfo
3662 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3663                                              unsigned &NeededSSE) const {
3664   auto RT = Ty->getAs<RecordType>();
3665   assert(RT && "classifyRegCallStructType only valid with struct types");
3666 
3667   if (RT->getDecl()->hasFlexibleArrayMember())
3668     return getIndirectReturnResult(Ty);
3669 
3670   // Sum up bases
3671   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3672     if (CXXRD->isDynamicClass()) {
3673       NeededInt = NeededSSE = 0;
3674       return getIndirectReturnResult(Ty);
3675     }
3676 
3677     for (const auto &I : CXXRD->bases())
3678       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3679               .isIndirect()) {
3680         NeededInt = NeededSSE = 0;
3681         return getIndirectReturnResult(Ty);
3682       }
3683   }
3684 
3685   // Sum up members
3686   for (const auto *FD : RT->getDecl()->fields()) {
3687     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3688       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3689               .isIndirect()) {
3690         NeededInt = NeededSSE = 0;
3691         return getIndirectReturnResult(Ty);
3692       }
3693     } else {
3694       unsigned LocalNeededInt, LocalNeededSSE;
3695       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3696                                LocalNeededSSE, true)
3697               .isIndirect()) {
3698         NeededInt = NeededSSE = 0;
3699         return getIndirectReturnResult(Ty);
3700       }
3701       NeededInt += LocalNeededInt;
3702       NeededSSE += LocalNeededSSE;
3703     }
3704   }
3705 
3706   return ABIArgInfo::getDirect();
3707 }
3708 
3709 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3710                                                     unsigned &NeededInt,
3711                                                     unsigned &NeededSSE) const {
3712 
3713   NeededInt = 0;
3714   NeededSSE = 0;
3715 
3716   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3717 }
3718 
3719 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3720 
3721   const unsigned CallingConv = FI.getCallingConvention();
3722   // It is possible to force Win64 calling convention on any x86_64 target by
3723   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3724   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3725   if (CallingConv == llvm::CallingConv::Win64) {
3726     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3727     Win64ABIInfo.computeInfo(FI);
3728     return;
3729   }
3730 
3731   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3732 
3733   // Keep track of the number of assigned registers.
3734   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3735   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3736   unsigned NeededInt, NeededSSE;
3737 
3738   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3739     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3740         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3741       FI.getReturnInfo() =
3742           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3743       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3744         FreeIntRegs -= NeededInt;
3745         FreeSSERegs -= NeededSSE;
3746       } else {
3747         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3748       }
3749     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3750                getContext().getCanonicalType(FI.getReturnType()
3751                                                  ->getAs<ComplexType>()
3752                                                  ->getElementType()) ==
3753                    getContext().LongDoubleTy)
3754       // Complex Long Double Type is passed in Memory when Regcall
3755       // calling convention is used.
3756       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3757     else
3758       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3759   }
3760 
3761   // If the return value is indirect, then the hidden argument is consuming one
3762   // integer register.
3763   if (FI.getReturnInfo().isIndirect())
3764     --FreeIntRegs;
3765 
3766   // The chain argument effectively gives us another free register.
3767   if (FI.isChainCall())
3768     ++FreeIntRegs;
3769 
3770   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3771   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3772   // get assigned (in left-to-right order) for passing as follows...
3773   unsigned ArgNo = 0;
3774   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3775        it != ie; ++it, ++ArgNo) {
3776     bool IsNamedArg = ArgNo < NumRequiredArgs;
3777 
3778     if (IsRegCall && it->type->isStructureOrClassType())
3779       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3780     else
3781       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3782                                       NeededSSE, IsNamedArg);
3783 
3784     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3785     // eightbyte of an argument, the whole argument is passed on the
3786     // stack. If registers have already been assigned for some
3787     // eightbytes of such an argument, the assignments get reverted.
3788     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3789       FreeIntRegs -= NeededInt;
3790       FreeSSERegs -= NeededSSE;
3791     } else {
3792       it->info = getIndirectResult(it->type, FreeIntRegs);
3793     }
3794   }
3795 }
3796 
3797 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3798                                          Address VAListAddr, QualType Ty) {
3799   Address overflow_arg_area_p =
3800       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3801   llvm::Value *overflow_arg_area =
3802     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3803 
3804   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3805   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3806   // It isn't stated explicitly in the standard, but in practice we use
3807   // alignment greater than 16 where necessary.
3808   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3809   if (Align > CharUnits::fromQuantity(8)) {
3810     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3811                                                       Align);
3812   }
3813 
3814   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3815   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3816   llvm::Value *Res =
3817     CGF.Builder.CreateBitCast(overflow_arg_area,
3818                               llvm::PointerType::getUnqual(LTy));
3819 
3820   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3821   // l->overflow_arg_area + sizeof(type).
3822   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3823   // an 8 byte boundary.
3824 
3825   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3826   llvm::Value *Offset =
3827       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3828   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3829                                             "overflow_arg_area.next");
3830   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3831 
3832   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3833   return Address(Res, Align);
3834 }
3835 
3836 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3837                                  QualType Ty) const {
3838   // Assume that va_list type is correct; should be pointer to LLVM type:
3839   // struct {
3840   //   i32 gp_offset;
3841   //   i32 fp_offset;
3842   //   i8* overflow_arg_area;
3843   //   i8* reg_save_area;
3844   // };
3845   unsigned neededInt, neededSSE;
3846 
3847   Ty = getContext().getCanonicalType(Ty);
3848   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3849                                        /*isNamedArg*/false);
3850 
3851   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3852   // in the registers. If not go to step 7.
3853   if (!neededInt && !neededSSE)
3854     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3855 
3856   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3857   // general purpose registers needed to pass type and num_fp to hold
3858   // the number of floating point registers needed.
3859 
3860   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3861   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3862   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3863   //
3864   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3865   // register save space).
3866 
3867   llvm::Value *InRegs = nullptr;
3868   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3869   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3870   if (neededInt) {
3871     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3872     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3873     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3874     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3875   }
3876 
3877   if (neededSSE) {
3878     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3879     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3880     llvm::Value *FitsInFP =
3881       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3882     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3883     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3884   }
3885 
3886   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3887   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3888   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3889   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3890 
3891   // Emit code to load the value if it was passed in registers.
3892 
3893   CGF.EmitBlock(InRegBlock);
3894 
3895   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3896   // an offset of l->gp_offset and/or l->fp_offset. This may require
3897   // copying to a temporary location in case the parameter is passed
3898   // in different register classes or requires an alignment greater
3899   // than 8 for general purpose registers and 16 for XMM registers.
3900   //
3901   // FIXME: This really results in shameful code when we end up needing to
3902   // collect arguments from different places; often what should result in a
3903   // simple assembling of a structure from scattered addresses has many more
3904   // loads than necessary. Can we clean this up?
3905   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3906   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3907       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3908 
3909   Address RegAddr = Address::invalid();
3910   if (neededInt && neededSSE) {
3911     // FIXME: Cleanup.
3912     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3913     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3914     Address Tmp = CGF.CreateMemTemp(Ty);
3915     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3916     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3917     llvm::Type *TyLo = ST->getElementType(0);
3918     llvm::Type *TyHi = ST->getElementType(1);
3919     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3920            "Unexpected ABI info for mixed regs");
3921     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3922     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3923     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3924     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3925     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3926     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3927 
3928     // Copy the first element.
3929     // FIXME: Our choice of alignment here and below is probably pessimistic.
3930     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3931         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3932         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3933     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3934 
3935     // Copy the second element.
3936     V = CGF.Builder.CreateAlignedLoad(
3937         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3938         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3939     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3940 
3941     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3942   } else if (neededInt) {
3943     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3944                       CharUnits::fromQuantity(8));
3945     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3946 
3947     // Copy to a temporary if necessary to ensure the appropriate alignment.
3948     std::pair<CharUnits, CharUnits> SizeAlign =
3949         getContext().getTypeInfoInChars(Ty);
3950     uint64_t TySize = SizeAlign.first.getQuantity();
3951     CharUnits TyAlign = SizeAlign.second;
3952 
3953     // Copy into a temporary if the type is more aligned than the
3954     // register save area.
3955     if (TyAlign.getQuantity() > 8) {
3956       Address Tmp = CGF.CreateMemTemp(Ty);
3957       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3958       RegAddr = Tmp;
3959     }
3960 
3961   } else if (neededSSE == 1) {
3962     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3963                       CharUnits::fromQuantity(16));
3964     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3965   } else {
3966     assert(neededSSE == 2 && "Invalid number of needed registers!");
3967     // SSE registers are spaced 16 bytes apart in the register save
3968     // area, we need to collect the two eightbytes together.
3969     // The ABI isn't explicit about this, but it seems reasonable
3970     // to assume that the slots are 16-byte aligned, since the stack is
3971     // naturally 16-byte aligned and the prologue is expected to store
3972     // all the SSE registers to the RSA.
3973     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3974                                 CharUnits::fromQuantity(16));
3975     Address RegAddrHi =
3976       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3977                                              CharUnits::fromQuantity(16));
3978     llvm::Type *ST = AI.canHaveCoerceToType()
3979                          ? AI.getCoerceToType()
3980                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3981     llvm::Value *V;
3982     Address Tmp = CGF.CreateMemTemp(Ty);
3983     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3984     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3985         RegAddrLo, ST->getStructElementType(0)));
3986     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3987     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3988         RegAddrHi, ST->getStructElementType(1)));
3989     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3990 
3991     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3992   }
3993 
3994   // AMD64-ABI 3.5.7p5: Step 5. Set:
3995   // l->gp_offset = l->gp_offset + num_gp * 8
3996   // l->fp_offset = l->fp_offset + num_fp * 16.
3997   if (neededInt) {
3998     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3999     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4000                             gp_offset_p);
4001   }
4002   if (neededSSE) {
4003     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4004     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4005                             fp_offset_p);
4006   }
4007   CGF.EmitBranch(ContBlock);
4008 
4009   // Emit code to load the value if it was passed in memory.
4010 
4011   CGF.EmitBlock(InMemBlock);
4012   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4013 
4014   // Return the appropriate result.
4015 
4016   CGF.EmitBlock(ContBlock);
4017   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4018                                  "vaarg.addr");
4019   return ResAddr;
4020 }
4021 
4022 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4023                                    QualType Ty) const {
4024   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4025                           CGF.getContext().getTypeInfoInChars(Ty),
4026                           CharUnits::fromQuantity(8),
4027                           /*allowHigherAlign*/ false);
4028 }
4029 
4030 ABIArgInfo
4031 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
4032                                     const ABIArgInfo &current) const {
4033   // Assumes vectorCall calling convention.
4034   const Type *Base = nullptr;
4035   uint64_t NumElts = 0;
4036 
4037   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4038       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4039     FreeSSERegs -= NumElts;
4040     return getDirectX86Hva();
4041   }
4042   return current;
4043 }
4044 
4045 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4046                                       bool IsReturnType, bool IsVectorCall,
4047                                       bool IsRegCall) const {
4048 
4049   if (Ty->isVoidType())
4050     return ABIArgInfo::getIgnore();
4051 
4052   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4053     Ty = EnumTy->getDecl()->getIntegerType();
4054 
4055   TypeInfo Info = getContext().getTypeInfo(Ty);
4056   uint64_t Width = Info.Width;
4057   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4058 
4059   const RecordType *RT = Ty->getAs<RecordType>();
4060   if (RT) {
4061     if (!IsReturnType) {
4062       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4063         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4064     }
4065 
4066     if (RT->getDecl()->hasFlexibleArrayMember())
4067       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4068 
4069   }
4070 
4071   const Type *Base = nullptr;
4072   uint64_t NumElts = 0;
4073   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4074   // other targets.
4075   if ((IsVectorCall || IsRegCall) &&
4076       isHomogeneousAggregate(Ty, Base, NumElts)) {
4077     if (IsRegCall) {
4078       if (FreeSSERegs >= NumElts) {
4079         FreeSSERegs -= NumElts;
4080         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4081           return ABIArgInfo::getDirect();
4082         return ABIArgInfo::getExpand();
4083       }
4084       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4085     } else if (IsVectorCall) {
4086       if (FreeSSERegs >= NumElts &&
4087           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4088         FreeSSERegs -= NumElts;
4089         return ABIArgInfo::getDirect();
4090       } else if (IsReturnType) {
4091         return ABIArgInfo::getExpand();
4092       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4093         // HVAs are delayed and reclassified in the 2nd step.
4094         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4095       }
4096     }
4097   }
4098 
4099   if (Ty->isMemberPointerType()) {
4100     // If the member pointer is represented by an LLVM int or ptr, pass it
4101     // directly.
4102     llvm::Type *LLTy = CGT.ConvertType(Ty);
4103     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4104       return ABIArgInfo::getDirect();
4105   }
4106 
4107   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4108     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4109     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4110     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4111       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4112 
4113     // Otherwise, coerce it to a small integer.
4114     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4115   }
4116 
4117   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4118     switch (BT->getKind()) {
4119     case BuiltinType::Bool:
4120       // Bool type is always extended to the ABI, other builtin types are not
4121       // extended.
4122       return ABIArgInfo::getExtend(Ty);
4123 
4124     case BuiltinType::LongDouble:
4125       // Mingw64 GCC uses the old 80 bit extended precision floating point
4126       // unit. It passes them indirectly through memory.
4127       if (IsMingw64) {
4128         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4129         if (LDF == &llvm::APFloat::x87DoubleExtended())
4130           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4131       }
4132       break;
4133 
4134     case BuiltinType::Int128:
4135     case BuiltinType::UInt128:
4136       // If it's a parameter type, the normal ABI rule is that arguments larger
4137       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4138       // even though it isn't particularly efficient.
4139       if (!IsReturnType)
4140         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4141 
4142       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4143       // Clang matches them for compatibility.
4144       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4145           llvm::Type::getInt64Ty(getVMContext()), 2));
4146 
4147     default:
4148       break;
4149     }
4150   }
4151 
4152   if (Ty->isExtIntType()) {
4153     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4154     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4155     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4156     // anyway as long is it fits in them, so we don't have to check the power of
4157     // 2.
4158     if (Width <= 64)
4159       return ABIArgInfo::getDirect();
4160     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4161   }
4162 
4163   return ABIArgInfo::getDirect();
4164 }
4165 
4166 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4167                                              unsigned FreeSSERegs,
4168                                              bool IsVectorCall,
4169                                              bool IsRegCall) const {
4170   unsigned Count = 0;
4171   for (auto &I : FI.arguments()) {
4172     // Vectorcall in x64 only permits the first 6 arguments to be passed
4173     // as XMM/YMM registers.
4174     if (Count < VectorcallMaxParamNumAsReg)
4175       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4176     else {
4177       // Since these cannot be passed in registers, pretend no registers
4178       // are left.
4179       unsigned ZeroSSERegsAvail = 0;
4180       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4181                         IsVectorCall, IsRegCall);
4182     }
4183     ++Count;
4184   }
4185 
4186   for (auto &I : FI.arguments()) {
4187     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4188   }
4189 }
4190 
4191 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4192   const unsigned CC = FI.getCallingConvention();
4193   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4194   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4195 
4196   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4197   // classification rules.
4198   if (CC == llvm::CallingConv::X86_64_SysV) {
4199     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4200     SysVABIInfo.computeInfo(FI);
4201     return;
4202   }
4203 
4204   unsigned FreeSSERegs = 0;
4205   if (IsVectorCall) {
4206     // We can use up to 4 SSE return registers with vectorcall.
4207     FreeSSERegs = 4;
4208   } else if (IsRegCall) {
4209     // RegCall gives us 16 SSE registers.
4210     FreeSSERegs = 16;
4211   }
4212 
4213   if (!getCXXABI().classifyReturnType(FI))
4214     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4215                                   IsVectorCall, IsRegCall);
4216 
4217   if (IsVectorCall) {
4218     // We can use up to 6 SSE register parameters with vectorcall.
4219     FreeSSERegs = 6;
4220   } else if (IsRegCall) {
4221     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4222     FreeSSERegs = 16;
4223   }
4224 
4225   if (IsVectorCall) {
4226     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4227   } else {
4228     for (auto &I : FI.arguments())
4229       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4230   }
4231 
4232 }
4233 
4234 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4235                                     QualType Ty) const {
4236 
4237   bool IsIndirect = false;
4238 
4239   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4240   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4241   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4242     uint64_t Width = getContext().getTypeSize(Ty);
4243     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4244   }
4245 
4246   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4247                           CGF.getContext().getTypeInfoInChars(Ty),
4248                           CharUnits::fromQuantity(8),
4249                           /*allowHigherAlign*/ false);
4250 }
4251 
4252 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4253                                         llvm::Value *Address, bool Is64Bit,
4254                                         bool IsAIX) {
4255   // This is calculated from the LLVM and GCC tables and verified
4256   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4257 
4258   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4259 
4260   llvm::IntegerType *i8 = CGF.Int8Ty;
4261   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4262   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4263   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4264 
4265   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4266   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4267 
4268   // 32-63: fp0-31, the 8-byte floating-point registers
4269   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4270 
4271   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4272   // 64: mq
4273   // 65: lr
4274   // 66: ctr
4275   // 67: ap
4276   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4277 
4278   // 68-76 are various 4-byte special-purpose registers:
4279   // 68-75 cr0-7
4280   // 76: xer
4281   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4282 
4283   // 77-108: v0-31, the 16-byte vector registers
4284   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4285 
4286   // 109: vrsave
4287   // 110: vscr
4288   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4289 
4290   // AIX does not utilize the rest of the registers.
4291   if (IsAIX)
4292     return false;
4293 
4294   // 111: spe_acc
4295   // 112: spefscr
4296   // 113: sfp
4297   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4298 
4299   if (!Is64Bit)
4300     return false;
4301 
4302   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4303   // or above CPU.
4304   // 64-bit only registers:
4305   // 114: tfhar
4306   // 115: tfiar
4307   // 116: texasr
4308   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4309 
4310   return false;
4311 }
4312 
4313 // AIX
4314 namespace {
4315 /// AIXABIInfo - The AIX XCOFF ABI information.
4316 class AIXABIInfo : public ABIInfo {
4317   const bool Is64Bit;
4318   const unsigned PtrByteSize;
4319   CharUnits getParamTypeAlignment(QualType Ty) const;
4320 
4321 public:
4322   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4323       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4324 
4325   bool isPromotableTypeForABI(QualType Ty) const;
4326 
4327   ABIArgInfo classifyReturnType(QualType RetTy) const;
4328   ABIArgInfo classifyArgumentType(QualType Ty) const;
4329 
4330   void computeInfo(CGFunctionInfo &FI) const override {
4331     if (!getCXXABI().classifyReturnType(FI))
4332       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4333 
4334     for (auto &I : FI.arguments())
4335       I.info = classifyArgumentType(I.type);
4336   }
4337 
4338   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4339                     QualType Ty) const override;
4340 };
4341 
4342 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4343   const bool Is64Bit;
4344 
4345 public:
4346   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4347       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4348         Is64Bit(Is64Bit) {}
4349   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4350     return 1; // r1 is the dedicated stack pointer
4351   }
4352 
4353   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4354                                llvm::Value *Address) const override;
4355 };
4356 } // namespace
4357 
4358 // Return true if the ABI requires Ty to be passed sign- or zero-
4359 // extended to 32/64 bits.
4360 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4361   // Treat an enum type as its underlying type.
4362   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4363     Ty = EnumTy->getDecl()->getIntegerType();
4364 
4365   // Promotable integer types are required to be promoted by the ABI.
4366   if (Ty->isPromotableIntegerType())
4367     return true;
4368 
4369   if (!Is64Bit)
4370     return false;
4371 
4372   // For 64 bit mode, in addition to the usual promotable integer types, we also
4373   // need to extend all 32-bit types, since the ABI requires promotion to 64
4374   // bits.
4375   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4376     switch (BT->getKind()) {
4377     case BuiltinType::Int:
4378     case BuiltinType::UInt:
4379       return true;
4380     default:
4381       break;
4382     }
4383 
4384   return false;
4385 }
4386 
4387 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4388   if (RetTy->isAnyComplexType())
4389     llvm::report_fatal_error("complex type is not supported on AIX yet");
4390 
4391   if (RetTy->isVectorType())
4392     llvm::report_fatal_error("vector type is not supported on AIX yet");
4393 
4394   if (RetTy->isVoidType())
4395     return ABIArgInfo::getIgnore();
4396 
4397   // TODO:  Evaluate if AIX power alignment rule would have an impact on the
4398   // alignment here.
4399   if (isAggregateTypeForABI(RetTy))
4400     return getNaturalAlignIndirect(RetTy);
4401 
4402   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4403                                         : ABIArgInfo::getDirect());
4404 }
4405 
4406 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4407   Ty = useFirstFieldIfTransparentUnion(Ty);
4408 
4409   if (Ty->isAnyComplexType())
4410     llvm::report_fatal_error("complex type is not supported on AIX yet");
4411 
4412   if (Ty->isVectorType())
4413     llvm::report_fatal_error("vector type is not supported on AIX yet");
4414 
4415   // TODO:  Evaluate if AIX power alignment rule would have an impact on the
4416   // alignment here.
4417   if (isAggregateTypeForABI(Ty)) {
4418     // Records with non-trivial destructors/copy-constructors should not be
4419     // passed by value.
4420     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4421       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4422 
4423     CharUnits CCAlign = getParamTypeAlignment(Ty);
4424     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4425 
4426     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4427                                    /*Realign*/ TyAlign > CCAlign);
4428   }
4429 
4430   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4431                                      : ABIArgInfo::getDirect());
4432 }
4433 
4434 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4435   if (Ty->isAnyComplexType())
4436     llvm::report_fatal_error("complex type is not supported on AIX yet");
4437 
4438   if (Ty->isVectorType())
4439     llvm::report_fatal_error("vector type is not supported on AIX yet");
4440 
4441   // If the structure contains a vector type, the alignment is 16.
4442   if (isRecordWithSIMDVectorType(getContext(), Ty))
4443     return CharUnits::fromQuantity(16);
4444 
4445   return CharUnits::fromQuantity(PtrByteSize);
4446 }
4447 
4448 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4449                               QualType Ty) const {
4450   if (Ty->isAnyComplexType())
4451     llvm::report_fatal_error("complex type is not supported on AIX yet");
4452 
4453   if (Ty->isVectorType())
4454     llvm::report_fatal_error("vector type is not supported on AIX yet");
4455 
4456   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4457   TypeInfo.second = getParamTypeAlignment(Ty);
4458 
4459   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4460 
4461   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4462                           SlotSize, /*AllowHigher*/ true);
4463 }
4464 
4465 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4466     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4467   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4468 }
4469 
4470 // PowerPC-32
4471 namespace {
4472 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4473 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4474   bool IsSoftFloatABI;
4475   bool IsRetSmallStructInRegABI;
4476 
4477   CharUnits getParamTypeAlignment(QualType Ty) const;
4478 
4479 public:
4480   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4481                      bool RetSmallStructInRegABI)
4482       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4483         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4484 
4485   ABIArgInfo classifyReturnType(QualType RetTy) const;
4486 
4487   void computeInfo(CGFunctionInfo &FI) const override {
4488     if (!getCXXABI().classifyReturnType(FI))
4489       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4490     for (auto &I : FI.arguments())
4491       I.info = classifyArgumentType(I.type);
4492   }
4493 
4494   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4495                     QualType Ty) const override;
4496 };
4497 
4498 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4499 public:
4500   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4501                          bool RetSmallStructInRegABI)
4502       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4503             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4504 
4505   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4506                                      const CodeGenOptions &Opts);
4507 
4508   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4509     // This is recovered from gcc output.
4510     return 1; // r1 is the dedicated stack pointer
4511   }
4512 
4513   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4514                                llvm::Value *Address) const override;
4515 };
4516 }
4517 
4518 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4519   // Complex types are passed just like their elements.
4520   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4521     Ty = CTy->getElementType();
4522 
4523   if (Ty->isVectorType())
4524     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4525                                                                        : 4);
4526 
4527   // For single-element float/vector structs, we consider the whole type
4528   // to have the same alignment requirements as its single element.
4529   const Type *AlignTy = nullptr;
4530   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4531     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4532     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4533         (BT && BT->isFloatingPoint()))
4534       AlignTy = EltType;
4535   }
4536 
4537   if (AlignTy)
4538     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4539   return CharUnits::fromQuantity(4);
4540 }
4541 
4542 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4543   uint64_t Size;
4544 
4545   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4546   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4547       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4548     // System V ABI (1995), page 3-22, specified:
4549     // > A structure or union whose size is less than or equal to 8 bytes
4550     // > shall be returned in r3 and r4, as if it were first stored in the
4551     // > 8-byte aligned memory area and then the low addressed word were
4552     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4553     // > the last member of the structure or union are not defined.
4554     //
4555     // GCC for big-endian PPC32 inserts the pad before the first member,
4556     // not "beyond the last member" of the struct.  To stay compatible
4557     // with GCC, we coerce the struct to an integer of the same size.
4558     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4559     if (Size == 0)
4560       return ABIArgInfo::getIgnore();
4561     else {
4562       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4563       return ABIArgInfo::getDirect(CoerceTy);
4564     }
4565   }
4566 
4567   return DefaultABIInfo::classifyReturnType(RetTy);
4568 }
4569 
4570 // TODO: this implementation is now likely redundant with
4571 // DefaultABIInfo::EmitVAArg.
4572 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4573                                       QualType Ty) const {
4574   if (getTarget().getTriple().isOSDarwin()) {
4575     auto TI = getContext().getTypeInfoInChars(Ty);
4576     TI.second = getParamTypeAlignment(Ty);
4577 
4578     CharUnits SlotSize = CharUnits::fromQuantity(4);
4579     return emitVoidPtrVAArg(CGF, VAList, Ty,
4580                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4581                             /*AllowHigherAlign=*/true);
4582   }
4583 
4584   const unsigned OverflowLimit = 8;
4585   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4586     // TODO: Implement this. For now ignore.
4587     (void)CTy;
4588     return Address::invalid(); // FIXME?
4589   }
4590 
4591   // struct __va_list_tag {
4592   //   unsigned char gpr;
4593   //   unsigned char fpr;
4594   //   unsigned short reserved;
4595   //   void *overflow_arg_area;
4596   //   void *reg_save_area;
4597   // };
4598 
4599   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4600   bool isInt =
4601       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4602   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4603 
4604   // All aggregates are passed indirectly?  That doesn't seem consistent
4605   // with the argument-lowering code.
4606   bool isIndirect = Ty->isAggregateType();
4607 
4608   CGBuilderTy &Builder = CGF.Builder;
4609 
4610   // The calling convention either uses 1-2 GPRs or 1 FPR.
4611   Address NumRegsAddr = Address::invalid();
4612   if (isInt || IsSoftFloatABI) {
4613     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4614   } else {
4615     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4616   }
4617 
4618   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4619 
4620   // "Align" the register count when TY is i64.
4621   if (isI64 || (isF64 && IsSoftFloatABI)) {
4622     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4623     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4624   }
4625 
4626   llvm::Value *CC =
4627       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4628 
4629   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4630   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4631   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4632 
4633   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4634 
4635   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4636   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4637 
4638   // Case 1: consume registers.
4639   Address RegAddr = Address::invalid();
4640   {
4641     CGF.EmitBlock(UsingRegs);
4642 
4643     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4644     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4645                       CharUnits::fromQuantity(8));
4646     assert(RegAddr.getElementType() == CGF.Int8Ty);
4647 
4648     // Floating-point registers start after the general-purpose registers.
4649     if (!(isInt || IsSoftFloatABI)) {
4650       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4651                                                    CharUnits::fromQuantity(32));
4652     }
4653 
4654     // Get the address of the saved value by scaling the number of
4655     // registers we've used by the number of
4656     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4657     llvm::Value *RegOffset =
4658       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4659     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4660                                             RegAddr.getPointer(), RegOffset),
4661                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4662     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4663 
4664     // Increase the used-register count.
4665     NumRegs =
4666       Builder.CreateAdd(NumRegs,
4667                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4668     Builder.CreateStore(NumRegs, NumRegsAddr);
4669 
4670     CGF.EmitBranch(Cont);
4671   }
4672 
4673   // Case 2: consume space in the overflow area.
4674   Address MemAddr = Address::invalid();
4675   {
4676     CGF.EmitBlock(UsingOverflow);
4677 
4678     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4679 
4680     // Everything in the overflow area is rounded up to a size of at least 4.
4681     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4682 
4683     CharUnits Size;
4684     if (!isIndirect) {
4685       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4686       Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4687     } else {
4688       Size = CGF.getPointerSize();
4689     }
4690 
4691     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4692     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4693                          OverflowAreaAlign);
4694     // Round up address of argument to alignment
4695     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4696     if (Align > OverflowAreaAlign) {
4697       llvm::Value *Ptr = OverflowArea.getPointer();
4698       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4699                                                            Align);
4700     }
4701 
4702     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4703 
4704     // Increase the overflow area.
4705     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4706     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4707     CGF.EmitBranch(Cont);
4708   }
4709 
4710   CGF.EmitBlock(Cont);
4711 
4712   // Merge the cases with a phi.
4713   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4714                                 "vaarg.addr");
4715 
4716   // Load the pointer if the argument was passed indirectly.
4717   if (isIndirect) {
4718     Result = Address(Builder.CreateLoad(Result, "aggr"),
4719                      getContext().getTypeAlignInChars(Ty));
4720   }
4721 
4722   return Result;
4723 }
4724 
4725 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4726     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4727   assert(Triple.getArch() == llvm::Triple::ppc);
4728 
4729   switch (Opts.getStructReturnConvention()) {
4730   case CodeGenOptions::SRCK_Default:
4731     break;
4732   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4733     return false;
4734   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4735     return true;
4736   }
4737 
4738   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4739     return true;
4740 
4741   return false;
4742 }
4743 
4744 bool
4745 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4746                                                 llvm::Value *Address) const {
4747   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4748                                      /*IsAIX*/ false);
4749 }
4750 
4751 // PowerPC-64
4752 
4753 namespace {
4754 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4755 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4756 public:
4757   enum ABIKind {
4758     ELFv1 = 0,
4759     ELFv2
4760   };
4761 
4762 private:
4763   static const unsigned GPRBits = 64;
4764   ABIKind Kind;
4765   bool HasQPX;
4766   bool IsSoftFloatABI;
4767 
4768   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4769   // will be passed in a QPX register.
4770   bool IsQPXVectorTy(const Type *Ty) const {
4771     if (!HasQPX)
4772       return false;
4773 
4774     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4775       unsigned NumElements = VT->getNumElements();
4776       if (NumElements == 1)
4777         return false;
4778 
4779       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4780         if (getContext().getTypeSize(Ty) <= 256)
4781           return true;
4782       } else if (VT->getElementType()->
4783                    isSpecificBuiltinType(BuiltinType::Float)) {
4784         if (getContext().getTypeSize(Ty) <= 128)
4785           return true;
4786       }
4787     }
4788 
4789     return false;
4790   }
4791 
4792   bool IsQPXVectorTy(QualType Ty) const {
4793     return IsQPXVectorTy(Ty.getTypePtr());
4794   }
4795 
4796 public:
4797   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4798                      bool SoftFloatABI)
4799       : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4800         IsSoftFloatABI(SoftFloatABI) {}
4801 
4802   bool isPromotableTypeForABI(QualType Ty) const;
4803   CharUnits getParamTypeAlignment(QualType Ty) const;
4804 
4805   ABIArgInfo classifyReturnType(QualType RetTy) const;
4806   ABIArgInfo classifyArgumentType(QualType Ty) const;
4807 
4808   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4809   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4810                                          uint64_t Members) const override;
4811 
4812   // TODO: We can add more logic to computeInfo to improve performance.
4813   // Example: For aggregate arguments that fit in a register, we could
4814   // use getDirectInReg (as is done below for structs containing a single
4815   // floating-point value) to avoid pushing them to memory on function
4816   // entry.  This would require changing the logic in PPCISelLowering
4817   // when lowering the parameters in the caller and args in the callee.
4818   void computeInfo(CGFunctionInfo &FI) const override {
4819     if (!getCXXABI().classifyReturnType(FI))
4820       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4821     for (auto &I : FI.arguments()) {
4822       // We rely on the default argument classification for the most part.
4823       // One exception:  An aggregate containing a single floating-point
4824       // or vector item must be passed in a register if one is available.
4825       const Type *T = isSingleElementStruct(I.type, getContext());
4826       if (T) {
4827         const BuiltinType *BT = T->getAs<BuiltinType>();
4828         if (IsQPXVectorTy(T) ||
4829             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4830             (BT && BT->isFloatingPoint())) {
4831           QualType QT(T, 0);
4832           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4833           continue;
4834         }
4835       }
4836       I.info = classifyArgumentType(I.type);
4837     }
4838   }
4839 
4840   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4841                     QualType Ty) const override;
4842 
4843   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4844                                     bool asReturnValue) const override {
4845     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4846   }
4847 
4848   bool isSwiftErrorInRegister() const override {
4849     return false;
4850   }
4851 };
4852 
4853 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4854 
4855 public:
4856   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4857                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4858                                bool SoftFloatABI)
4859       : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>(
4860             CGT, Kind, HasQPX, SoftFloatABI)) {}
4861 
4862   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4863     // This is recovered from gcc output.
4864     return 1; // r1 is the dedicated stack pointer
4865   }
4866 
4867   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4868                                llvm::Value *Address) const override;
4869 };
4870 
4871 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4872 public:
4873   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4874 
4875   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4876     // This is recovered from gcc output.
4877     return 1; // r1 is the dedicated stack pointer
4878   }
4879 
4880   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4881                                llvm::Value *Address) const override;
4882 };
4883 
4884 }
4885 
4886 // Return true if the ABI requires Ty to be passed sign- or zero-
4887 // extended to 64 bits.
4888 bool
4889 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4890   // Treat an enum type as its underlying type.
4891   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4892     Ty = EnumTy->getDecl()->getIntegerType();
4893 
4894   // Promotable integer types are required to be promoted by the ABI.
4895   if (isPromotableIntegerTypeForABI(Ty))
4896     return true;
4897 
4898   // In addition to the usual promotable integer types, we also need to
4899   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4900   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4901     switch (BT->getKind()) {
4902     case BuiltinType::Int:
4903     case BuiltinType::UInt:
4904       return true;
4905     default:
4906       break;
4907     }
4908 
4909   if (const auto *EIT = Ty->getAs<ExtIntType>())
4910     if (EIT->getNumBits() < 64)
4911       return true;
4912 
4913   return false;
4914 }
4915 
4916 /// isAlignedParamType - Determine whether a type requires 16-byte or
4917 /// higher alignment in the parameter area.  Always returns at least 8.
4918 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4919   // Complex types are passed just like their elements.
4920   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4921     Ty = CTy->getElementType();
4922 
4923   // Only vector types of size 16 bytes need alignment (larger types are
4924   // passed via reference, smaller types are not aligned).
4925   if (IsQPXVectorTy(Ty)) {
4926     if (getContext().getTypeSize(Ty) > 128)
4927       return CharUnits::fromQuantity(32);
4928 
4929     return CharUnits::fromQuantity(16);
4930   } else if (Ty->isVectorType()) {
4931     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4932   }
4933 
4934   // For single-element float/vector structs, we consider the whole type
4935   // to have the same alignment requirements as its single element.
4936   const Type *AlignAsType = nullptr;
4937   const Type *EltType = isSingleElementStruct(Ty, getContext());
4938   if (EltType) {
4939     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4940     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4941          getContext().getTypeSize(EltType) == 128) ||
4942         (BT && BT->isFloatingPoint()))
4943       AlignAsType = EltType;
4944   }
4945 
4946   // Likewise for ELFv2 homogeneous aggregates.
4947   const Type *Base = nullptr;
4948   uint64_t Members = 0;
4949   if (!AlignAsType && Kind == ELFv2 &&
4950       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4951     AlignAsType = Base;
4952 
4953   // With special case aggregates, only vector base types need alignment.
4954   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4955     if (getContext().getTypeSize(AlignAsType) > 128)
4956       return CharUnits::fromQuantity(32);
4957 
4958     return CharUnits::fromQuantity(16);
4959   } else if (AlignAsType) {
4960     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4961   }
4962 
4963   // Otherwise, we only need alignment for any aggregate type that
4964   // has an alignment requirement of >= 16 bytes.
4965   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4966     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4967       return CharUnits::fromQuantity(32);
4968     return CharUnits::fromQuantity(16);
4969   }
4970 
4971   return CharUnits::fromQuantity(8);
4972 }
4973 
4974 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4975 /// aggregate.  Base is set to the base element type, and Members is set
4976 /// to the number of base elements.
4977 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4978                                      uint64_t &Members) const {
4979   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4980     uint64_t NElements = AT->getSize().getZExtValue();
4981     if (NElements == 0)
4982       return false;
4983     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4984       return false;
4985     Members *= NElements;
4986   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4987     const RecordDecl *RD = RT->getDecl();
4988     if (RD->hasFlexibleArrayMember())
4989       return false;
4990 
4991     Members = 0;
4992 
4993     // If this is a C++ record, check the bases first.
4994     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4995       for (const auto &I : CXXRD->bases()) {
4996         // Ignore empty records.
4997         if (isEmptyRecord(getContext(), I.getType(), true))
4998           continue;
4999 
5000         uint64_t FldMembers;
5001         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5002           return false;
5003 
5004         Members += FldMembers;
5005       }
5006     }
5007 
5008     for (const auto *FD : RD->fields()) {
5009       // Ignore (non-zero arrays of) empty records.
5010       QualType FT = FD->getType();
5011       while (const ConstantArrayType *AT =
5012              getContext().getAsConstantArrayType(FT)) {
5013         if (AT->getSize().getZExtValue() == 0)
5014           return false;
5015         FT = AT->getElementType();
5016       }
5017       if (isEmptyRecord(getContext(), FT, true))
5018         continue;
5019 
5020       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5021       if (getContext().getLangOpts().CPlusPlus &&
5022           FD->isZeroLengthBitField(getContext()))
5023         continue;
5024 
5025       uint64_t FldMembers;
5026       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5027         return false;
5028 
5029       Members = (RD->isUnion() ?
5030                  std::max(Members, FldMembers) : Members + FldMembers);
5031     }
5032 
5033     if (!Base)
5034       return false;
5035 
5036     // Ensure there is no padding.
5037     if (getContext().getTypeSize(Base) * Members !=
5038         getContext().getTypeSize(Ty))
5039       return false;
5040   } else {
5041     Members = 1;
5042     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5043       Members = 2;
5044       Ty = CT->getElementType();
5045     }
5046 
5047     // Most ABIs only support float, double, and some vector type widths.
5048     if (!isHomogeneousAggregateBaseType(Ty))
5049       return false;
5050 
5051     // The base type must be the same for all members.  Types that
5052     // agree in both total size and mode (float vs. vector) are
5053     // treated as being equivalent here.
5054     const Type *TyPtr = Ty.getTypePtr();
5055     if (!Base) {
5056       Base = TyPtr;
5057       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5058       // so make sure to widen it explicitly.
5059       if (const VectorType *VT = Base->getAs<VectorType>()) {
5060         QualType EltTy = VT->getElementType();
5061         unsigned NumElements =
5062             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5063         Base = getContext()
5064                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5065                    .getTypePtr();
5066       }
5067     }
5068 
5069     if (Base->isVectorType() != TyPtr->isVectorType() ||
5070         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5071       return false;
5072   }
5073   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5074 }
5075 
5076 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5077   // Homogeneous aggregates for ELFv2 must have base types of float,
5078   // double, long double, or 128-bit vectors.
5079   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5080     if (BT->getKind() == BuiltinType::Float ||
5081         BT->getKind() == BuiltinType::Double ||
5082         BT->getKind() == BuiltinType::LongDouble ||
5083         (getContext().getTargetInfo().hasFloat128Type() &&
5084           (BT->getKind() == BuiltinType::Float128))) {
5085       if (IsSoftFloatABI)
5086         return false;
5087       return true;
5088     }
5089   }
5090   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5091     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
5092       return true;
5093   }
5094   return false;
5095 }
5096 
5097 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5098     const Type *Base, uint64_t Members) const {
5099   // Vector and fp128 types require one register, other floating point types
5100   // require one or two registers depending on their size.
5101   uint32_t NumRegs =
5102       ((getContext().getTargetInfo().hasFloat128Type() &&
5103           Base->isFloat128Type()) ||
5104         Base->isVectorType()) ? 1
5105                               : (getContext().getTypeSize(Base) + 63) / 64;
5106 
5107   // Homogeneous Aggregates may occupy at most 8 registers.
5108   return Members * NumRegs <= 8;
5109 }
5110 
5111 ABIArgInfo
5112 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5113   Ty = useFirstFieldIfTransparentUnion(Ty);
5114 
5115   if (Ty->isAnyComplexType())
5116     return ABIArgInfo::getDirect();
5117 
5118   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5119   // or via reference (larger than 16 bytes).
5120   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
5121     uint64_t Size = getContext().getTypeSize(Ty);
5122     if (Size > 128)
5123       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5124     else if (Size < 128) {
5125       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5126       return ABIArgInfo::getDirect(CoerceTy);
5127     }
5128   }
5129 
5130   if (const auto *EIT = Ty->getAs<ExtIntType>())
5131     if (EIT->getNumBits() > 128)
5132       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5133 
5134   if (isAggregateTypeForABI(Ty)) {
5135     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5136       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5137 
5138     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5139     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5140 
5141     // ELFv2 homogeneous aggregates are passed as array types.
5142     const Type *Base = nullptr;
5143     uint64_t Members = 0;
5144     if (Kind == ELFv2 &&
5145         isHomogeneousAggregate(Ty, Base, Members)) {
5146       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5147       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5148       return ABIArgInfo::getDirect(CoerceTy);
5149     }
5150 
5151     // If an aggregate may end up fully in registers, we do not
5152     // use the ByVal method, but pass the aggregate as array.
5153     // This is usually beneficial since we avoid forcing the
5154     // back-end to store the argument to memory.
5155     uint64_t Bits = getContext().getTypeSize(Ty);
5156     if (Bits > 0 && Bits <= 8 * GPRBits) {
5157       llvm::Type *CoerceTy;
5158 
5159       // Types up to 8 bytes are passed as integer type (which will be
5160       // properly aligned in the argument save area doubleword).
5161       if (Bits <= GPRBits)
5162         CoerceTy =
5163             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5164       // Larger types are passed as arrays, with the base type selected
5165       // according to the required alignment in the save area.
5166       else {
5167         uint64_t RegBits = ABIAlign * 8;
5168         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5169         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5170         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5171       }
5172 
5173       return ABIArgInfo::getDirect(CoerceTy);
5174     }
5175 
5176     // All other aggregates are passed ByVal.
5177     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5178                                    /*ByVal=*/true,
5179                                    /*Realign=*/TyAlign > ABIAlign);
5180   }
5181 
5182   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5183                                      : ABIArgInfo::getDirect());
5184 }
5185 
5186 ABIArgInfo
5187 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5188   if (RetTy->isVoidType())
5189     return ABIArgInfo::getIgnore();
5190 
5191   if (RetTy->isAnyComplexType())
5192     return ABIArgInfo::getDirect();
5193 
5194   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5195   // or via reference (larger than 16 bytes).
5196   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
5197     uint64_t Size = getContext().getTypeSize(RetTy);
5198     if (Size > 128)
5199       return getNaturalAlignIndirect(RetTy);
5200     else if (Size < 128) {
5201       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5202       return ABIArgInfo::getDirect(CoerceTy);
5203     }
5204   }
5205 
5206   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5207     if (EIT->getNumBits() > 128)
5208       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5209 
5210   if (isAggregateTypeForABI(RetTy)) {
5211     // ELFv2 homogeneous aggregates are returned as array types.
5212     const Type *Base = nullptr;
5213     uint64_t Members = 0;
5214     if (Kind == ELFv2 &&
5215         isHomogeneousAggregate(RetTy, Base, Members)) {
5216       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5217       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5218       return ABIArgInfo::getDirect(CoerceTy);
5219     }
5220 
5221     // ELFv2 small aggregates are returned in up to two registers.
5222     uint64_t Bits = getContext().getTypeSize(RetTy);
5223     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5224       if (Bits == 0)
5225         return ABIArgInfo::getIgnore();
5226 
5227       llvm::Type *CoerceTy;
5228       if (Bits > GPRBits) {
5229         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5230         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5231       } else
5232         CoerceTy =
5233             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5234       return ABIArgInfo::getDirect(CoerceTy);
5235     }
5236 
5237     // All other aggregates are returned indirectly.
5238     return getNaturalAlignIndirect(RetTy);
5239   }
5240 
5241   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5242                                         : ABIArgInfo::getDirect());
5243 }
5244 
5245 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5246 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5247                                       QualType Ty) const {
5248   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5249   TypeInfo.second = getParamTypeAlignment(Ty);
5250 
5251   CharUnits SlotSize = CharUnits::fromQuantity(8);
5252 
5253   // If we have a complex type and the base type is smaller than 8 bytes,
5254   // the ABI calls for the real and imaginary parts to be right-adjusted
5255   // in separate doublewords.  However, Clang expects us to produce a
5256   // pointer to a structure with the two parts packed tightly.  So generate
5257   // loads of the real and imaginary parts relative to the va_list pointer,
5258   // and store them to a temporary structure.
5259   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5260     CharUnits EltSize = TypeInfo.first / 2;
5261     if (EltSize < SlotSize) {
5262       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5263                                             SlotSize * 2, SlotSize,
5264                                             SlotSize, /*AllowHigher*/ true);
5265 
5266       Address RealAddr = Addr;
5267       Address ImagAddr = RealAddr;
5268       if (CGF.CGM.getDataLayout().isBigEndian()) {
5269         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5270                                                           SlotSize - EltSize);
5271         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5272                                                       2 * SlotSize - EltSize);
5273       } else {
5274         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5275       }
5276 
5277       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5278       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5279       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5280       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5281       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5282 
5283       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5284       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5285                              /*init*/ true);
5286       return Temp;
5287     }
5288   }
5289 
5290   // Otherwise, just use the general rule.
5291   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5292                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5293 }
5294 
5295 bool
5296 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5297   CodeGen::CodeGenFunction &CGF,
5298   llvm::Value *Address) const {
5299   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5300                                      /*IsAIX*/ false);
5301 }
5302 
5303 bool
5304 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5305                                                 llvm::Value *Address) const {
5306   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5307                                      /*IsAIX*/ false);
5308 }
5309 
5310 //===----------------------------------------------------------------------===//
5311 // AArch64 ABI Implementation
5312 //===----------------------------------------------------------------------===//
5313 
5314 namespace {
5315 
5316 class AArch64ABIInfo : public SwiftABIInfo {
5317 public:
5318   enum ABIKind {
5319     AAPCS = 0,
5320     DarwinPCS,
5321     Win64
5322   };
5323 
5324 private:
5325   ABIKind Kind;
5326 
5327 public:
5328   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5329     : SwiftABIInfo(CGT), Kind(Kind) {}
5330 
5331 private:
5332   ABIKind getABIKind() const { return Kind; }
5333   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5334 
5335   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5336   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5337   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5338   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5339                                          uint64_t Members) const override;
5340 
5341   bool isIllegalVectorType(QualType Ty) const;
5342 
5343   void computeInfo(CGFunctionInfo &FI) const override {
5344     if (!::classifyReturnType(getCXXABI(), FI, *this))
5345       FI.getReturnInfo() =
5346           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5347 
5348     for (auto &it : FI.arguments())
5349       it.info = classifyArgumentType(it.type);
5350   }
5351 
5352   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5353                           CodeGenFunction &CGF) const;
5354 
5355   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5356                          CodeGenFunction &CGF) const;
5357 
5358   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5359                     QualType Ty) const override {
5360     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5361                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5362                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5363   }
5364 
5365   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5366                       QualType Ty) const override;
5367 
5368   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5369                                     bool asReturnValue) const override {
5370     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5371   }
5372   bool isSwiftErrorInRegister() const override {
5373     return true;
5374   }
5375 
5376   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5377                                  unsigned elts) const override;
5378 
5379   bool allowBFloatArgsAndRet() const override {
5380     return getTarget().hasBFloat16Type();
5381   }
5382 };
5383 
5384 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5385 public:
5386   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5387       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5388 
5389   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5390     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5391   }
5392 
5393   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5394     return 31;
5395   }
5396 
5397   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5398 
5399   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5400                            CodeGen::CodeGenModule &CGM) const override {
5401     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5402     if (!FD)
5403       return;
5404 
5405     LangOptions::SignReturnAddressScopeKind Scope =
5406         CGM.getLangOpts().getSignReturnAddressScope();
5407     LangOptions::SignReturnAddressKeyKind Key =
5408         CGM.getLangOpts().getSignReturnAddressKey();
5409     bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement;
5410     if (const auto *TA = FD->getAttr<TargetAttr>()) {
5411       ParsedTargetAttr Attr = TA->parse();
5412       if (!Attr.BranchProtection.empty()) {
5413         TargetInfo::BranchProtectionInfo BPI;
5414         StringRef Error;
5415         (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5416                                                        BPI, Error);
5417         assert(Error.empty());
5418         Scope = BPI.SignReturnAddr;
5419         Key = BPI.SignKey;
5420         BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5421       }
5422     }
5423 
5424     auto *Fn = cast<llvm::Function>(GV);
5425     if (Scope != LangOptions::SignReturnAddressScopeKind::None) {
5426       Fn->addFnAttr("sign-return-address",
5427                     Scope == LangOptions::SignReturnAddressScopeKind::All
5428                         ? "all"
5429                         : "non-leaf");
5430 
5431       Fn->addFnAttr("sign-return-address-key",
5432                     Key == LangOptions::SignReturnAddressKeyKind::AKey
5433                         ? "a_key"
5434                         : "b_key");
5435     }
5436 
5437     if (BranchTargetEnforcement)
5438       Fn->addFnAttr("branch-target-enforcement");
5439   }
5440 };
5441 
5442 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5443 public:
5444   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5445       : AArch64TargetCodeGenInfo(CGT, K) {}
5446 
5447   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5448                            CodeGen::CodeGenModule &CGM) const override;
5449 
5450   void getDependentLibraryOption(llvm::StringRef Lib,
5451                                  llvm::SmallString<24> &Opt) const override {
5452     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5453   }
5454 
5455   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5456                                llvm::SmallString<32> &Opt) const override {
5457     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5458   }
5459 };
5460 
5461 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5462     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5463   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5464   if (GV->isDeclaration())
5465     return;
5466   addStackProbeTargetAttributes(D, GV, CGM);
5467 }
5468 }
5469 
5470 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5471   Ty = useFirstFieldIfTransparentUnion(Ty);
5472 
5473   // Handle illegal vector types here.
5474   if (isIllegalVectorType(Ty)) {
5475     uint64_t Size = getContext().getTypeSize(Ty);
5476     // Android promotes <2 x i8> to i16, not i32
5477     if (isAndroid() && (Size <= 16)) {
5478       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5479       return ABIArgInfo::getDirect(ResType);
5480     }
5481     if (Size <= 32) {
5482       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5483       return ABIArgInfo::getDirect(ResType);
5484     }
5485     if (Size == 64) {
5486       auto *ResType =
5487           llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5488       return ABIArgInfo::getDirect(ResType);
5489     }
5490     if (Size == 128) {
5491       auto *ResType =
5492           llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5493       return ABIArgInfo::getDirect(ResType);
5494     }
5495     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5496   }
5497 
5498   if (!isAggregateTypeForABI(Ty)) {
5499     // Treat an enum type as its underlying type.
5500     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5501       Ty = EnumTy->getDecl()->getIntegerType();
5502 
5503     if (const auto *EIT = Ty->getAs<ExtIntType>())
5504       if (EIT->getNumBits() > 128)
5505         return getNaturalAlignIndirect(Ty);
5506 
5507     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5508                 ? ABIArgInfo::getExtend(Ty)
5509                 : ABIArgInfo::getDirect());
5510   }
5511 
5512   // Structures with either a non-trivial destructor or a non-trivial
5513   // copy constructor are always indirect.
5514   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5515     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5516                                      CGCXXABI::RAA_DirectInMemory);
5517   }
5518 
5519   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5520   // elsewhere for GNU compatibility.
5521   uint64_t Size = getContext().getTypeSize(Ty);
5522   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5523   if (IsEmpty || Size == 0) {
5524     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5525       return ABIArgInfo::getIgnore();
5526 
5527     // GNU C mode. The only argument that gets ignored is an empty one with size
5528     // 0.
5529     if (IsEmpty && Size == 0)
5530       return ABIArgInfo::getIgnore();
5531     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5532   }
5533 
5534   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5535   const Type *Base = nullptr;
5536   uint64_t Members = 0;
5537   if (isHomogeneousAggregate(Ty, Base, Members)) {
5538     return ABIArgInfo::getDirect(
5539         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5540   }
5541 
5542   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5543   if (Size <= 128) {
5544     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5545     // same size and alignment.
5546     if (getTarget().isRenderScriptTarget()) {
5547       return coerceToIntArray(Ty, getContext(), getVMContext());
5548     }
5549     unsigned Alignment;
5550     if (Kind == AArch64ABIInfo::AAPCS) {
5551       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5552       Alignment = Alignment < 128 ? 64 : 128;
5553     } else {
5554       Alignment = std::max(getContext().getTypeAlign(Ty),
5555                            (unsigned)getTarget().getPointerWidth(0));
5556     }
5557     Size = llvm::alignTo(Size, Alignment);
5558 
5559     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5560     // For aggregates with 16-byte alignment, we use i128.
5561     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5562     return ABIArgInfo::getDirect(
5563         Size == Alignment ? BaseTy
5564                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5565   }
5566 
5567   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5568 }
5569 
5570 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5571                                               bool IsVariadic) const {
5572   if (RetTy->isVoidType())
5573     return ABIArgInfo::getIgnore();
5574 
5575   // Large vector types should be returned via memory.
5576   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5577     return getNaturalAlignIndirect(RetTy);
5578 
5579   if (!isAggregateTypeForABI(RetTy)) {
5580     // Treat an enum type as its underlying type.
5581     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5582       RetTy = EnumTy->getDecl()->getIntegerType();
5583 
5584     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5585       if (EIT->getNumBits() > 128)
5586         return getNaturalAlignIndirect(RetTy);
5587 
5588     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5589                 ? ABIArgInfo::getExtend(RetTy)
5590                 : ABIArgInfo::getDirect());
5591   }
5592 
5593   uint64_t Size = getContext().getTypeSize(RetTy);
5594   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5595     return ABIArgInfo::getIgnore();
5596 
5597   const Type *Base = nullptr;
5598   uint64_t Members = 0;
5599   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5600       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5601         IsVariadic))
5602     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5603     return ABIArgInfo::getDirect();
5604 
5605   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5606   if (Size <= 128) {
5607     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5608     // same size and alignment.
5609     if (getTarget().isRenderScriptTarget()) {
5610       return coerceToIntArray(RetTy, getContext(), getVMContext());
5611     }
5612     unsigned Alignment = getContext().getTypeAlign(RetTy);
5613     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5614 
5615     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5616     // For aggregates with 16-byte alignment, we use i128.
5617     if (Alignment < 128 && Size == 128) {
5618       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5619       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5620     }
5621     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5622   }
5623 
5624   return getNaturalAlignIndirect(RetTy);
5625 }
5626 
5627 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5628 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5629   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5630     // Check whether VT is legal.
5631     unsigned NumElements = VT->getNumElements();
5632     uint64_t Size = getContext().getTypeSize(VT);
5633     // NumElements should be power of 2.
5634     if (!llvm::isPowerOf2_32(NumElements))
5635       return true;
5636 
5637     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5638     // vectors for some reason.
5639     llvm::Triple Triple = getTarget().getTriple();
5640     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5641         Triple.isOSBinFormatMachO())
5642       return Size <= 32;
5643 
5644     return Size != 64 && (Size != 128 || NumElements == 1);
5645   }
5646   return false;
5647 }
5648 
5649 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5650                                                llvm::Type *eltTy,
5651                                                unsigned elts) const {
5652   if (!llvm::isPowerOf2_32(elts))
5653     return false;
5654   if (totalSize.getQuantity() != 8 &&
5655       (totalSize.getQuantity() != 16 || elts == 1))
5656     return false;
5657   return true;
5658 }
5659 
5660 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5661   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5662   // point type or a short-vector type. This is the same as the 32-bit ABI,
5663   // but with the difference that any floating-point type is allowed,
5664   // including __fp16.
5665   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5666     if (BT->isFloatingPoint())
5667       return true;
5668   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5669     unsigned VecSize = getContext().getTypeSize(VT);
5670     if (VecSize == 64 || VecSize == 128)
5671       return true;
5672   }
5673   return false;
5674 }
5675 
5676 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5677                                                        uint64_t Members) const {
5678   return Members <= 4;
5679 }
5680 
5681 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5682                                             QualType Ty,
5683                                             CodeGenFunction &CGF) const {
5684   ABIArgInfo AI = classifyArgumentType(Ty);
5685   bool IsIndirect = AI.isIndirect();
5686 
5687   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5688   if (IsIndirect)
5689     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5690   else if (AI.getCoerceToType())
5691     BaseTy = AI.getCoerceToType();
5692 
5693   unsigned NumRegs = 1;
5694   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5695     BaseTy = ArrTy->getElementType();
5696     NumRegs = ArrTy->getNumElements();
5697   }
5698   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5699 
5700   // The AArch64 va_list type and handling is specified in the Procedure Call
5701   // Standard, section B.4:
5702   //
5703   // struct {
5704   //   void *__stack;
5705   //   void *__gr_top;
5706   //   void *__vr_top;
5707   //   int __gr_offs;
5708   //   int __vr_offs;
5709   // };
5710 
5711   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5712   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5713   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5714   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5715 
5716   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5717   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5718 
5719   Address reg_offs_p = Address::invalid();
5720   llvm::Value *reg_offs = nullptr;
5721   int reg_top_index;
5722   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5723   if (!IsFPR) {
5724     // 3 is the field number of __gr_offs
5725     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5726     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5727     reg_top_index = 1; // field number for __gr_top
5728     RegSize = llvm::alignTo(RegSize, 8);
5729   } else {
5730     // 4 is the field number of __vr_offs.
5731     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5732     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5733     reg_top_index = 2; // field number for __vr_top
5734     RegSize = 16 * NumRegs;
5735   }
5736 
5737   //=======================================
5738   // Find out where argument was passed
5739   //=======================================
5740 
5741   // If reg_offs >= 0 we're already using the stack for this type of
5742   // argument. We don't want to keep updating reg_offs (in case it overflows,
5743   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5744   // whatever they get).
5745   llvm::Value *UsingStack = nullptr;
5746   UsingStack = CGF.Builder.CreateICmpSGE(
5747       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5748 
5749   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5750 
5751   // Otherwise, at least some kind of argument could go in these registers, the
5752   // question is whether this particular type is too big.
5753   CGF.EmitBlock(MaybeRegBlock);
5754 
5755   // Integer arguments may need to correct register alignment (for example a
5756   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5757   // align __gr_offs to calculate the potential address.
5758   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5759     int Align = TyAlign.getQuantity();
5760 
5761     reg_offs = CGF.Builder.CreateAdd(
5762         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5763         "align_regoffs");
5764     reg_offs = CGF.Builder.CreateAnd(
5765         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5766         "aligned_regoffs");
5767   }
5768 
5769   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5770   // The fact that this is done unconditionally reflects the fact that
5771   // allocating an argument to the stack also uses up all the remaining
5772   // registers of the appropriate kind.
5773   llvm::Value *NewOffset = nullptr;
5774   NewOffset = CGF.Builder.CreateAdd(
5775       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5776   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5777 
5778   // Now we're in a position to decide whether this argument really was in
5779   // registers or not.
5780   llvm::Value *InRegs = nullptr;
5781   InRegs = CGF.Builder.CreateICmpSLE(
5782       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5783 
5784   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5785 
5786   //=======================================
5787   // Argument was in registers
5788   //=======================================
5789 
5790   // Now we emit the code for if the argument was originally passed in
5791   // registers. First start the appropriate block:
5792   CGF.EmitBlock(InRegBlock);
5793 
5794   llvm::Value *reg_top = nullptr;
5795   Address reg_top_p =
5796       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5797   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5798   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5799                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5800   Address RegAddr = Address::invalid();
5801   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5802 
5803   if (IsIndirect) {
5804     // If it's been passed indirectly (actually a struct), whatever we find from
5805     // stored registers or on the stack will actually be a struct **.
5806     MemTy = llvm::PointerType::getUnqual(MemTy);
5807   }
5808 
5809   const Type *Base = nullptr;
5810   uint64_t NumMembers = 0;
5811   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5812   if (IsHFA && NumMembers > 1) {
5813     // Homogeneous aggregates passed in registers will have their elements split
5814     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5815     // qN+1, ...). We reload and store into a temporary local variable
5816     // contiguously.
5817     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5818     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5819     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5820     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5821     Address Tmp = CGF.CreateTempAlloca(HFATy,
5822                                        std::max(TyAlign, BaseTyInfo.second));
5823 
5824     // On big-endian platforms, the value will be right-aligned in its slot.
5825     int Offset = 0;
5826     if (CGF.CGM.getDataLayout().isBigEndian() &&
5827         BaseTyInfo.first.getQuantity() < 16)
5828       Offset = 16 - BaseTyInfo.first.getQuantity();
5829 
5830     for (unsigned i = 0; i < NumMembers; ++i) {
5831       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5832       Address LoadAddr =
5833         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5834       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5835 
5836       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5837 
5838       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5839       CGF.Builder.CreateStore(Elem, StoreAddr);
5840     }
5841 
5842     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5843   } else {
5844     // Otherwise the object is contiguous in memory.
5845 
5846     // It might be right-aligned in its slot.
5847     CharUnits SlotSize = BaseAddr.getAlignment();
5848     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5849         (IsHFA || !isAggregateTypeForABI(Ty)) &&
5850         TySize < SlotSize) {
5851       CharUnits Offset = SlotSize - TySize;
5852       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5853     }
5854 
5855     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5856   }
5857 
5858   CGF.EmitBranch(ContBlock);
5859 
5860   //=======================================
5861   // Argument was on the stack
5862   //=======================================
5863   CGF.EmitBlock(OnStackBlock);
5864 
5865   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
5866   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5867 
5868   // Again, stack arguments may need realignment. In this case both integer and
5869   // floating-point ones might be affected.
5870   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5871     int Align = TyAlign.getQuantity();
5872 
5873     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5874 
5875     OnStackPtr = CGF.Builder.CreateAdd(
5876         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5877         "align_stack");
5878     OnStackPtr = CGF.Builder.CreateAnd(
5879         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5880         "align_stack");
5881 
5882     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5883   }
5884   Address OnStackAddr(OnStackPtr,
5885                       std::max(CharUnits::fromQuantity(8), TyAlign));
5886 
5887   // All stack slots are multiples of 8 bytes.
5888   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5889   CharUnits StackSize;
5890   if (IsIndirect)
5891     StackSize = StackSlotSize;
5892   else
5893     StackSize = TySize.alignTo(StackSlotSize);
5894 
5895   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5896   llvm::Value *NewStack =
5897       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5898 
5899   // Write the new value of __stack for the next call to va_arg
5900   CGF.Builder.CreateStore(NewStack, stack_p);
5901 
5902   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5903       TySize < StackSlotSize) {
5904     CharUnits Offset = StackSlotSize - TySize;
5905     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5906   }
5907 
5908   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5909 
5910   CGF.EmitBranch(ContBlock);
5911 
5912   //=======================================
5913   // Tidy up
5914   //=======================================
5915   CGF.EmitBlock(ContBlock);
5916 
5917   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5918                                  OnStackAddr, OnStackBlock, "vaargs.addr");
5919 
5920   if (IsIndirect)
5921     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5922                    TyAlign);
5923 
5924   return ResAddr;
5925 }
5926 
5927 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5928                                         CodeGenFunction &CGF) const {
5929   // The backend's lowering doesn't support va_arg for aggregates or
5930   // illegal vector types.  Lower VAArg here for these cases and use
5931   // the LLVM va_arg instruction for everything else.
5932   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5933     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5934 
5935   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
5936   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
5937 
5938   // Empty records are ignored for parameter passing purposes.
5939   if (isEmptyRecord(getContext(), Ty, true)) {
5940     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5941     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5942     return Addr;
5943   }
5944 
5945   // The size of the actual thing passed, which might end up just
5946   // being a pointer for indirect types.
5947   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5948 
5949   // Arguments bigger than 16 bytes which aren't homogeneous
5950   // aggregates should be passed indirectly.
5951   bool IsIndirect = false;
5952   if (TyInfo.first.getQuantity() > 16) {
5953     const Type *Base = nullptr;
5954     uint64_t Members = 0;
5955     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5956   }
5957 
5958   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5959                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5960 }
5961 
5962 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5963                                     QualType Ty) const {
5964   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5965                           CGF.getContext().getTypeInfoInChars(Ty),
5966                           CharUnits::fromQuantity(8),
5967                           /*allowHigherAlign*/ false);
5968 }
5969 
5970 //===----------------------------------------------------------------------===//
5971 // ARM ABI Implementation
5972 //===----------------------------------------------------------------------===//
5973 
5974 namespace {
5975 
5976 class ARMABIInfo : public SwiftABIInfo {
5977 public:
5978   enum ABIKind {
5979     APCS = 0,
5980     AAPCS = 1,
5981     AAPCS_VFP = 2,
5982     AAPCS16_VFP = 3,
5983   };
5984 
5985 private:
5986   ABIKind Kind;
5987   bool IsFloatABISoftFP;
5988 
5989 public:
5990   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5991       : SwiftABIInfo(CGT), Kind(_Kind) {
5992     setCCs();
5993     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
5994         CGT.getCodeGenOpts().FloatABI == ""; // default
5995   }
5996 
5997   bool isEABI() const {
5998     switch (getTarget().getTriple().getEnvironment()) {
5999     case llvm::Triple::Android:
6000     case llvm::Triple::EABI:
6001     case llvm::Triple::EABIHF:
6002     case llvm::Triple::GNUEABI:
6003     case llvm::Triple::GNUEABIHF:
6004     case llvm::Triple::MuslEABI:
6005     case llvm::Triple::MuslEABIHF:
6006       return true;
6007     default:
6008       return false;
6009     }
6010   }
6011 
6012   bool isEABIHF() const {
6013     switch (getTarget().getTriple().getEnvironment()) {
6014     case llvm::Triple::EABIHF:
6015     case llvm::Triple::GNUEABIHF:
6016     case llvm::Triple::MuslEABIHF:
6017       return true;
6018     default:
6019       return false;
6020     }
6021   }
6022 
6023   ABIKind getABIKind() const { return Kind; }
6024 
6025   bool allowBFloatArgsAndRet() const override {
6026     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6027   }
6028 
6029 private:
6030   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6031                                 unsigned functionCallConv) const;
6032   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6033                                   unsigned functionCallConv) const;
6034   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6035                                           uint64_t Members) const;
6036   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6037   bool isIllegalVectorType(QualType Ty) const;
6038   bool containsAnyFP16Vectors(QualType Ty) const;
6039 
6040   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6041   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6042                                          uint64_t Members) const override;
6043 
6044   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6045 
6046   void computeInfo(CGFunctionInfo &FI) const override;
6047 
6048   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6049                     QualType Ty) const override;
6050 
6051   llvm::CallingConv::ID getLLVMDefaultCC() const;
6052   llvm::CallingConv::ID getABIDefaultCC() const;
6053   void setCCs();
6054 
6055   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6056                                     bool asReturnValue) const override {
6057     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6058   }
6059   bool isSwiftErrorInRegister() const override {
6060     return true;
6061   }
6062   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6063                                  unsigned elts) const override;
6064 };
6065 
6066 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6067 public:
6068   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6069       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6070 
6071   const ARMABIInfo &getABIInfo() const {
6072     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6073   }
6074 
6075   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6076     return 13;
6077   }
6078 
6079   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6080     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6081   }
6082 
6083   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6084                                llvm::Value *Address) const override {
6085     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6086 
6087     // 0-15 are the 16 integer registers.
6088     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6089     return false;
6090   }
6091 
6092   unsigned getSizeOfUnwindException() const override {
6093     if (getABIInfo().isEABI()) return 88;
6094     return TargetCodeGenInfo::getSizeOfUnwindException();
6095   }
6096 
6097   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6098                            CodeGen::CodeGenModule &CGM) const override {
6099     if (GV->isDeclaration())
6100       return;
6101     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6102     if (!FD)
6103       return;
6104 
6105     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6106     if (!Attr)
6107       return;
6108 
6109     const char *Kind;
6110     switch (Attr->getInterrupt()) {
6111     case ARMInterruptAttr::Generic: Kind = ""; break;
6112     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6113     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6114     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6115     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6116     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6117     }
6118 
6119     llvm::Function *Fn = cast<llvm::Function>(GV);
6120 
6121     Fn->addFnAttr("interrupt", Kind);
6122 
6123     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6124     if (ABI == ARMABIInfo::APCS)
6125       return;
6126 
6127     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6128     // however this is not necessarily true on taking any interrupt. Instruct
6129     // the backend to perform a realignment as part of the function prologue.
6130     llvm::AttrBuilder B;
6131     B.addStackAlignmentAttr(8);
6132     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6133   }
6134 };
6135 
6136 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6137 public:
6138   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6139       : ARMTargetCodeGenInfo(CGT, K) {}
6140 
6141   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6142                            CodeGen::CodeGenModule &CGM) const override;
6143 
6144   void getDependentLibraryOption(llvm::StringRef Lib,
6145                                  llvm::SmallString<24> &Opt) const override {
6146     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6147   }
6148 
6149   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6150                                llvm::SmallString<32> &Opt) const override {
6151     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6152   }
6153 };
6154 
6155 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6156     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6157   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6158   if (GV->isDeclaration())
6159     return;
6160   addStackProbeTargetAttributes(D, GV, CGM);
6161 }
6162 }
6163 
6164 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6165   if (!::classifyReturnType(getCXXABI(), FI, *this))
6166     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6167                                             FI.getCallingConvention());
6168 
6169   for (auto &I : FI.arguments())
6170     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6171                                   FI.getCallingConvention());
6172 
6173 
6174   // Always honor user-specified calling convention.
6175   if (FI.getCallingConvention() != llvm::CallingConv::C)
6176     return;
6177 
6178   llvm::CallingConv::ID cc = getRuntimeCC();
6179   if (cc != llvm::CallingConv::C)
6180     FI.setEffectiveCallingConvention(cc);
6181 }
6182 
6183 /// Return the default calling convention that LLVM will use.
6184 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6185   // The default calling convention that LLVM will infer.
6186   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6187     return llvm::CallingConv::ARM_AAPCS_VFP;
6188   else if (isEABI())
6189     return llvm::CallingConv::ARM_AAPCS;
6190   else
6191     return llvm::CallingConv::ARM_APCS;
6192 }
6193 
6194 /// Return the calling convention that our ABI would like us to use
6195 /// as the C calling convention.
6196 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6197   switch (getABIKind()) {
6198   case APCS: return llvm::CallingConv::ARM_APCS;
6199   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6200   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6201   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6202   }
6203   llvm_unreachable("bad ABI kind");
6204 }
6205 
6206 void ARMABIInfo::setCCs() {
6207   assert(getRuntimeCC() == llvm::CallingConv::C);
6208 
6209   // Don't muddy up the IR with a ton of explicit annotations if
6210   // they'd just match what LLVM will infer from the triple.
6211   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6212   if (abiCC != getLLVMDefaultCC())
6213     RuntimeCC = abiCC;
6214 }
6215 
6216 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6217   uint64_t Size = getContext().getTypeSize(Ty);
6218   if (Size <= 32) {
6219     llvm::Type *ResType =
6220         llvm::Type::getInt32Ty(getVMContext());
6221     return ABIArgInfo::getDirect(ResType);
6222   }
6223   if (Size == 64 || Size == 128) {
6224     auto *ResType = llvm::FixedVectorType::get(
6225         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6226     return ABIArgInfo::getDirect(ResType);
6227   }
6228   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6229 }
6230 
6231 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6232                                                     const Type *Base,
6233                                                     uint64_t Members) const {
6234   assert(Base && "Base class should be set for homogeneous aggregate");
6235   // Base can be a floating-point or a vector.
6236   if (const VectorType *VT = Base->getAs<VectorType>()) {
6237     // FP16 vectors should be converted to integer vectors
6238     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6239       uint64_t Size = getContext().getTypeSize(VT);
6240       auto *NewVecTy = llvm::FixedVectorType::get(
6241           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6242       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6243       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6244     }
6245   }
6246   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6247 }
6248 
6249 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6250                                             unsigned functionCallConv) const {
6251   // 6.1.2.1 The following argument types are VFP CPRCs:
6252   //   A single-precision floating-point type (including promoted
6253   //   half-precision types); A double-precision floating-point type;
6254   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6255   //   with a Base Type of a single- or double-precision floating-point type,
6256   //   64-bit containerized vectors or 128-bit containerized vectors with one
6257   //   to four Elements.
6258   // Variadic functions should always marshal to the base standard.
6259   bool IsAAPCS_VFP =
6260       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6261 
6262   Ty = useFirstFieldIfTransparentUnion(Ty);
6263 
6264   // Handle illegal vector types here.
6265   if (isIllegalVectorType(Ty))
6266     return coerceIllegalVector(Ty);
6267 
6268   // _Float16 and __fp16 get passed as if it were an int or float, but
6269   // with the top 16 bits unspecified. This is not done for OpenCL as it handles
6270   // the half type natively, and does not need to interwork with AAPCS code.
6271   if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
6272       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6273     llvm::Type *ResType = IsAAPCS_VFP ?
6274       llvm::Type::getFloatTy(getVMContext()) :
6275       llvm::Type::getInt32Ty(getVMContext());
6276     return ABIArgInfo::getDirect(ResType);
6277   }
6278 
6279   // __bf16 gets passed using the bfloat IR type, or using i32 but
6280   // with the top 16 bits unspecified.
6281   if (Ty->isBFloat16Type() && IsFloatABISoftFP) {
6282     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
6283     return ABIArgInfo::getDirect(ResType);
6284   }
6285 
6286   if (!isAggregateTypeForABI(Ty)) {
6287     // Treat an enum type as its underlying type.
6288     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6289       Ty = EnumTy->getDecl()->getIntegerType();
6290     }
6291 
6292     if (const auto *EIT = Ty->getAs<ExtIntType>())
6293       if (EIT->getNumBits() > 64)
6294         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6295 
6296     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6297                                               : ABIArgInfo::getDirect());
6298   }
6299 
6300   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6301     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6302   }
6303 
6304   // Ignore empty records.
6305   if (isEmptyRecord(getContext(), Ty, true))
6306     return ABIArgInfo::getIgnore();
6307 
6308   if (IsAAPCS_VFP) {
6309     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6310     // into VFP registers.
6311     const Type *Base = nullptr;
6312     uint64_t Members = 0;
6313     if (isHomogeneousAggregate(Ty, Base, Members))
6314       return classifyHomogeneousAggregate(Ty, Base, Members);
6315   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6316     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6317     // this convention even for a variadic function: the backend will use GPRs
6318     // if needed.
6319     const Type *Base = nullptr;
6320     uint64_t Members = 0;
6321     if (isHomogeneousAggregate(Ty, Base, Members)) {
6322       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6323       llvm::Type *Ty =
6324         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6325       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6326     }
6327   }
6328 
6329   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6330       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6331     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6332     // bigger than 128-bits, they get placed in space allocated by the caller,
6333     // and a pointer is passed.
6334     return ABIArgInfo::getIndirect(
6335         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6336   }
6337 
6338   // Support byval for ARM.
6339   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6340   // most 8-byte. We realign the indirect argument if type alignment is bigger
6341   // than ABI alignment.
6342   uint64_t ABIAlign = 4;
6343   uint64_t TyAlign;
6344   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6345       getABIKind() == ARMABIInfo::AAPCS) {
6346     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6347     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6348   } else {
6349     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6350   }
6351   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6352     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6353     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6354                                    /*ByVal=*/true,
6355                                    /*Realign=*/TyAlign > ABIAlign);
6356   }
6357 
6358   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6359   // same size and alignment.
6360   if (getTarget().isRenderScriptTarget()) {
6361     return coerceToIntArray(Ty, getContext(), getVMContext());
6362   }
6363 
6364   // Otherwise, pass by coercing to a structure of the appropriate size.
6365   llvm::Type* ElemTy;
6366   unsigned SizeRegs;
6367   // FIXME: Try to match the types of the arguments more accurately where
6368   // we can.
6369   if (TyAlign <= 4) {
6370     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6371     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6372   } else {
6373     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6374     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6375   }
6376 
6377   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6378 }
6379 
6380 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6381                               llvm::LLVMContext &VMContext) {
6382   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6383   // is called integer-like if its size is less than or equal to one word, and
6384   // the offset of each of its addressable sub-fields is zero.
6385 
6386   uint64_t Size = Context.getTypeSize(Ty);
6387 
6388   // Check that the type fits in a word.
6389   if (Size > 32)
6390     return false;
6391 
6392   // FIXME: Handle vector types!
6393   if (Ty->isVectorType())
6394     return false;
6395 
6396   // Float types are never treated as "integer like".
6397   if (Ty->isRealFloatingType())
6398     return false;
6399 
6400   // If this is a builtin or pointer type then it is ok.
6401   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6402     return true;
6403 
6404   // Small complex integer types are "integer like".
6405   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6406     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6407 
6408   // Single element and zero sized arrays should be allowed, by the definition
6409   // above, but they are not.
6410 
6411   // Otherwise, it must be a record type.
6412   const RecordType *RT = Ty->getAs<RecordType>();
6413   if (!RT) return false;
6414 
6415   // Ignore records with flexible arrays.
6416   const RecordDecl *RD = RT->getDecl();
6417   if (RD->hasFlexibleArrayMember())
6418     return false;
6419 
6420   // Check that all sub-fields are at offset 0, and are themselves "integer
6421   // like".
6422   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6423 
6424   bool HadField = false;
6425   unsigned idx = 0;
6426   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6427        i != e; ++i, ++idx) {
6428     const FieldDecl *FD = *i;
6429 
6430     // Bit-fields are not addressable, we only need to verify they are "integer
6431     // like". We still have to disallow a subsequent non-bitfield, for example:
6432     //   struct { int : 0; int x }
6433     // is non-integer like according to gcc.
6434     if (FD->isBitField()) {
6435       if (!RD->isUnion())
6436         HadField = true;
6437 
6438       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6439         return false;
6440 
6441       continue;
6442     }
6443 
6444     // Check if this field is at offset 0.
6445     if (Layout.getFieldOffset(idx) != 0)
6446       return false;
6447 
6448     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6449       return false;
6450 
6451     // Only allow at most one field in a structure. This doesn't match the
6452     // wording above, but follows gcc in situations with a field following an
6453     // empty structure.
6454     if (!RD->isUnion()) {
6455       if (HadField)
6456         return false;
6457 
6458       HadField = true;
6459     }
6460   }
6461 
6462   return true;
6463 }
6464 
6465 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6466                                           unsigned functionCallConv) const {
6467 
6468   // Variadic functions should always marshal to the base standard.
6469   bool IsAAPCS_VFP =
6470       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6471 
6472   if (RetTy->isVoidType())
6473     return ABIArgInfo::getIgnore();
6474 
6475   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6476     // Large vector types should be returned via memory.
6477     if (getContext().getTypeSize(RetTy) > 128)
6478       return getNaturalAlignIndirect(RetTy);
6479     // TODO: FP16/BF16 vectors should be converted to integer vectors
6480     // This check is similar  to isIllegalVectorType - refactor?
6481     if ((!getTarget().hasLegalHalfType() &&
6482         (VT->getElementType()->isFloat16Type() ||
6483          VT->getElementType()->isHalfType())) ||
6484         (IsFloatABISoftFP &&
6485          VT->getElementType()->isBFloat16Type()))
6486       return coerceIllegalVector(RetTy);
6487   }
6488 
6489   // _Float16 and __fp16 get returned as if it were an int or float, but with
6490   // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6491   // half type natively, and does not need to interwork with AAPCS code.
6492   if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6493       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6494     llvm::Type *ResType = IsAAPCS_VFP ?
6495       llvm::Type::getFloatTy(getVMContext()) :
6496       llvm::Type::getInt32Ty(getVMContext());
6497     return ABIArgInfo::getDirect(ResType);
6498   }
6499 
6500   // if we're using the softfp float abi, __bf16 get returned as if it were an
6501   // int but with the top 16 bits unspecified.
6502   if (RetTy->isBFloat16Type()) {
6503     llvm::Type *ResType = IsAAPCS_VFP ?
6504       llvm::Type::getBFloatTy(getVMContext()) :
6505       llvm::Type::getInt32Ty(getVMContext());
6506     return ABIArgInfo::getDirect(ResType);
6507   }
6508 
6509   if (!isAggregateTypeForABI(RetTy)) {
6510     // Treat an enum type as its underlying type.
6511     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6512       RetTy = EnumTy->getDecl()->getIntegerType();
6513 
6514     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6515       if (EIT->getNumBits() > 64)
6516         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6517 
6518     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6519                                                 : ABIArgInfo::getDirect();
6520   }
6521 
6522   // Are we following APCS?
6523   if (getABIKind() == APCS) {
6524     if (isEmptyRecord(getContext(), RetTy, false))
6525       return ABIArgInfo::getIgnore();
6526 
6527     // Complex types are all returned as packed integers.
6528     //
6529     // FIXME: Consider using 2 x vector types if the back end handles them
6530     // correctly.
6531     if (RetTy->isAnyComplexType())
6532       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6533           getVMContext(), getContext().getTypeSize(RetTy)));
6534 
6535     // Integer like structures are returned in r0.
6536     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6537       // Return in the smallest viable integer type.
6538       uint64_t Size = getContext().getTypeSize(RetTy);
6539       if (Size <= 8)
6540         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6541       if (Size <= 16)
6542         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6543       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6544     }
6545 
6546     // Otherwise return in memory.
6547     return getNaturalAlignIndirect(RetTy);
6548   }
6549 
6550   // Otherwise this is an AAPCS variant.
6551 
6552   if (isEmptyRecord(getContext(), RetTy, true))
6553     return ABIArgInfo::getIgnore();
6554 
6555   // Check for homogeneous aggregates with AAPCS-VFP.
6556   if (IsAAPCS_VFP) {
6557     const Type *Base = nullptr;
6558     uint64_t Members = 0;
6559     if (isHomogeneousAggregate(RetTy, Base, Members))
6560       return classifyHomogeneousAggregate(RetTy, Base, Members);
6561   }
6562 
6563   // Aggregates <= 4 bytes are returned in r0; other aggregates
6564   // are returned indirectly.
6565   uint64_t Size = getContext().getTypeSize(RetTy);
6566   if (Size <= 32) {
6567     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6568     // same size and alignment.
6569     if (getTarget().isRenderScriptTarget()) {
6570       return coerceToIntArray(RetTy, getContext(), getVMContext());
6571     }
6572     if (getDataLayout().isBigEndian())
6573       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6574       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6575 
6576     // Return in the smallest viable integer type.
6577     if (Size <= 8)
6578       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6579     if (Size <= 16)
6580       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6581     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6582   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6583     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6584     llvm::Type *CoerceTy =
6585         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6586     return ABIArgInfo::getDirect(CoerceTy);
6587   }
6588 
6589   return getNaturalAlignIndirect(RetTy);
6590 }
6591 
6592 /// isIllegalVector - check whether Ty is an illegal vector type.
6593 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6594   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6595     // On targets that don't support half, fp16 or bfloat, they are expanded
6596     // into float, and we don't want the ABI to depend on whether or not they
6597     // are supported in hardware. Thus return false to coerce vectors of these
6598     // types into integer vectors.
6599     // We do not depend on hasLegalHalfType for bfloat as it is a
6600     // separate IR type.
6601     if ((!getTarget().hasLegalHalfType() &&
6602         (VT->getElementType()->isFloat16Type() ||
6603          VT->getElementType()->isHalfType())) ||
6604         (IsFloatABISoftFP &&
6605          VT->getElementType()->isBFloat16Type()))
6606       return true;
6607     if (isAndroid()) {
6608       // Android shipped using Clang 3.1, which supported a slightly different
6609       // vector ABI. The primary differences were that 3-element vector types
6610       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6611       // accepts that legacy behavior for Android only.
6612       // Check whether VT is legal.
6613       unsigned NumElements = VT->getNumElements();
6614       // NumElements should be power of 2 or equal to 3.
6615       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6616         return true;
6617     } else {
6618       // Check whether VT is legal.
6619       unsigned NumElements = VT->getNumElements();
6620       uint64_t Size = getContext().getTypeSize(VT);
6621       // NumElements should be power of 2.
6622       if (!llvm::isPowerOf2_32(NumElements))
6623         return true;
6624       // Size should be greater than 32 bits.
6625       return Size <= 32;
6626     }
6627   }
6628   return false;
6629 }
6630 
6631 /// Return true if a type contains any 16-bit floating point vectors
6632 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6633   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6634     uint64_t NElements = AT->getSize().getZExtValue();
6635     if (NElements == 0)
6636       return false;
6637     return containsAnyFP16Vectors(AT->getElementType());
6638   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6639     const RecordDecl *RD = RT->getDecl();
6640 
6641     // If this is a C++ record, check the bases first.
6642     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6643       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6644             return containsAnyFP16Vectors(B.getType());
6645           }))
6646         return true;
6647 
6648     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6649           return FD && containsAnyFP16Vectors(FD->getType());
6650         }))
6651       return true;
6652 
6653     return false;
6654   } else {
6655     if (const VectorType *VT = Ty->getAs<VectorType>())
6656       return (VT->getElementType()->isFloat16Type() ||
6657               VT->getElementType()->isBFloat16Type() ||
6658               VT->getElementType()->isHalfType());
6659     return false;
6660   }
6661 }
6662 
6663 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6664                                            llvm::Type *eltTy,
6665                                            unsigned numElts) const {
6666   if (!llvm::isPowerOf2_32(numElts))
6667     return false;
6668   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6669   if (size > 64)
6670     return false;
6671   if (vectorSize.getQuantity() != 8 &&
6672       (vectorSize.getQuantity() != 16 || numElts == 1))
6673     return false;
6674   return true;
6675 }
6676 
6677 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6678   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6679   // double, or 64-bit or 128-bit vectors.
6680   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6681     if (BT->getKind() == BuiltinType::Float ||
6682         BT->getKind() == BuiltinType::Double ||
6683         BT->getKind() == BuiltinType::LongDouble)
6684       return true;
6685   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6686     unsigned VecSize = getContext().getTypeSize(VT);
6687     if (VecSize == 64 || VecSize == 128)
6688       return true;
6689   }
6690   return false;
6691 }
6692 
6693 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6694                                                    uint64_t Members) const {
6695   return Members <= 4;
6696 }
6697 
6698 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6699                                         bool acceptHalf) const {
6700   // Give precedence to user-specified calling conventions.
6701   if (callConvention != llvm::CallingConv::C)
6702     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6703   else
6704     return (getABIKind() == AAPCS_VFP) ||
6705            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6706 }
6707 
6708 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6709                               QualType Ty) const {
6710   CharUnits SlotSize = CharUnits::fromQuantity(4);
6711 
6712   // Empty records are ignored for parameter passing purposes.
6713   if (isEmptyRecord(getContext(), Ty, true)) {
6714     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6715     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6716     return Addr;
6717   }
6718 
6719   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6720   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6721 
6722   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6723   bool IsIndirect = false;
6724   const Type *Base = nullptr;
6725   uint64_t Members = 0;
6726   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6727     IsIndirect = true;
6728 
6729   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6730   // allocated by the caller.
6731   } else if (TySize > CharUnits::fromQuantity(16) &&
6732              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6733              !isHomogeneousAggregate(Ty, Base, Members)) {
6734     IsIndirect = true;
6735 
6736   // Otherwise, bound the type's ABI alignment.
6737   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6738   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6739   // Our callers should be prepared to handle an under-aligned address.
6740   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6741              getABIKind() == ARMABIInfo::AAPCS) {
6742     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6743     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6744   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6745     // ARMv7k allows type alignment up to 16 bytes.
6746     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6747     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6748   } else {
6749     TyAlignForABI = CharUnits::fromQuantity(4);
6750   }
6751 
6752   std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
6753   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6754                           SlotSize, /*AllowHigherAlign*/ true);
6755 }
6756 
6757 //===----------------------------------------------------------------------===//
6758 // NVPTX ABI Implementation
6759 //===----------------------------------------------------------------------===//
6760 
6761 namespace {
6762 
6763 class NVPTXTargetCodeGenInfo;
6764 
6765 class NVPTXABIInfo : public ABIInfo {
6766   NVPTXTargetCodeGenInfo &CGInfo;
6767 
6768 public:
6769   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6770       : ABIInfo(CGT), CGInfo(Info) {}
6771 
6772   ABIArgInfo classifyReturnType(QualType RetTy) const;
6773   ABIArgInfo classifyArgumentType(QualType Ty) const;
6774 
6775   void computeInfo(CGFunctionInfo &FI) const override;
6776   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6777                     QualType Ty) const override;
6778   bool isUnsupportedType(QualType T) const;
6779   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6780 };
6781 
6782 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6783 public:
6784   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6785       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6786 
6787   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6788                            CodeGen::CodeGenModule &M) const override;
6789   bool shouldEmitStaticExternCAliases() const override;
6790 
6791   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6792     // On the device side, surface reference is represented as an object handle
6793     // in 64-bit integer.
6794     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6795   }
6796 
6797   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6798     // On the device side, texture reference is represented as an object handle
6799     // in 64-bit integer.
6800     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6801   }
6802 
6803   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6804                                               LValue Src) const override {
6805     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6806     return true;
6807   }
6808 
6809   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6810                                               LValue Src) const override {
6811     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6812     return true;
6813   }
6814 
6815 private:
6816   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6817   // resulting MDNode to the nvvm.annotations MDNode.
6818   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6819                               int Operand);
6820 
6821   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6822                                            LValue Src) {
6823     llvm::Value *Handle = nullptr;
6824     llvm::Constant *C =
6825         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6826     // Lookup `addrspacecast` through the constant pointer if any.
6827     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6828       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6829     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6830       // Load the handle from the specific global variable using
6831       // `nvvm.texsurf.handle.internal` intrinsic.
6832       Handle = CGF.EmitRuntimeCall(
6833           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6834                                {GV->getType()}),
6835           {GV}, "texsurf_handle");
6836     } else
6837       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6838     CGF.EmitStoreOfScalar(Handle, Dst);
6839   }
6840 };
6841 
6842 /// Checks if the type is unsupported directly by the current target.
6843 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6844   ASTContext &Context = getContext();
6845   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6846     return true;
6847   if (!Context.getTargetInfo().hasFloat128Type() &&
6848       (T->isFloat128Type() ||
6849        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6850     return true;
6851   if (const auto *EIT = T->getAs<ExtIntType>())
6852     return EIT->getNumBits() >
6853            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6854   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6855       Context.getTypeSize(T) > 64U)
6856     return true;
6857   if (const auto *AT = T->getAsArrayTypeUnsafe())
6858     return isUnsupportedType(AT->getElementType());
6859   const auto *RT = T->getAs<RecordType>();
6860   if (!RT)
6861     return false;
6862   const RecordDecl *RD = RT->getDecl();
6863 
6864   // If this is a C++ record, check the bases first.
6865   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6866     for (const CXXBaseSpecifier &I : CXXRD->bases())
6867       if (isUnsupportedType(I.getType()))
6868         return true;
6869 
6870   for (const FieldDecl *I : RD->fields())
6871     if (isUnsupportedType(I->getType()))
6872       return true;
6873   return false;
6874 }
6875 
6876 /// Coerce the given type into an array with maximum allowed size of elements.
6877 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6878                                                    unsigned MaxSize) const {
6879   // Alignment and Size are measured in bits.
6880   const uint64_t Size = getContext().getTypeSize(Ty);
6881   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6882   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6883   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
6884   const uint64_t NumElements = (Size + Div - 1) / Div;
6885   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6886 }
6887 
6888 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6889   if (RetTy->isVoidType())
6890     return ABIArgInfo::getIgnore();
6891 
6892   if (getContext().getLangOpts().OpenMP &&
6893       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
6894     return coerceToIntArrayWithLimit(RetTy, 64);
6895 
6896   // note: this is different from default ABI
6897   if (!RetTy->isScalarType())
6898     return ABIArgInfo::getDirect();
6899 
6900   // Treat an enum type as its underlying type.
6901   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6902     RetTy = EnumTy->getDecl()->getIntegerType();
6903 
6904   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6905                                                : ABIArgInfo::getDirect());
6906 }
6907 
6908 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6909   // Treat an enum type as its underlying type.
6910   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6911     Ty = EnumTy->getDecl()->getIntegerType();
6912 
6913   // Return aggregates type as indirect by value
6914   if (isAggregateTypeForABI(Ty)) {
6915     // Under CUDA device compilation, tex/surf builtin types are replaced with
6916     // object types and passed directly.
6917     if (getContext().getLangOpts().CUDAIsDevice) {
6918       if (Ty->isCUDADeviceBuiltinSurfaceType())
6919         return ABIArgInfo::getDirect(
6920             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
6921       if (Ty->isCUDADeviceBuiltinTextureType())
6922         return ABIArgInfo::getDirect(
6923             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
6924     }
6925     return getNaturalAlignIndirect(Ty, /* byval */ true);
6926   }
6927 
6928   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
6929     if ((EIT->getNumBits() > 128) ||
6930         (!getContext().getTargetInfo().hasInt128Type() &&
6931          EIT->getNumBits() > 64))
6932       return getNaturalAlignIndirect(Ty, /* byval */ true);
6933   }
6934 
6935   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6936                                             : ABIArgInfo::getDirect());
6937 }
6938 
6939 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6940   if (!getCXXABI().classifyReturnType(FI))
6941     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6942   for (auto &I : FI.arguments())
6943     I.info = classifyArgumentType(I.type);
6944 
6945   // Always honor user-specified calling convention.
6946   if (FI.getCallingConvention() != llvm::CallingConv::C)
6947     return;
6948 
6949   FI.setEffectiveCallingConvention(getRuntimeCC());
6950 }
6951 
6952 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6953                                 QualType Ty) const {
6954   llvm_unreachable("NVPTX does not support varargs");
6955 }
6956 
6957 void NVPTXTargetCodeGenInfo::setTargetAttributes(
6958     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6959   if (GV->isDeclaration())
6960     return;
6961   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6962   if (VD) {
6963     if (M.getLangOpts().CUDA) {
6964       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
6965         addNVVMMetadata(GV, "surface", 1);
6966       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
6967         addNVVMMetadata(GV, "texture", 1);
6968       return;
6969     }
6970   }
6971 
6972   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6973   if (!FD) return;
6974 
6975   llvm::Function *F = cast<llvm::Function>(GV);
6976 
6977   // Perform special handling in OpenCL mode
6978   if (M.getLangOpts().OpenCL) {
6979     // Use OpenCL function attributes to check for kernel functions
6980     // By default, all functions are device functions
6981     if (FD->hasAttr<OpenCLKernelAttr>()) {
6982       // OpenCL __kernel functions get kernel metadata
6983       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6984       addNVVMMetadata(F, "kernel", 1);
6985       // And kernel functions are not subject to inlining
6986       F->addFnAttr(llvm::Attribute::NoInline);
6987     }
6988   }
6989 
6990   // Perform special handling in CUDA mode.
6991   if (M.getLangOpts().CUDA) {
6992     // CUDA __global__ functions get a kernel metadata entry.  Since
6993     // __global__ functions cannot be called from the device, we do not
6994     // need to set the noinline attribute.
6995     if (FD->hasAttr<CUDAGlobalAttr>()) {
6996       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6997       addNVVMMetadata(F, "kernel", 1);
6998     }
6999     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7000       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7001       llvm::APSInt MaxThreads(32);
7002       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7003       if (MaxThreads > 0)
7004         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7005 
7006       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7007       // not specified in __launch_bounds__ or if the user specified a 0 value,
7008       // we don't have to add a PTX directive.
7009       if (Attr->getMinBlocks()) {
7010         llvm::APSInt MinBlocks(32);
7011         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7012         if (MinBlocks > 0)
7013           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7014           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7015       }
7016     }
7017   }
7018 }
7019 
7020 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7021                                              StringRef Name, int Operand) {
7022   llvm::Module *M = GV->getParent();
7023   llvm::LLVMContext &Ctx = M->getContext();
7024 
7025   // Get "nvvm.annotations" metadata node
7026   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7027 
7028   llvm::Metadata *MDVals[] = {
7029       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7030       llvm::ConstantAsMetadata::get(
7031           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7032   // Append metadata to nvvm.annotations
7033   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7034 }
7035 
7036 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7037   return false;
7038 }
7039 }
7040 
7041 //===----------------------------------------------------------------------===//
7042 // SystemZ ABI Implementation
7043 //===----------------------------------------------------------------------===//
7044 
7045 namespace {
7046 
7047 class SystemZABIInfo : public SwiftABIInfo {
7048   bool HasVector;
7049   bool IsSoftFloatABI;
7050 
7051 public:
7052   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7053     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7054 
7055   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7056   bool isCompoundType(QualType Ty) const;
7057   bool isVectorArgumentType(QualType Ty) const;
7058   bool isFPArgumentType(QualType Ty) const;
7059   QualType GetSingleElementType(QualType Ty) const;
7060 
7061   ABIArgInfo classifyReturnType(QualType RetTy) const;
7062   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7063 
7064   void computeInfo(CGFunctionInfo &FI) const override {
7065     if (!getCXXABI().classifyReturnType(FI))
7066       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7067     for (auto &I : FI.arguments())
7068       I.info = classifyArgumentType(I.type);
7069   }
7070 
7071   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7072                     QualType Ty) const override;
7073 
7074   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7075                                     bool asReturnValue) const override {
7076     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7077   }
7078   bool isSwiftErrorInRegister() const override {
7079     return false;
7080   }
7081 };
7082 
7083 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7084 public:
7085   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7086       : TargetCodeGenInfo(
7087             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7088 };
7089 
7090 }
7091 
7092 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7093   // Treat an enum type as its underlying type.
7094   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7095     Ty = EnumTy->getDecl()->getIntegerType();
7096 
7097   // Promotable integer types are required to be promoted by the ABI.
7098   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7099     return true;
7100 
7101   if (const auto *EIT = Ty->getAs<ExtIntType>())
7102     if (EIT->getNumBits() < 64)
7103       return true;
7104 
7105   // 32-bit values must also be promoted.
7106   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7107     switch (BT->getKind()) {
7108     case BuiltinType::Int:
7109     case BuiltinType::UInt:
7110       return true;
7111     default:
7112       return false;
7113     }
7114   return false;
7115 }
7116 
7117 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7118   return (Ty->isAnyComplexType() ||
7119           Ty->isVectorType() ||
7120           isAggregateTypeForABI(Ty));
7121 }
7122 
7123 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7124   return (HasVector &&
7125           Ty->isVectorType() &&
7126           getContext().getTypeSize(Ty) <= 128);
7127 }
7128 
7129 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7130   if (IsSoftFloatABI)
7131     return false;
7132 
7133   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7134     switch (BT->getKind()) {
7135     case BuiltinType::Float:
7136     case BuiltinType::Double:
7137       return true;
7138     default:
7139       return false;
7140     }
7141 
7142   return false;
7143 }
7144 
7145 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7146   if (const RecordType *RT = Ty->getAsStructureType()) {
7147     const RecordDecl *RD = RT->getDecl();
7148     QualType Found;
7149 
7150     // If this is a C++ record, check the bases first.
7151     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7152       for (const auto &I : CXXRD->bases()) {
7153         QualType Base = I.getType();
7154 
7155         // Empty bases don't affect things either way.
7156         if (isEmptyRecord(getContext(), Base, true))
7157           continue;
7158 
7159         if (!Found.isNull())
7160           return Ty;
7161         Found = GetSingleElementType(Base);
7162       }
7163 
7164     // Check the fields.
7165     for (const auto *FD : RD->fields()) {
7166       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7167       // Unlike isSingleElementStruct(), empty structure and array fields
7168       // do count.  So do anonymous bitfields that aren't zero-sized.
7169       if (getContext().getLangOpts().CPlusPlus &&
7170           FD->isZeroLengthBitField(getContext()))
7171         continue;
7172 
7173       // Unlike isSingleElementStruct(), arrays do not count.
7174       // Nested structures still do though.
7175       if (!Found.isNull())
7176         return Ty;
7177       Found = GetSingleElementType(FD->getType());
7178     }
7179 
7180     // Unlike isSingleElementStruct(), trailing padding is allowed.
7181     // An 8-byte aligned struct s { float f; } is passed as a double.
7182     if (!Found.isNull())
7183       return Found;
7184   }
7185 
7186   return Ty;
7187 }
7188 
7189 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7190                                   QualType Ty) const {
7191   // Assume that va_list type is correct; should be pointer to LLVM type:
7192   // struct {
7193   //   i64 __gpr;
7194   //   i64 __fpr;
7195   //   i8 *__overflow_arg_area;
7196   //   i8 *__reg_save_area;
7197   // };
7198 
7199   // Every non-vector argument occupies 8 bytes and is passed by preference
7200   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7201   // always passed on the stack.
7202   Ty = getContext().getCanonicalType(Ty);
7203   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7204   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7205   llvm::Type *DirectTy = ArgTy;
7206   ABIArgInfo AI = classifyArgumentType(Ty);
7207   bool IsIndirect = AI.isIndirect();
7208   bool InFPRs = false;
7209   bool IsVector = false;
7210   CharUnits UnpaddedSize;
7211   CharUnits DirectAlign;
7212   if (IsIndirect) {
7213     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7214     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7215   } else {
7216     if (AI.getCoerceToType())
7217       ArgTy = AI.getCoerceToType();
7218     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7219     IsVector = ArgTy->isVectorTy();
7220     UnpaddedSize = TyInfo.first;
7221     DirectAlign = TyInfo.second;
7222   }
7223   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7224   if (IsVector && UnpaddedSize > PaddedSize)
7225     PaddedSize = CharUnits::fromQuantity(16);
7226   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7227 
7228   CharUnits Padding = (PaddedSize - UnpaddedSize);
7229 
7230   llvm::Type *IndexTy = CGF.Int64Ty;
7231   llvm::Value *PaddedSizeV =
7232     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7233 
7234   if (IsVector) {
7235     // Work out the address of a vector argument on the stack.
7236     // Vector arguments are always passed in the high bits of a
7237     // single (8 byte) or double (16 byte) stack slot.
7238     Address OverflowArgAreaPtr =
7239         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7240     Address OverflowArgArea =
7241       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7242               TyInfo.second);
7243     Address MemAddr =
7244       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7245 
7246     // Update overflow_arg_area_ptr pointer
7247     llvm::Value *NewOverflowArgArea =
7248       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7249                             "overflow_arg_area");
7250     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7251 
7252     return MemAddr;
7253   }
7254 
7255   assert(PaddedSize.getQuantity() == 8);
7256 
7257   unsigned MaxRegs, RegCountField, RegSaveIndex;
7258   CharUnits RegPadding;
7259   if (InFPRs) {
7260     MaxRegs = 4; // Maximum of 4 FPR arguments
7261     RegCountField = 1; // __fpr
7262     RegSaveIndex = 16; // save offset for f0
7263     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7264   } else {
7265     MaxRegs = 5; // Maximum of 5 GPR arguments
7266     RegCountField = 0; // __gpr
7267     RegSaveIndex = 2; // save offset for r2
7268     RegPadding = Padding; // values are passed in the low bits of a GPR
7269   }
7270 
7271   Address RegCountPtr =
7272       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7273   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7274   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7275   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7276                                                  "fits_in_regs");
7277 
7278   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7279   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7280   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7281   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7282 
7283   // Emit code to load the value if it was passed in registers.
7284   CGF.EmitBlock(InRegBlock);
7285 
7286   // Work out the address of an argument register.
7287   llvm::Value *ScaledRegCount =
7288     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7289   llvm::Value *RegBase =
7290     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7291                                       + RegPadding.getQuantity());
7292   llvm::Value *RegOffset =
7293     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7294   Address RegSaveAreaPtr =
7295       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7296   llvm::Value *RegSaveArea =
7297     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7298   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7299                                            "raw_reg_addr"),
7300                      PaddedSize);
7301   Address RegAddr =
7302     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7303 
7304   // Update the register count
7305   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7306   llvm::Value *NewRegCount =
7307     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7308   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7309   CGF.EmitBranch(ContBlock);
7310 
7311   // Emit code to load the value if it was passed in memory.
7312   CGF.EmitBlock(InMemBlock);
7313 
7314   // Work out the address of a stack argument.
7315   Address OverflowArgAreaPtr =
7316       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7317   Address OverflowArgArea =
7318     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7319             PaddedSize);
7320   Address RawMemAddr =
7321     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7322   Address MemAddr =
7323     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7324 
7325   // Update overflow_arg_area_ptr pointer
7326   llvm::Value *NewOverflowArgArea =
7327     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7328                           "overflow_arg_area");
7329   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7330   CGF.EmitBranch(ContBlock);
7331 
7332   // Return the appropriate result.
7333   CGF.EmitBlock(ContBlock);
7334   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7335                                  MemAddr, InMemBlock, "va_arg.addr");
7336 
7337   if (IsIndirect)
7338     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7339                       TyInfo.second);
7340 
7341   return ResAddr;
7342 }
7343 
7344 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7345   if (RetTy->isVoidType())
7346     return ABIArgInfo::getIgnore();
7347   if (isVectorArgumentType(RetTy))
7348     return ABIArgInfo::getDirect();
7349   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7350     return getNaturalAlignIndirect(RetTy);
7351   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7352                                                : ABIArgInfo::getDirect());
7353 }
7354 
7355 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7356   // Handle the generic C++ ABI.
7357   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7358     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7359 
7360   // Integers and enums are extended to full register width.
7361   if (isPromotableIntegerTypeForABI(Ty))
7362     return ABIArgInfo::getExtend(Ty);
7363 
7364   // Handle vector types and vector-like structure types.  Note that
7365   // as opposed to float-like structure types, we do not allow any
7366   // padding for vector-like structures, so verify the sizes match.
7367   uint64_t Size = getContext().getTypeSize(Ty);
7368   QualType SingleElementTy = GetSingleElementType(Ty);
7369   if (isVectorArgumentType(SingleElementTy) &&
7370       getContext().getTypeSize(SingleElementTy) == Size)
7371     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7372 
7373   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7374   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7375     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7376 
7377   // Handle small structures.
7378   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7379     // Structures with flexible arrays have variable length, so really
7380     // fail the size test above.
7381     const RecordDecl *RD = RT->getDecl();
7382     if (RD->hasFlexibleArrayMember())
7383       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7384 
7385     // The structure is passed as an unextended integer, a float, or a double.
7386     llvm::Type *PassTy;
7387     if (isFPArgumentType(SingleElementTy)) {
7388       assert(Size == 32 || Size == 64);
7389       if (Size == 32)
7390         PassTy = llvm::Type::getFloatTy(getVMContext());
7391       else
7392         PassTy = llvm::Type::getDoubleTy(getVMContext());
7393     } else
7394       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7395     return ABIArgInfo::getDirect(PassTy);
7396   }
7397 
7398   // Non-structure compounds are passed indirectly.
7399   if (isCompoundType(Ty))
7400     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7401 
7402   return ABIArgInfo::getDirect(nullptr);
7403 }
7404 
7405 //===----------------------------------------------------------------------===//
7406 // MSP430 ABI Implementation
7407 //===----------------------------------------------------------------------===//
7408 
7409 namespace {
7410 
7411 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7412 public:
7413   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7414       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
7415   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7416                            CodeGen::CodeGenModule &M) const override;
7417 };
7418 
7419 }
7420 
7421 void MSP430TargetCodeGenInfo::setTargetAttributes(
7422     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7423   if (GV->isDeclaration())
7424     return;
7425   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7426     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7427     if (!InterruptAttr)
7428       return;
7429 
7430     // Handle 'interrupt' attribute:
7431     llvm::Function *F = cast<llvm::Function>(GV);
7432 
7433     // Step 1: Set ISR calling convention.
7434     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7435 
7436     // Step 2: Add attributes goodness.
7437     F->addFnAttr(llvm::Attribute::NoInline);
7438     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7439   }
7440 }
7441 
7442 //===----------------------------------------------------------------------===//
7443 // MIPS ABI Implementation.  This works for both little-endian and
7444 // big-endian variants.
7445 //===----------------------------------------------------------------------===//
7446 
7447 namespace {
7448 class MipsABIInfo : public ABIInfo {
7449   bool IsO32;
7450   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7451   void CoerceToIntArgs(uint64_t TySize,
7452                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7453   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7454   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7455   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7456 public:
7457   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7458     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7459     StackAlignInBytes(IsO32 ? 8 : 16) {}
7460 
7461   ABIArgInfo classifyReturnType(QualType RetTy) const;
7462   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7463   void computeInfo(CGFunctionInfo &FI) const override;
7464   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7465                     QualType Ty) const override;
7466   ABIArgInfo extendType(QualType Ty) const;
7467 };
7468 
7469 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7470   unsigned SizeOfUnwindException;
7471 public:
7472   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7473       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7474         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7475 
7476   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7477     return 29;
7478   }
7479 
7480   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7481                            CodeGen::CodeGenModule &CGM) const override {
7482     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7483     if (!FD) return;
7484     llvm::Function *Fn = cast<llvm::Function>(GV);
7485 
7486     if (FD->hasAttr<MipsLongCallAttr>())
7487       Fn->addFnAttr("long-call");
7488     else if (FD->hasAttr<MipsShortCallAttr>())
7489       Fn->addFnAttr("short-call");
7490 
7491     // Other attributes do not have a meaning for declarations.
7492     if (GV->isDeclaration())
7493       return;
7494 
7495     if (FD->hasAttr<Mips16Attr>()) {
7496       Fn->addFnAttr("mips16");
7497     }
7498     else if (FD->hasAttr<NoMips16Attr>()) {
7499       Fn->addFnAttr("nomips16");
7500     }
7501 
7502     if (FD->hasAttr<MicroMipsAttr>())
7503       Fn->addFnAttr("micromips");
7504     else if (FD->hasAttr<NoMicroMipsAttr>())
7505       Fn->addFnAttr("nomicromips");
7506 
7507     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7508     if (!Attr)
7509       return;
7510 
7511     const char *Kind;
7512     switch (Attr->getInterrupt()) {
7513     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7514     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7515     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7516     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7517     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7518     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7519     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7520     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7521     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7522     }
7523 
7524     Fn->addFnAttr("interrupt", Kind);
7525 
7526   }
7527 
7528   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7529                                llvm::Value *Address) const override;
7530 
7531   unsigned getSizeOfUnwindException() const override {
7532     return SizeOfUnwindException;
7533   }
7534 };
7535 }
7536 
7537 void MipsABIInfo::CoerceToIntArgs(
7538     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7539   llvm::IntegerType *IntTy =
7540     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7541 
7542   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7543   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7544     ArgList.push_back(IntTy);
7545 
7546   // If necessary, add one more integer type to ArgList.
7547   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7548 
7549   if (R)
7550     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7551 }
7552 
7553 // In N32/64, an aligned double precision floating point field is passed in
7554 // a register.
7555 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7556   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7557 
7558   if (IsO32) {
7559     CoerceToIntArgs(TySize, ArgList);
7560     return llvm::StructType::get(getVMContext(), ArgList);
7561   }
7562 
7563   if (Ty->isComplexType())
7564     return CGT.ConvertType(Ty);
7565 
7566   const RecordType *RT = Ty->getAs<RecordType>();
7567 
7568   // Unions/vectors are passed in integer registers.
7569   if (!RT || !RT->isStructureOrClassType()) {
7570     CoerceToIntArgs(TySize, ArgList);
7571     return llvm::StructType::get(getVMContext(), ArgList);
7572   }
7573 
7574   const RecordDecl *RD = RT->getDecl();
7575   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7576   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7577 
7578   uint64_t LastOffset = 0;
7579   unsigned idx = 0;
7580   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7581 
7582   // Iterate over fields in the struct/class and check if there are any aligned
7583   // double fields.
7584   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7585        i != e; ++i, ++idx) {
7586     const QualType Ty = i->getType();
7587     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7588 
7589     if (!BT || BT->getKind() != BuiltinType::Double)
7590       continue;
7591 
7592     uint64_t Offset = Layout.getFieldOffset(idx);
7593     if (Offset % 64) // Ignore doubles that are not aligned.
7594       continue;
7595 
7596     // Add ((Offset - LastOffset) / 64) args of type i64.
7597     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7598       ArgList.push_back(I64);
7599 
7600     // Add double type.
7601     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7602     LastOffset = Offset + 64;
7603   }
7604 
7605   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7606   ArgList.append(IntArgList.begin(), IntArgList.end());
7607 
7608   return llvm::StructType::get(getVMContext(), ArgList);
7609 }
7610 
7611 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7612                                         uint64_t Offset) const {
7613   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7614     return nullptr;
7615 
7616   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7617 }
7618 
7619 ABIArgInfo
7620 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7621   Ty = useFirstFieldIfTransparentUnion(Ty);
7622 
7623   uint64_t OrigOffset = Offset;
7624   uint64_t TySize = getContext().getTypeSize(Ty);
7625   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7626 
7627   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7628                    (uint64_t)StackAlignInBytes);
7629   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7630   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7631 
7632   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7633     // Ignore empty aggregates.
7634     if (TySize == 0)
7635       return ABIArgInfo::getIgnore();
7636 
7637     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7638       Offset = OrigOffset + MinABIStackAlignInBytes;
7639       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7640     }
7641 
7642     // If we have reached here, aggregates are passed directly by coercing to
7643     // another structure type. Padding is inserted if the offset of the
7644     // aggregate is unaligned.
7645     ABIArgInfo ArgInfo =
7646         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7647                               getPaddingType(OrigOffset, CurrOffset));
7648     ArgInfo.setInReg(true);
7649     return ArgInfo;
7650   }
7651 
7652   // Treat an enum type as its underlying type.
7653   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7654     Ty = EnumTy->getDecl()->getIntegerType();
7655 
7656   // Make sure we pass indirectly things that are too large.
7657   if (const auto *EIT = Ty->getAs<ExtIntType>())
7658     if (EIT->getNumBits() > 128 ||
7659         (EIT->getNumBits() > 64 &&
7660          !getContext().getTargetInfo().hasInt128Type()))
7661       return getNaturalAlignIndirect(Ty);
7662 
7663   // All integral types are promoted to the GPR width.
7664   if (Ty->isIntegralOrEnumerationType())
7665     return extendType(Ty);
7666 
7667   return ABIArgInfo::getDirect(
7668       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7669 }
7670 
7671 llvm::Type*
7672 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7673   const RecordType *RT = RetTy->getAs<RecordType>();
7674   SmallVector<llvm::Type*, 8> RTList;
7675 
7676   if (RT && RT->isStructureOrClassType()) {
7677     const RecordDecl *RD = RT->getDecl();
7678     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7679     unsigned FieldCnt = Layout.getFieldCount();
7680 
7681     // N32/64 returns struct/classes in floating point registers if the
7682     // following conditions are met:
7683     // 1. The size of the struct/class is no larger than 128-bit.
7684     // 2. The struct/class has one or two fields all of which are floating
7685     //    point types.
7686     // 3. The offset of the first field is zero (this follows what gcc does).
7687     //
7688     // Any other composite results are returned in integer registers.
7689     //
7690     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7691       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7692       for (; b != e; ++b) {
7693         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7694 
7695         if (!BT || !BT->isFloatingPoint())
7696           break;
7697 
7698         RTList.push_back(CGT.ConvertType(b->getType()));
7699       }
7700 
7701       if (b == e)
7702         return llvm::StructType::get(getVMContext(), RTList,
7703                                      RD->hasAttr<PackedAttr>());
7704 
7705       RTList.clear();
7706     }
7707   }
7708 
7709   CoerceToIntArgs(Size, RTList);
7710   return llvm::StructType::get(getVMContext(), RTList);
7711 }
7712 
7713 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7714   uint64_t Size = getContext().getTypeSize(RetTy);
7715 
7716   if (RetTy->isVoidType())
7717     return ABIArgInfo::getIgnore();
7718 
7719   // O32 doesn't treat zero-sized structs differently from other structs.
7720   // However, N32/N64 ignores zero sized return values.
7721   if (!IsO32 && Size == 0)
7722     return ABIArgInfo::getIgnore();
7723 
7724   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7725     if (Size <= 128) {
7726       if (RetTy->isAnyComplexType())
7727         return ABIArgInfo::getDirect();
7728 
7729       // O32 returns integer vectors in registers and N32/N64 returns all small
7730       // aggregates in registers.
7731       if (!IsO32 ||
7732           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7733         ABIArgInfo ArgInfo =
7734             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7735         ArgInfo.setInReg(true);
7736         return ArgInfo;
7737       }
7738     }
7739 
7740     return getNaturalAlignIndirect(RetTy);
7741   }
7742 
7743   // Treat an enum type as its underlying type.
7744   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7745     RetTy = EnumTy->getDecl()->getIntegerType();
7746 
7747   // Make sure we pass indirectly things that are too large.
7748   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7749     if (EIT->getNumBits() > 128 ||
7750         (EIT->getNumBits() > 64 &&
7751          !getContext().getTargetInfo().hasInt128Type()))
7752       return getNaturalAlignIndirect(RetTy);
7753 
7754   if (isPromotableIntegerTypeForABI(RetTy))
7755     return ABIArgInfo::getExtend(RetTy);
7756 
7757   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7758       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7759     return ABIArgInfo::getSignExtend(RetTy);
7760 
7761   return ABIArgInfo::getDirect();
7762 }
7763 
7764 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7765   ABIArgInfo &RetInfo = FI.getReturnInfo();
7766   if (!getCXXABI().classifyReturnType(FI))
7767     RetInfo = classifyReturnType(FI.getReturnType());
7768 
7769   // Check if a pointer to an aggregate is passed as a hidden argument.
7770   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7771 
7772   for (auto &I : FI.arguments())
7773     I.info = classifyArgumentType(I.type, Offset);
7774 }
7775 
7776 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7777                                QualType OrigTy) const {
7778   QualType Ty = OrigTy;
7779 
7780   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7781   // Pointers are also promoted in the same way but this only matters for N32.
7782   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7783   unsigned PtrWidth = getTarget().getPointerWidth(0);
7784   bool DidPromote = false;
7785   if ((Ty->isIntegerType() &&
7786           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7787       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7788     DidPromote = true;
7789     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7790                                             Ty->isSignedIntegerType());
7791   }
7792 
7793   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7794 
7795   // The alignment of things in the argument area is never larger than
7796   // StackAlignInBytes.
7797   TyInfo.second =
7798     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7799 
7800   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7801   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7802 
7803   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7804                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7805 
7806 
7807   // If there was a promotion, "unpromote" into a temporary.
7808   // TODO: can we just use a pointer into a subset of the original slot?
7809   if (DidPromote) {
7810     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7811     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7812 
7813     // Truncate down to the right width.
7814     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7815                                                  : CGF.IntPtrTy);
7816     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7817     if (OrigTy->isPointerType())
7818       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7819 
7820     CGF.Builder.CreateStore(V, Temp);
7821     Addr = Temp;
7822   }
7823 
7824   return Addr;
7825 }
7826 
7827 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7828   int TySize = getContext().getTypeSize(Ty);
7829 
7830   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7831   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7832     return ABIArgInfo::getSignExtend(Ty);
7833 
7834   return ABIArgInfo::getExtend(Ty);
7835 }
7836 
7837 bool
7838 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7839                                                llvm::Value *Address) const {
7840   // This information comes from gcc's implementation, which seems to
7841   // as canonical as it gets.
7842 
7843   // Everything on MIPS is 4 bytes.  Double-precision FP registers
7844   // are aliased to pairs of single-precision FP registers.
7845   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7846 
7847   // 0-31 are the general purpose registers, $0 - $31.
7848   // 32-63 are the floating-point registers, $f0 - $f31.
7849   // 64 and 65 are the multiply/divide registers, $hi and $lo.
7850   // 66 is the (notional, I think) register for signal-handler return.
7851   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7852 
7853   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7854   // They are one bit wide and ignored here.
7855 
7856   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7857   // (coprocessor 1 is the FP unit)
7858   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7859   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7860   // 176-181 are the DSP accumulator registers.
7861   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7862   return false;
7863 }
7864 
7865 //===----------------------------------------------------------------------===//
7866 // AVR ABI Implementation.
7867 //===----------------------------------------------------------------------===//
7868 
7869 namespace {
7870 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7871 public:
7872   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7873       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
7874 
7875   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7876                            CodeGen::CodeGenModule &CGM) const override {
7877     if (GV->isDeclaration())
7878       return;
7879     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7880     if (!FD) return;
7881     auto *Fn = cast<llvm::Function>(GV);
7882 
7883     if (FD->getAttr<AVRInterruptAttr>())
7884       Fn->addFnAttr("interrupt");
7885 
7886     if (FD->getAttr<AVRSignalAttr>())
7887       Fn->addFnAttr("signal");
7888   }
7889 };
7890 }
7891 
7892 //===----------------------------------------------------------------------===//
7893 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
7894 // Currently subclassed only to implement custom OpenCL C function attribute
7895 // handling.
7896 //===----------------------------------------------------------------------===//
7897 
7898 namespace {
7899 
7900 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7901 public:
7902   TCETargetCodeGenInfo(CodeGenTypes &CGT)
7903     : DefaultTargetCodeGenInfo(CGT) {}
7904 
7905   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7906                            CodeGen::CodeGenModule &M) const override;
7907 };
7908 
7909 void TCETargetCodeGenInfo::setTargetAttributes(
7910     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7911   if (GV->isDeclaration())
7912     return;
7913   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7914   if (!FD) return;
7915 
7916   llvm::Function *F = cast<llvm::Function>(GV);
7917 
7918   if (M.getLangOpts().OpenCL) {
7919     if (FD->hasAttr<OpenCLKernelAttr>()) {
7920       // OpenCL C Kernel functions are not subject to inlining
7921       F->addFnAttr(llvm::Attribute::NoInline);
7922       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7923       if (Attr) {
7924         // Convert the reqd_work_group_size() attributes to metadata.
7925         llvm::LLVMContext &Context = F->getContext();
7926         llvm::NamedMDNode *OpenCLMetadata =
7927             M.getModule().getOrInsertNamedMetadata(
7928                 "opencl.kernel_wg_size_info");
7929 
7930         SmallVector<llvm::Metadata *, 5> Operands;
7931         Operands.push_back(llvm::ConstantAsMetadata::get(F));
7932 
7933         Operands.push_back(
7934             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7935                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7936         Operands.push_back(
7937             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7938                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7939         Operands.push_back(
7940             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7941                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7942 
7943         // Add a boolean constant operand for "required" (true) or "hint"
7944         // (false) for implementing the work_group_size_hint attr later.
7945         // Currently always true as the hint is not yet implemented.
7946         Operands.push_back(
7947             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7948         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7949       }
7950     }
7951   }
7952 }
7953 
7954 }
7955 
7956 //===----------------------------------------------------------------------===//
7957 // Hexagon ABI Implementation
7958 //===----------------------------------------------------------------------===//
7959 
7960 namespace {
7961 
7962 class HexagonABIInfo : public DefaultABIInfo {
7963 public:
7964   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7965 
7966 private:
7967   ABIArgInfo classifyReturnType(QualType RetTy) const;
7968   ABIArgInfo classifyArgumentType(QualType RetTy) const;
7969   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
7970 
7971   void computeInfo(CGFunctionInfo &FI) const override;
7972 
7973   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7974                     QualType Ty) const override;
7975   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
7976                               QualType Ty) const;
7977   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
7978                               QualType Ty) const;
7979   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
7980                                    QualType Ty) const;
7981 };
7982 
7983 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7984 public:
7985   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7986       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
7987 
7988   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7989     return 29;
7990   }
7991 
7992   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7993                            CodeGen::CodeGenModule &GCM) const override {
7994     if (GV->isDeclaration())
7995       return;
7996     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7997     if (!FD)
7998       return;
7999   }
8000 };
8001 
8002 } // namespace
8003 
8004 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8005   unsigned RegsLeft = 6;
8006   if (!getCXXABI().classifyReturnType(FI))
8007     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8008   for (auto &I : FI.arguments())
8009     I.info = classifyArgumentType(I.type, &RegsLeft);
8010 }
8011 
8012 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8013   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8014                        " through registers");
8015 
8016   if (*RegsLeft == 0)
8017     return false;
8018 
8019   if (Size <= 32) {
8020     (*RegsLeft)--;
8021     return true;
8022   }
8023 
8024   if (2 <= (*RegsLeft & (~1U))) {
8025     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8026     return true;
8027   }
8028 
8029   // Next available register was r5 but candidate was greater than 32-bits so it
8030   // has to go on the stack. However we still consume r5
8031   if (*RegsLeft == 1)
8032     *RegsLeft = 0;
8033 
8034   return false;
8035 }
8036 
8037 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8038                                                 unsigned *RegsLeft) const {
8039   if (!isAggregateTypeForABI(Ty)) {
8040     // Treat an enum type as its underlying type.
8041     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8042       Ty = EnumTy->getDecl()->getIntegerType();
8043 
8044     uint64_t Size = getContext().getTypeSize(Ty);
8045     if (Size <= 64)
8046       HexagonAdjustRegsLeft(Size, RegsLeft);
8047 
8048     if (Size > 64 && Ty->isExtIntType())
8049       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8050 
8051     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8052                                              : ABIArgInfo::getDirect();
8053   }
8054 
8055   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8056     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8057 
8058   // Ignore empty records.
8059   if (isEmptyRecord(getContext(), Ty, true))
8060     return ABIArgInfo::getIgnore();
8061 
8062   uint64_t Size = getContext().getTypeSize(Ty);
8063   unsigned Align = getContext().getTypeAlign(Ty);
8064 
8065   if (Size > 64)
8066     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8067 
8068   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8069     Align = Size <= 32 ? 32 : 64;
8070   if (Size <= Align) {
8071     // Pass in the smallest viable integer type.
8072     if (!llvm::isPowerOf2_64(Size))
8073       Size = llvm::NextPowerOf2(Size);
8074     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8075   }
8076   return DefaultABIInfo::classifyArgumentType(Ty);
8077 }
8078 
8079 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8080   if (RetTy->isVoidType())
8081     return ABIArgInfo::getIgnore();
8082 
8083   const TargetInfo &T = CGT.getTarget();
8084   uint64_t Size = getContext().getTypeSize(RetTy);
8085 
8086   if (RetTy->getAs<VectorType>()) {
8087     // HVX vectors are returned in vector registers or register pairs.
8088     if (T.hasFeature("hvx")) {
8089       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8090       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8091       if (Size == VecSize || Size == 2*VecSize)
8092         return ABIArgInfo::getDirectInReg();
8093     }
8094     // Large vector types should be returned via memory.
8095     if (Size > 64)
8096       return getNaturalAlignIndirect(RetTy);
8097   }
8098 
8099   if (!isAggregateTypeForABI(RetTy)) {
8100     // Treat an enum type as its underlying type.
8101     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8102       RetTy = EnumTy->getDecl()->getIntegerType();
8103 
8104     if (Size > 64 && RetTy->isExtIntType())
8105       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8106 
8107     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8108                                                 : ABIArgInfo::getDirect();
8109   }
8110 
8111   if (isEmptyRecord(getContext(), RetTy, true))
8112     return ABIArgInfo::getIgnore();
8113 
8114   // Aggregates <= 8 bytes are returned in registers, other aggregates
8115   // are returned indirectly.
8116   if (Size <= 64) {
8117     // Return in the smallest viable integer type.
8118     if (!llvm::isPowerOf2_64(Size))
8119       Size = llvm::NextPowerOf2(Size);
8120     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8121   }
8122   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8123 }
8124 
8125 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8126                                             Address VAListAddr,
8127                                             QualType Ty) const {
8128   // Load the overflow area pointer.
8129   Address __overflow_area_pointer_p =
8130       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8131   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8132       __overflow_area_pointer_p, "__overflow_area_pointer");
8133 
8134   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8135   if (Align > 4) {
8136     // Alignment should be a power of 2.
8137     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8138 
8139     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8140     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8141 
8142     // Add offset to the current pointer to access the argument.
8143     __overflow_area_pointer =
8144         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8145     llvm::Value *AsInt =
8146         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8147 
8148     // Create a mask which should be "AND"ed
8149     // with (overflow_arg_area + align - 1)
8150     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8151     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8152         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8153         "__overflow_area_pointer.align");
8154   }
8155 
8156   // Get the type of the argument from memory and bitcast
8157   // overflow area pointer to the argument type.
8158   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8159   Address AddrTyped = CGF.Builder.CreateBitCast(
8160       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8161       llvm::PointerType::getUnqual(PTy));
8162 
8163   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8164   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8165 
8166   __overflow_area_pointer = CGF.Builder.CreateGEP(
8167       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8168       "__overflow_area_pointer.next");
8169   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8170 
8171   return AddrTyped;
8172 }
8173 
8174 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8175                                             Address VAListAddr,
8176                                             QualType Ty) const {
8177   // FIXME: Need to handle alignment
8178   llvm::Type *BP = CGF.Int8PtrTy;
8179   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8180   CGBuilderTy &Builder = CGF.Builder;
8181   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8182   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8183   // Handle address alignment for type alignment > 32 bits
8184   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8185   if (TyAlign > 4) {
8186     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8187     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8188     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8189     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8190     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8191   }
8192   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8193   Address AddrTyped = Builder.CreateBitCast(
8194       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8195 
8196   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8197   llvm::Value *NextAddr = Builder.CreateGEP(
8198       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8199   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8200 
8201   return AddrTyped;
8202 }
8203 
8204 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8205                                                  Address VAListAddr,
8206                                                  QualType Ty) const {
8207   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8208 
8209   if (ArgSize > 8)
8210     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8211 
8212   // Here we have check if the argument is in register area or
8213   // in overflow area.
8214   // If the saved register area pointer + argsize rounded up to alignment >
8215   // saved register area end pointer, argument is in overflow area.
8216   unsigned RegsLeft = 6;
8217   Ty = CGF.getContext().getCanonicalType(Ty);
8218   (void)classifyArgumentType(Ty, &RegsLeft);
8219 
8220   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8221   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8222   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8223   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8224 
8225   // Get rounded size of the argument.GCC does not allow vararg of
8226   // size < 4 bytes. We follow the same logic here.
8227   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8228   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8229 
8230   // Argument may be in saved register area
8231   CGF.EmitBlock(MaybeRegBlock);
8232 
8233   // Load the current saved register area pointer.
8234   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8235       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8236   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8237       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8238 
8239   // Load the saved register area end pointer.
8240   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8241       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8242   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8243       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8244 
8245   // If the size of argument is > 4 bytes, check if the stack
8246   // location is aligned to 8 bytes
8247   if (ArgAlign > 4) {
8248 
8249     llvm::Value *__current_saved_reg_area_pointer_int =
8250         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8251                                    CGF.Int32Ty);
8252 
8253     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8254         __current_saved_reg_area_pointer_int,
8255         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8256         "align_current_saved_reg_area_pointer");
8257 
8258     __current_saved_reg_area_pointer_int =
8259         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8260                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8261                               "align_current_saved_reg_area_pointer");
8262 
8263     __current_saved_reg_area_pointer =
8264         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8265                                    __current_saved_reg_area_pointer->getType(),
8266                                    "align_current_saved_reg_area_pointer");
8267   }
8268 
8269   llvm::Value *__new_saved_reg_area_pointer =
8270       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8271                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8272                             "__new_saved_reg_area_pointer");
8273 
8274   llvm::Value *UsingStack = 0;
8275   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8276                                          __saved_reg_area_end_pointer);
8277 
8278   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8279 
8280   // Argument in saved register area
8281   // Implement the block where argument is in register saved area
8282   CGF.EmitBlock(InRegBlock);
8283 
8284   llvm::Type *PTy = CGF.ConvertType(Ty);
8285   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8286       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8287 
8288   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8289                           __current_saved_reg_area_pointer_p);
8290 
8291   CGF.EmitBranch(ContBlock);
8292 
8293   // Argument in overflow area
8294   // Implement the block where the argument is in overflow area.
8295   CGF.EmitBlock(OnStackBlock);
8296 
8297   // Load the overflow area pointer
8298   Address __overflow_area_pointer_p =
8299       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8300   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8301       __overflow_area_pointer_p, "__overflow_area_pointer");
8302 
8303   // Align the overflow area pointer according to the alignment of the argument
8304   if (ArgAlign > 4) {
8305     llvm::Value *__overflow_area_pointer_int =
8306         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8307 
8308     __overflow_area_pointer_int =
8309         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8310                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8311                               "align_overflow_area_pointer");
8312 
8313     __overflow_area_pointer_int =
8314         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8315                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8316                               "align_overflow_area_pointer");
8317 
8318     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8319         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8320         "align_overflow_area_pointer");
8321   }
8322 
8323   // Get the pointer for next argument in overflow area and store it
8324   // to overflow area pointer.
8325   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8326       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8327       "__overflow_area_pointer.next");
8328 
8329   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8330                           __overflow_area_pointer_p);
8331 
8332   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8333                           __current_saved_reg_area_pointer_p);
8334 
8335   // Bitcast the overflow area pointer to the type of argument.
8336   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8337   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8338       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8339 
8340   CGF.EmitBranch(ContBlock);
8341 
8342   // Get the correct pointer to load the variable argument
8343   // Implement the ContBlock
8344   CGF.EmitBlock(ContBlock);
8345 
8346   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8347   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8348   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8349   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8350 
8351   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8352 }
8353 
8354 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8355                                   QualType Ty) const {
8356 
8357   if (getTarget().getTriple().isMusl())
8358     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8359 
8360   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8361 }
8362 
8363 //===----------------------------------------------------------------------===//
8364 // Lanai ABI Implementation
8365 //===----------------------------------------------------------------------===//
8366 
8367 namespace {
8368 class LanaiABIInfo : public DefaultABIInfo {
8369 public:
8370   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8371 
8372   bool shouldUseInReg(QualType Ty, CCState &State) const;
8373 
8374   void computeInfo(CGFunctionInfo &FI) const override {
8375     CCState State(FI);
8376     // Lanai uses 4 registers to pass arguments unless the function has the
8377     // regparm attribute set.
8378     if (FI.getHasRegParm()) {
8379       State.FreeRegs = FI.getRegParm();
8380     } else {
8381       State.FreeRegs = 4;
8382     }
8383 
8384     if (!getCXXABI().classifyReturnType(FI))
8385       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8386     for (auto &I : FI.arguments())
8387       I.info = classifyArgumentType(I.type, State);
8388   }
8389 
8390   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8391   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8392 };
8393 } // end anonymous namespace
8394 
8395 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8396   unsigned Size = getContext().getTypeSize(Ty);
8397   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8398 
8399   if (SizeInRegs == 0)
8400     return false;
8401 
8402   if (SizeInRegs > State.FreeRegs) {
8403     State.FreeRegs = 0;
8404     return false;
8405   }
8406 
8407   State.FreeRegs -= SizeInRegs;
8408 
8409   return true;
8410 }
8411 
8412 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8413                                            CCState &State) const {
8414   if (!ByVal) {
8415     if (State.FreeRegs) {
8416       --State.FreeRegs; // Non-byval indirects just use one pointer.
8417       return getNaturalAlignIndirectInReg(Ty);
8418     }
8419     return getNaturalAlignIndirect(Ty, false);
8420   }
8421 
8422   // Compute the byval alignment.
8423   const unsigned MinABIStackAlignInBytes = 4;
8424   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8425   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8426                                  /*Realign=*/TypeAlign >
8427                                      MinABIStackAlignInBytes);
8428 }
8429 
8430 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8431                                               CCState &State) const {
8432   // Check with the C++ ABI first.
8433   const RecordType *RT = Ty->getAs<RecordType>();
8434   if (RT) {
8435     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8436     if (RAA == CGCXXABI::RAA_Indirect) {
8437       return getIndirectResult(Ty, /*ByVal=*/false, State);
8438     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8439       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
8440     }
8441   }
8442 
8443   if (isAggregateTypeForABI(Ty)) {
8444     // Structures with flexible arrays are always indirect.
8445     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8446       return getIndirectResult(Ty, /*ByVal=*/true, State);
8447 
8448     // Ignore empty structs/unions.
8449     if (isEmptyRecord(getContext(), Ty, true))
8450       return ABIArgInfo::getIgnore();
8451 
8452     llvm::LLVMContext &LLVMContext = getVMContext();
8453     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8454     if (SizeInRegs <= State.FreeRegs) {
8455       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8456       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8457       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8458       State.FreeRegs -= SizeInRegs;
8459       return ABIArgInfo::getDirectInReg(Result);
8460     } else {
8461       State.FreeRegs = 0;
8462     }
8463     return getIndirectResult(Ty, true, State);
8464   }
8465 
8466   // Treat an enum type as its underlying type.
8467   if (const auto *EnumTy = Ty->getAs<EnumType>())
8468     Ty = EnumTy->getDecl()->getIntegerType();
8469 
8470   bool InReg = shouldUseInReg(Ty, State);
8471 
8472   // Don't pass >64 bit integers in registers.
8473   if (const auto *EIT = Ty->getAs<ExtIntType>())
8474     if (EIT->getNumBits() > 64)
8475       return getIndirectResult(Ty, /*ByVal=*/true, State);
8476 
8477   if (isPromotableIntegerTypeForABI(Ty)) {
8478     if (InReg)
8479       return ABIArgInfo::getDirectInReg();
8480     return ABIArgInfo::getExtend(Ty);
8481   }
8482   if (InReg)
8483     return ABIArgInfo::getDirectInReg();
8484   return ABIArgInfo::getDirect();
8485 }
8486 
8487 namespace {
8488 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8489 public:
8490   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8491       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8492 };
8493 }
8494 
8495 //===----------------------------------------------------------------------===//
8496 // AMDGPU ABI Implementation
8497 //===----------------------------------------------------------------------===//
8498 
8499 namespace {
8500 
8501 class AMDGPUABIInfo final : public DefaultABIInfo {
8502 private:
8503   static const unsigned MaxNumRegsForArgsRet = 16;
8504 
8505   unsigned numRegsForType(QualType Ty) const;
8506 
8507   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8508   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8509                                          uint64_t Members) const override;
8510 
8511   // Coerce HIP pointer arguments from generic pointers to global ones.
8512   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8513                                        unsigned ToAS) const {
8514     // Structure types.
8515     if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
8516       SmallVector<llvm::Type *, 8> EltTys;
8517       bool Changed = false;
8518       for (auto T : STy->elements()) {
8519         auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8520         EltTys.push_back(NT);
8521         Changed |= (NT != T);
8522       }
8523       // Skip if there is no change in element types.
8524       if (!Changed)
8525         return STy;
8526       if (STy->hasName())
8527         return llvm::StructType::create(
8528             EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
8529       return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
8530     }
8531     // Array types.
8532     if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
8533       auto T = ATy->getElementType();
8534       auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8535       // Skip if there is no change in that element type.
8536       if (NT == T)
8537         return ATy;
8538       return llvm::ArrayType::get(NT, ATy->getNumElements());
8539     }
8540     // Single value types.
8541     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8542       return llvm::PointerType::get(
8543           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8544     return Ty;
8545   }
8546 
8547 public:
8548   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8549     DefaultABIInfo(CGT) {}
8550 
8551   ABIArgInfo classifyReturnType(QualType RetTy) const;
8552   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8553   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8554 
8555   void computeInfo(CGFunctionInfo &FI) const override;
8556   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8557                     QualType Ty) const override;
8558 };
8559 
8560 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8561   return true;
8562 }
8563 
8564 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8565   const Type *Base, uint64_t Members) const {
8566   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8567 
8568   // Homogeneous Aggregates may occupy at most 16 registers.
8569   return Members * NumRegs <= MaxNumRegsForArgsRet;
8570 }
8571 
8572 /// Estimate number of registers the type will use when passed in registers.
8573 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8574   unsigned NumRegs = 0;
8575 
8576   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8577     // Compute from the number of elements. The reported size is based on the
8578     // in-memory size, which includes the padding 4th element for 3-vectors.
8579     QualType EltTy = VT->getElementType();
8580     unsigned EltSize = getContext().getTypeSize(EltTy);
8581 
8582     // 16-bit element vectors should be passed as packed.
8583     if (EltSize == 16)
8584       return (VT->getNumElements() + 1) / 2;
8585 
8586     unsigned EltNumRegs = (EltSize + 31) / 32;
8587     return EltNumRegs * VT->getNumElements();
8588   }
8589 
8590   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8591     const RecordDecl *RD = RT->getDecl();
8592     assert(!RD->hasFlexibleArrayMember());
8593 
8594     for (const FieldDecl *Field : RD->fields()) {
8595       QualType FieldTy = Field->getType();
8596       NumRegs += numRegsForType(FieldTy);
8597     }
8598 
8599     return NumRegs;
8600   }
8601 
8602   return (getContext().getTypeSize(Ty) + 31) / 32;
8603 }
8604 
8605 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8606   llvm::CallingConv::ID CC = FI.getCallingConvention();
8607 
8608   if (!getCXXABI().classifyReturnType(FI))
8609     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8610 
8611   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8612   for (auto &Arg : FI.arguments()) {
8613     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8614       Arg.info = classifyKernelArgumentType(Arg.type);
8615     } else {
8616       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8617     }
8618   }
8619 }
8620 
8621 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8622                                  QualType Ty) const {
8623   llvm_unreachable("AMDGPU does not support varargs");
8624 }
8625 
8626 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8627   if (isAggregateTypeForABI(RetTy)) {
8628     // Records with non-trivial destructors/copy-constructors should not be
8629     // returned by value.
8630     if (!getRecordArgABI(RetTy, getCXXABI())) {
8631       // Ignore empty structs/unions.
8632       if (isEmptyRecord(getContext(), RetTy, true))
8633         return ABIArgInfo::getIgnore();
8634 
8635       // Lower single-element structs to just return a regular value.
8636       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8637         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8638 
8639       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8640         const RecordDecl *RD = RT->getDecl();
8641         if (RD->hasFlexibleArrayMember())
8642           return DefaultABIInfo::classifyReturnType(RetTy);
8643       }
8644 
8645       // Pack aggregates <= 4 bytes into single VGPR or pair.
8646       uint64_t Size = getContext().getTypeSize(RetTy);
8647       if (Size <= 16)
8648         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8649 
8650       if (Size <= 32)
8651         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8652 
8653       if (Size <= 64) {
8654         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8655         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8656       }
8657 
8658       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8659         return ABIArgInfo::getDirect();
8660     }
8661   }
8662 
8663   // Otherwise just do the default thing.
8664   return DefaultABIInfo::classifyReturnType(RetTy);
8665 }
8666 
8667 /// For kernels all parameters are really passed in a special buffer. It doesn't
8668 /// make sense to pass anything byval, so everything must be direct.
8669 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8670   Ty = useFirstFieldIfTransparentUnion(Ty);
8671 
8672   // TODO: Can we omit empty structs?
8673 
8674   llvm::Type *LTy = nullptr;
8675   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8676     LTy = CGT.ConvertType(QualType(SeltTy, 0));
8677 
8678   if (getContext().getLangOpts().HIP) {
8679     if (!LTy)
8680       LTy = CGT.ConvertType(Ty);
8681     LTy = coerceKernelArgumentType(
8682         LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8683         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8684   }
8685 
8686   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8687   // individual elements, which confuses the Clover OpenCL backend; therefore we
8688   // have to set it to false here. Other args of getDirect() are just defaults.
8689   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8690 }
8691 
8692 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8693                                                unsigned &NumRegsLeft) const {
8694   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8695 
8696   Ty = useFirstFieldIfTransparentUnion(Ty);
8697 
8698   if (isAggregateTypeForABI(Ty)) {
8699     // Records with non-trivial destructors/copy-constructors should not be
8700     // passed by value.
8701     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8702       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8703 
8704     // Ignore empty structs/unions.
8705     if (isEmptyRecord(getContext(), Ty, true))
8706       return ABIArgInfo::getIgnore();
8707 
8708     // Lower single-element structs to just pass a regular value. TODO: We
8709     // could do reasonable-size multiple-element structs too, using getExpand(),
8710     // though watch out for things like bitfields.
8711     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8712       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8713 
8714     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8715       const RecordDecl *RD = RT->getDecl();
8716       if (RD->hasFlexibleArrayMember())
8717         return DefaultABIInfo::classifyArgumentType(Ty);
8718     }
8719 
8720     // Pack aggregates <= 8 bytes into single VGPR or pair.
8721     uint64_t Size = getContext().getTypeSize(Ty);
8722     if (Size <= 64) {
8723       unsigned NumRegs = (Size + 31) / 32;
8724       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8725 
8726       if (Size <= 16)
8727         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8728 
8729       if (Size <= 32)
8730         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8731 
8732       // XXX: Should this be i64 instead, and should the limit increase?
8733       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8734       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8735     }
8736 
8737     if (NumRegsLeft > 0) {
8738       unsigned NumRegs = numRegsForType(Ty);
8739       if (NumRegsLeft >= NumRegs) {
8740         NumRegsLeft -= NumRegs;
8741         return ABIArgInfo::getDirect();
8742       }
8743     }
8744   }
8745 
8746   // Otherwise just do the default thing.
8747   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8748   if (!ArgInfo.isIndirect()) {
8749     unsigned NumRegs = numRegsForType(Ty);
8750     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8751   }
8752 
8753   return ArgInfo;
8754 }
8755 
8756 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8757 public:
8758   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8759       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8760   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8761                            CodeGen::CodeGenModule &M) const override;
8762   unsigned getOpenCLKernelCallingConv() const override;
8763 
8764   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8765       llvm::PointerType *T, QualType QT) const override;
8766 
8767   LangAS getASTAllocaAddressSpace() const override {
8768     return getLangASFromTargetAS(
8769         getABIInfo().getDataLayout().getAllocaAddrSpace());
8770   }
8771   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8772                                   const VarDecl *D) const override;
8773   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8774                                          SyncScope Scope,
8775                                          llvm::AtomicOrdering Ordering,
8776                                          llvm::LLVMContext &Ctx) const override;
8777   llvm::Function *
8778   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8779                             llvm::Function *BlockInvokeFunc,
8780                             llvm::Value *BlockLiteral) const override;
8781   bool shouldEmitStaticExternCAliases() const override;
8782   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8783 };
8784 }
8785 
8786 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8787                                               llvm::GlobalValue *GV) {
8788   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8789     return false;
8790 
8791   return D->hasAttr<OpenCLKernelAttr>() ||
8792          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8793          (isa<VarDecl>(D) &&
8794           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8795            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8796            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8797 }
8798 
8799 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8800     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8801   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8802     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8803     GV->setDSOLocal(true);
8804   }
8805 
8806   if (GV->isDeclaration())
8807     return;
8808   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8809   if (!FD)
8810     return;
8811 
8812   llvm::Function *F = cast<llvm::Function>(GV);
8813 
8814   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8815     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8816 
8817 
8818   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8819                               FD->hasAttr<OpenCLKernelAttr>();
8820   const bool IsHIPKernel = M.getLangOpts().HIP &&
8821                            FD->hasAttr<CUDAGlobalAttr>();
8822   if ((IsOpenCLKernel || IsHIPKernel) &&
8823       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8824     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8825 
8826   if (IsHIPKernel)
8827     F->addFnAttr("uniform-work-group-size", "true");
8828 
8829 
8830   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8831   if (ReqdWGS || FlatWGS) {
8832     unsigned Min = 0;
8833     unsigned Max = 0;
8834     if (FlatWGS) {
8835       Min = FlatWGS->getMin()
8836                 ->EvaluateKnownConstInt(M.getContext())
8837                 .getExtValue();
8838       Max = FlatWGS->getMax()
8839                 ->EvaluateKnownConstInt(M.getContext())
8840                 .getExtValue();
8841     }
8842     if (ReqdWGS && Min == 0 && Max == 0)
8843       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8844 
8845     if (Min != 0) {
8846       assert(Min <= Max && "Min must be less than or equal Max");
8847 
8848       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8849       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8850     } else
8851       assert(Max == 0 && "Max must be zero");
8852   } else if (IsOpenCLKernel || IsHIPKernel) {
8853     // By default, restrict the maximum size to a value specified by
8854     // --gpu-max-threads-per-block=n or its default value for HIP.
8855     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
8856     const unsigned DefaultMaxWorkGroupSize =
8857         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
8858                        : M.getLangOpts().GPUMaxThreadsPerBlock;
8859     std::string AttrVal =
8860         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
8861     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8862   }
8863 
8864   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
8865     unsigned Min =
8866         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8867     unsigned Max = Attr->getMax() ? Attr->getMax()
8868                                         ->EvaluateKnownConstInt(M.getContext())
8869                                         .getExtValue()
8870                                   : 0;
8871 
8872     if (Min != 0) {
8873       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8874 
8875       std::string AttrVal = llvm::utostr(Min);
8876       if (Max != 0)
8877         AttrVal = AttrVal + "," + llvm::utostr(Max);
8878       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
8879     } else
8880       assert(Max == 0 && "Max must be zero");
8881   }
8882 
8883   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
8884     unsigned NumSGPR = Attr->getNumSGPR();
8885 
8886     if (NumSGPR != 0)
8887       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
8888   }
8889 
8890   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
8891     uint32_t NumVGPR = Attr->getNumVGPR();
8892 
8893     if (NumVGPR != 0)
8894       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
8895   }
8896 }
8897 
8898 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8899   return llvm::CallingConv::AMDGPU_KERNEL;
8900 }
8901 
8902 // Currently LLVM assumes null pointers always have value 0,
8903 // which results in incorrectly transformed IR. Therefore, instead of
8904 // emitting null pointers in private and local address spaces, a null
8905 // pointer in generic address space is emitted which is casted to a
8906 // pointer in local or private address space.
8907 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
8908     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
8909     QualType QT) const {
8910   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
8911     return llvm::ConstantPointerNull::get(PT);
8912 
8913   auto &Ctx = CGM.getContext();
8914   auto NPT = llvm::PointerType::get(PT->getElementType(),
8915       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8916   return llvm::ConstantExpr::getAddrSpaceCast(
8917       llvm::ConstantPointerNull::get(NPT), PT);
8918 }
8919 
8920 LangAS
8921 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8922                                                   const VarDecl *D) const {
8923   assert(!CGM.getLangOpts().OpenCL &&
8924          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8925          "Address space agnostic languages only");
8926   LangAS DefaultGlobalAS = getLangASFromTargetAS(
8927       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
8928   if (!D)
8929     return DefaultGlobalAS;
8930 
8931   LangAS AddrSpace = D->getType().getAddressSpace();
8932   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
8933   if (AddrSpace != LangAS::Default)
8934     return AddrSpace;
8935 
8936   if (CGM.isTypeConstant(D->getType(), false)) {
8937     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8938       return ConstAS.getValue();
8939   }
8940   return DefaultGlobalAS;
8941 }
8942 
8943 llvm::SyncScope::ID
8944 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8945                                             SyncScope Scope,
8946                                             llvm::AtomicOrdering Ordering,
8947                                             llvm::LLVMContext &Ctx) const {
8948   std::string Name;
8949   switch (Scope) {
8950   case SyncScope::OpenCLWorkGroup:
8951     Name = "workgroup";
8952     break;
8953   case SyncScope::OpenCLDevice:
8954     Name = "agent";
8955     break;
8956   case SyncScope::OpenCLAllSVMDevices:
8957     Name = "";
8958     break;
8959   case SyncScope::OpenCLSubGroup:
8960     Name = "wavefront";
8961   }
8962 
8963   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8964     if (!Name.empty())
8965       Name = Twine(Twine(Name) + Twine("-")).str();
8966 
8967     Name = Twine(Twine(Name) + Twine("one-as")).str();
8968   }
8969 
8970   return Ctx.getOrInsertSyncScopeID(Name);
8971 }
8972 
8973 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8974   return false;
8975 }
8976 
8977 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
8978     const FunctionType *&FT) const {
8979   FT = getABIInfo().getContext().adjustFunctionType(
8980       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
8981 }
8982 
8983 //===----------------------------------------------------------------------===//
8984 // SPARC v8 ABI Implementation.
8985 // Based on the SPARC Compliance Definition version 2.4.1.
8986 //
8987 // Ensures that complex values are passed in registers.
8988 //
8989 namespace {
8990 class SparcV8ABIInfo : public DefaultABIInfo {
8991 public:
8992   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8993 
8994 private:
8995   ABIArgInfo classifyReturnType(QualType RetTy) const;
8996   void computeInfo(CGFunctionInfo &FI) const override;
8997 };
8998 } // end anonymous namespace
8999 
9000 
9001 ABIArgInfo
9002 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9003   if (Ty->isAnyComplexType()) {
9004     return ABIArgInfo::getDirect();
9005   }
9006   else {
9007     return DefaultABIInfo::classifyReturnType(Ty);
9008   }
9009 }
9010 
9011 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9012 
9013   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9014   for (auto &Arg : FI.arguments())
9015     Arg.info = classifyArgumentType(Arg.type);
9016 }
9017 
9018 namespace {
9019 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9020 public:
9021   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9022       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9023 };
9024 } // end anonymous namespace
9025 
9026 //===----------------------------------------------------------------------===//
9027 // SPARC v9 ABI Implementation.
9028 // Based on the SPARC Compliance Definition version 2.4.1.
9029 //
9030 // Function arguments a mapped to a nominal "parameter array" and promoted to
9031 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9032 // the array, structs larger than 16 bytes are passed indirectly.
9033 //
9034 // One case requires special care:
9035 //
9036 //   struct mixed {
9037 //     int i;
9038 //     float f;
9039 //   };
9040 //
9041 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9042 // parameter array, but the int is passed in an integer register, and the float
9043 // is passed in a floating point register. This is represented as two arguments
9044 // with the LLVM IR inreg attribute:
9045 //
9046 //   declare void f(i32 inreg %i, float inreg %f)
9047 //
9048 // The code generator will only allocate 4 bytes from the parameter array for
9049 // the inreg arguments. All other arguments are allocated a multiple of 8
9050 // bytes.
9051 //
9052 namespace {
9053 class SparcV9ABIInfo : public ABIInfo {
9054 public:
9055   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9056 
9057 private:
9058   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9059   void computeInfo(CGFunctionInfo &FI) const override;
9060   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9061                     QualType Ty) const override;
9062 
9063   // Coercion type builder for structs passed in registers. The coercion type
9064   // serves two purposes:
9065   //
9066   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9067   //    in registers.
9068   // 2. Expose aligned floating point elements as first-level elements, so the
9069   //    code generator knows to pass them in floating point registers.
9070   //
9071   // We also compute the InReg flag which indicates that the struct contains
9072   // aligned 32-bit floats.
9073   //
9074   struct CoerceBuilder {
9075     llvm::LLVMContext &Context;
9076     const llvm::DataLayout &DL;
9077     SmallVector<llvm::Type*, 8> Elems;
9078     uint64_t Size;
9079     bool InReg;
9080 
9081     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9082       : Context(c), DL(dl), Size(0), InReg(false) {}
9083 
9084     // Pad Elems with integers until Size is ToSize.
9085     void pad(uint64_t ToSize) {
9086       assert(ToSize >= Size && "Cannot remove elements");
9087       if (ToSize == Size)
9088         return;
9089 
9090       // Finish the current 64-bit word.
9091       uint64_t Aligned = llvm::alignTo(Size, 64);
9092       if (Aligned > Size && Aligned <= ToSize) {
9093         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9094         Size = Aligned;
9095       }
9096 
9097       // Add whole 64-bit words.
9098       while (Size + 64 <= ToSize) {
9099         Elems.push_back(llvm::Type::getInt64Ty(Context));
9100         Size += 64;
9101       }
9102 
9103       // Final in-word padding.
9104       if (Size < ToSize) {
9105         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9106         Size = ToSize;
9107       }
9108     }
9109 
9110     // Add a floating point element at Offset.
9111     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9112       // Unaligned floats are treated as integers.
9113       if (Offset % Bits)
9114         return;
9115       // The InReg flag is only required if there are any floats < 64 bits.
9116       if (Bits < 64)
9117         InReg = true;
9118       pad(Offset);
9119       Elems.push_back(Ty);
9120       Size = Offset + Bits;
9121     }
9122 
9123     // Add a struct type to the coercion type, starting at Offset (in bits).
9124     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9125       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9126       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9127         llvm::Type *ElemTy = StrTy->getElementType(i);
9128         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9129         switch (ElemTy->getTypeID()) {
9130         case llvm::Type::StructTyID:
9131           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9132           break;
9133         case llvm::Type::FloatTyID:
9134           addFloat(ElemOffset, ElemTy, 32);
9135           break;
9136         case llvm::Type::DoubleTyID:
9137           addFloat(ElemOffset, ElemTy, 64);
9138           break;
9139         case llvm::Type::FP128TyID:
9140           addFloat(ElemOffset, ElemTy, 128);
9141           break;
9142         case llvm::Type::PointerTyID:
9143           if (ElemOffset % 64 == 0) {
9144             pad(ElemOffset);
9145             Elems.push_back(ElemTy);
9146             Size += 64;
9147           }
9148           break;
9149         default:
9150           break;
9151         }
9152       }
9153     }
9154 
9155     // Check if Ty is a usable substitute for the coercion type.
9156     bool isUsableType(llvm::StructType *Ty) const {
9157       return llvm::makeArrayRef(Elems) == Ty->elements();
9158     }
9159 
9160     // Get the coercion type as a literal struct type.
9161     llvm::Type *getType() const {
9162       if (Elems.size() == 1)
9163         return Elems.front();
9164       else
9165         return llvm::StructType::get(Context, Elems);
9166     }
9167   };
9168 };
9169 } // end anonymous namespace
9170 
9171 ABIArgInfo
9172 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9173   if (Ty->isVoidType())
9174     return ABIArgInfo::getIgnore();
9175 
9176   uint64_t Size = getContext().getTypeSize(Ty);
9177 
9178   // Anything too big to fit in registers is passed with an explicit indirect
9179   // pointer / sret pointer.
9180   if (Size > SizeLimit)
9181     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9182 
9183   // Treat an enum type as its underlying type.
9184   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9185     Ty = EnumTy->getDecl()->getIntegerType();
9186 
9187   // Integer types smaller than a register are extended.
9188   if (Size < 64 && Ty->isIntegerType())
9189     return ABIArgInfo::getExtend(Ty);
9190 
9191   if (const auto *EIT = Ty->getAs<ExtIntType>())
9192     if (EIT->getNumBits() < 64)
9193       return ABIArgInfo::getExtend(Ty);
9194 
9195   // Other non-aggregates go in registers.
9196   if (!isAggregateTypeForABI(Ty))
9197     return ABIArgInfo::getDirect();
9198 
9199   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9200   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9201   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9202     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9203 
9204   // This is a small aggregate type that should be passed in registers.
9205   // Build a coercion type from the LLVM struct type.
9206   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9207   if (!StrTy)
9208     return ABIArgInfo::getDirect();
9209 
9210   CoerceBuilder CB(getVMContext(), getDataLayout());
9211   CB.addStruct(0, StrTy);
9212   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9213 
9214   // Try to use the original type for coercion.
9215   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9216 
9217   if (CB.InReg)
9218     return ABIArgInfo::getDirectInReg(CoerceTy);
9219   else
9220     return ABIArgInfo::getDirect(CoerceTy);
9221 }
9222 
9223 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9224                                   QualType Ty) const {
9225   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9226   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9227   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9228     AI.setCoerceToType(ArgTy);
9229 
9230   CharUnits SlotSize = CharUnits::fromQuantity(8);
9231 
9232   CGBuilderTy &Builder = CGF.Builder;
9233   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9234   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9235 
9236   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9237 
9238   Address ArgAddr = Address::invalid();
9239   CharUnits Stride;
9240   switch (AI.getKind()) {
9241   case ABIArgInfo::Expand:
9242   case ABIArgInfo::CoerceAndExpand:
9243   case ABIArgInfo::InAlloca:
9244     llvm_unreachable("Unsupported ABI kind for va_arg");
9245 
9246   case ABIArgInfo::Extend: {
9247     Stride = SlotSize;
9248     CharUnits Offset = SlotSize - TypeInfo.first;
9249     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9250     break;
9251   }
9252 
9253   case ABIArgInfo::Direct: {
9254     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9255     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9256     ArgAddr = Addr;
9257     break;
9258   }
9259 
9260   case ABIArgInfo::Indirect:
9261     Stride = SlotSize;
9262     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9263     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9264                       TypeInfo.second);
9265     break;
9266 
9267   case ABIArgInfo::Ignore:
9268     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
9269   }
9270 
9271   // Update VAList.
9272   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9273   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9274 
9275   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9276 }
9277 
9278 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9279   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9280   for (auto &I : FI.arguments())
9281     I.info = classifyType(I.type, 16 * 8);
9282 }
9283 
9284 namespace {
9285 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9286 public:
9287   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9288       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9289 
9290   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9291     return 14;
9292   }
9293 
9294   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9295                                llvm::Value *Address) const override;
9296 };
9297 } // end anonymous namespace
9298 
9299 bool
9300 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9301                                                 llvm::Value *Address) const {
9302   // This is calculated from the LLVM and GCC tables and verified
9303   // against gcc output.  AFAIK all ABIs use the same encoding.
9304 
9305   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9306 
9307   llvm::IntegerType *i8 = CGF.Int8Ty;
9308   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9309   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9310 
9311   // 0-31: the 8-byte general-purpose registers
9312   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9313 
9314   // 32-63: f0-31, the 4-byte floating-point registers
9315   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9316 
9317   //   Y   = 64
9318   //   PSR = 65
9319   //   WIM = 66
9320   //   TBR = 67
9321   //   PC  = 68
9322   //   NPC = 69
9323   //   FSR = 70
9324   //   CSR = 71
9325   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9326 
9327   // 72-87: d0-15, the 8-byte floating-point registers
9328   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9329 
9330   return false;
9331 }
9332 
9333 // ARC ABI implementation.
9334 namespace {
9335 
9336 class ARCABIInfo : public DefaultABIInfo {
9337 public:
9338   using DefaultABIInfo::DefaultABIInfo;
9339 
9340 private:
9341   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9342                     QualType Ty) const override;
9343 
9344   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9345     if (!State.FreeRegs)
9346       return;
9347     if (Info.isIndirect() && Info.getInReg())
9348       State.FreeRegs--;
9349     else if (Info.isDirect() && Info.getInReg()) {
9350       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9351       if (sz < State.FreeRegs)
9352         State.FreeRegs -= sz;
9353       else
9354         State.FreeRegs = 0;
9355     }
9356   }
9357 
9358   void computeInfo(CGFunctionInfo &FI) const override {
9359     CCState State(FI);
9360     // ARC uses 8 registers to pass arguments.
9361     State.FreeRegs = 8;
9362 
9363     if (!getCXXABI().classifyReturnType(FI))
9364       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9365     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9366     for (auto &I : FI.arguments()) {
9367       I.info = classifyArgumentType(I.type, State.FreeRegs);
9368       updateState(I.info, I.type, State);
9369     }
9370   }
9371 
9372   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9373   ABIArgInfo getIndirectByValue(QualType Ty) const;
9374   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9375   ABIArgInfo classifyReturnType(QualType RetTy) const;
9376 };
9377 
9378 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9379 public:
9380   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9381       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9382 };
9383 
9384 
9385 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9386   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9387                        getNaturalAlignIndirect(Ty, false);
9388 }
9389 
9390 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9391   // Compute the byval alignment.
9392   const unsigned MinABIStackAlignInBytes = 4;
9393   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9394   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9395                                  TypeAlign > MinABIStackAlignInBytes);
9396 }
9397 
9398 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9399                               QualType Ty) const {
9400   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9401                           getContext().getTypeInfoInChars(Ty),
9402                           CharUnits::fromQuantity(4), true);
9403 }
9404 
9405 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9406                                             uint8_t FreeRegs) const {
9407   // Handle the generic C++ ABI.
9408   const RecordType *RT = Ty->getAs<RecordType>();
9409   if (RT) {
9410     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9411     if (RAA == CGCXXABI::RAA_Indirect)
9412       return getIndirectByRef(Ty, FreeRegs > 0);
9413 
9414     if (RAA == CGCXXABI::RAA_DirectInMemory)
9415       return getIndirectByValue(Ty);
9416   }
9417 
9418   // Treat an enum type as its underlying type.
9419   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9420     Ty = EnumTy->getDecl()->getIntegerType();
9421 
9422   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9423 
9424   if (isAggregateTypeForABI(Ty)) {
9425     // Structures with flexible arrays are always indirect.
9426     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9427       return getIndirectByValue(Ty);
9428 
9429     // Ignore empty structs/unions.
9430     if (isEmptyRecord(getContext(), Ty, true))
9431       return ABIArgInfo::getIgnore();
9432 
9433     llvm::LLVMContext &LLVMContext = getVMContext();
9434 
9435     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9436     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9437     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9438 
9439     return FreeRegs >= SizeInRegs ?
9440         ABIArgInfo::getDirectInReg(Result) :
9441         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9442   }
9443 
9444   if (const auto *EIT = Ty->getAs<ExtIntType>())
9445     if (EIT->getNumBits() > 64)
9446       return getIndirectByValue(Ty);
9447 
9448   return isPromotableIntegerTypeForABI(Ty)
9449              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9450                                        : ABIArgInfo::getExtend(Ty))
9451              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9452                                        : ABIArgInfo::getDirect());
9453 }
9454 
9455 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9456   if (RetTy->isAnyComplexType())
9457     return ABIArgInfo::getDirectInReg();
9458 
9459   // Arguments of size > 4 registers are indirect.
9460   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9461   if (RetSize > 4)
9462     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9463 
9464   return DefaultABIInfo::classifyReturnType(RetTy);
9465 }
9466 
9467 } // End anonymous namespace.
9468 
9469 //===----------------------------------------------------------------------===//
9470 // XCore ABI Implementation
9471 //===----------------------------------------------------------------------===//
9472 
9473 namespace {
9474 
9475 /// A SmallStringEnc instance is used to build up the TypeString by passing
9476 /// it by reference between functions that append to it.
9477 typedef llvm::SmallString<128> SmallStringEnc;
9478 
9479 /// TypeStringCache caches the meta encodings of Types.
9480 ///
9481 /// The reason for caching TypeStrings is two fold:
9482 ///   1. To cache a type's encoding for later uses;
9483 ///   2. As a means to break recursive member type inclusion.
9484 ///
9485 /// A cache Entry can have a Status of:
9486 ///   NonRecursive:   The type encoding is not recursive;
9487 ///   Recursive:      The type encoding is recursive;
9488 ///   Incomplete:     An incomplete TypeString;
9489 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9490 ///                   Recursive type encoding.
9491 ///
9492 /// A NonRecursive entry will have all of its sub-members expanded as fully
9493 /// as possible. Whilst it may contain types which are recursive, the type
9494 /// itself is not recursive and thus its encoding may be safely used whenever
9495 /// the type is encountered.
9496 ///
9497 /// A Recursive entry will have all of its sub-members expanded as fully as
9498 /// possible. The type itself is recursive and it may contain other types which
9499 /// are recursive. The Recursive encoding must not be used during the expansion
9500 /// of a recursive type's recursive branch. For simplicity the code uses
9501 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9502 ///
9503 /// An Incomplete entry is always a RecordType and only encodes its
9504 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9505 /// are placed into the cache during type expansion as a means to identify and
9506 /// handle recursive inclusion of types as sub-members. If there is recursion
9507 /// the entry becomes IncompleteUsed.
9508 ///
9509 /// During the expansion of a RecordType's members:
9510 ///
9511 ///   If the cache contains a NonRecursive encoding for the member type, the
9512 ///   cached encoding is used;
9513 ///
9514 ///   If the cache contains a Recursive encoding for the member type, the
9515 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9516 ///
9517 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9518 ///   cache to break potential recursive inclusion of itself as a sub-member;
9519 ///
9520 ///   Once a member RecordType has been expanded, its temporary incomplete
9521 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9522 ///   it is swapped back in;
9523 ///
9524 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9525 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9526 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9527 ///
9528 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9529 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9530 ///   Else the member is part of a recursive type and thus the recursion has
9531 ///   been exited too soon for the encoding to be correct for the member.
9532 ///
9533 class TypeStringCache {
9534   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9535   struct Entry {
9536     std::string Str;     // The encoded TypeString for the type.
9537     enum Status State;   // Information about the encoding in 'Str'.
9538     std::string Swapped; // A temporary place holder for a Recursive encoding
9539                          // during the expansion of RecordType's members.
9540   };
9541   std::map<const IdentifierInfo *, struct Entry> Map;
9542   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9543   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9544 public:
9545   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9546   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9547   bool removeIncomplete(const IdentifierInfo *ID);
9548   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9549                      bool IsRecursive);
9550   StringRef lookupStr(const IdentifierInfo *ID);
9551 };
9552 
9553 /// TypeString encodings for enum & union fields must be order.
9554 /// FieldEncoding is a helper for this ordering process.
9555 class FieldEncoding {
9556   bool HasName;
9557   std::string Enc;
9558 public:
9559   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9560   StringRef str() { return Enc; }
9561   bool operator<(const FieldEncoding &rhs) const {
9562     if (HasName != rhs.HasName) return HasName;
9563     return Enc < rhs.Enc;
9564   }
9565 };
9566 
9567 class XCoreABIInfo : public DefaultABIInfo {
9568 public:
9569   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9570   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9571                     QualType Ty) const override;
9572 };
9573 
9574 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9575   mutable TypeStringCache TSC;
9576 public:
9577   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9578       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9579   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9580                     CodeGen::CodeGenModule &M) const override;
9581 };
9582 
9583 } // End anonymous namespace.
9584 
9585 // TODO: this implementation is likely now redundant with the default
9586 // EmitVAArg.
9587 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9588                                 QualType Ty) const {
9589   CGBuilderTy &Builder = CGF.Builder;
9590 
9591   // Get the VAList.
9592   CharUnits SlotSize = CharUnits::fromQuantity(4);
9593   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9594 
9595   // Handle the argument.
9596   ABIArgInfo AI = classifyArgumentType(Ty);
9597   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9598   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9599   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9600     AI.setCoerceToType(ArgTy);
9601   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9602 
9603   Address Val = Address::invalid();
9604   CharUnits ArgSize = CharUnits::Zero();
9605   switch (AI.getKind()) {
9606   case ABIArgInfo::Expand:
9607   case ABIArgInfo::CoerceAndExpand:
9608   case ABIArgInfo::InAlloca:
9609     llvm_unreachable("Unsupported ABI kind for va_arg");
9610   case ABIArgInfo::Ignore:
9611     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9612     ArgSize = CharUnits::Zero();
9613     break;
9614   case ABIArgInfo::Extend:
9615   case ABIArgInfo::Direct:
9616     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9617     ArgSize = CharUnits::fromQuantity(
9618                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9619     ArgSize = ArgSize.alignTo(SlotSize);
9620     break;
9621   case ABIArgInfo::Indirect:
9622     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9623     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9624     ArgSize = SlotSize;
9625     break;
9626   }
9627 
9628   // Increment the VAList.
9629   if (!ArgSize.isZero()) {
9630     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9631     Builder.CreateStore(APN.getPointer(), VAListAddr);
9632   }
9633 
9634   return Val;
9635 }
9636 
9637 /// During the expansion of a RecordType, an incomplete TypeString is placed
9638 /// into the cache as a means to identify and break recursion.
9639 /// If there is a Recursive encoding in the cache, it is swapped out and will
9640 /// be reinserted by removeIncomplete().
9641 /// All other types of encoding should have been used rather than arriving here.
9642 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9643                                     std::string StubEnc) {
9644   if (!ID)
9645     return;
9646   Entry &E = Map[ID];
9647   assert( (E.Str.empty() || E.State == Recursive) &&
9648          "Incorrectly use of addIncomplete");
9649   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9650   E.Swapped.swap(E.Str); // swap out the Recursive
9651   E.Str.swap(StubEnc);
9652   E.State = Incomplete;
9653   ++IncompleteCount;
9654 }
9655 
9656 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9657 /// must be removed from the cache.
9658 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9659 /// Returns true if the RecordType was defined recursively.
9660 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9661   if (!ID)
9662     return false;
9663   auto I = Map.find(ID);
9664   assert(I != Map.end() && "Entry not present");
9665   Entry &E = I->second;
9666   assert( (E.State == Incomplete ||
9667            E.State == IncompleteUsed) &&
9668          "Entry must be an incomplete type");
9669   bool IsRecursive = false;
9670   if (E.State == IncompleteUsed) {
9671     // We made use of our Incomplete encoding, thus we are recursive.
9672     IsRecursive = true;
9673     --IncompleteUsedCount;
9674   }
9675   if (E.Swapped.empty())
9676     Map.erase(I);
9677   else {
9678     // Swap the Recursive back.
9679     E.Swapped.swap(E.Str);
9680     E.Swapped.clear();
9681     E.State = Recursive;
9682   }
9683   --IncompleteCount;
9684   return IsRecursive;
9685 }
9686 
9687 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9688 /// Recursive (viz: all sub-members were expanded as fully as possible).
9689 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9690                                     bool IsRecursive) {
9691   if (!ID || IncompleteUsedCount)
9692     return; // No key or it is is an incomplete sub-type so don't add.
9693   Entry &E = Map[ID];
9694   if (IsRecursive && !E.Str.empty()) {
9695     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9696            "This is not the same Recursive entry");
9697     // The parent container was not recursive after all, so we could have used
9698     // this Recursive sub-member entry after all, but we assumed the worse when
9699     // we started viz: IncompleteCount!=0.
9700     return;
9701   }
9702   assert(E.Str.empty() && "Entry already present");
9703   E.Str = Str.str();
9704   E.State = IsRecursive? Recursive : NonRecursive;
9705 }
9706 
9707 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9708 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9709 /// encoding is Recursive, return an empty StringRef.
9710 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9711   if (!ID)
9712     return StringRef();   // We have no key.
9713   auto I = Map.find(ID);
9714   if (I == Map.end())
9715     return StringRef();   // We have no encoding.
9716   Entry &E = I->second;
9717   if (E.State == Recursive && IncompleteCount)
9718     return StringRef();   // We don't use Recursive encodings for member types.
9719 
9720   if (E.State == Incomplete) {
9721     // The incomplete type is being used to break out of recursion.
9722     E.State = IncompleteUsed;
9723     ++IncompleteUsedCount;
9724   }
9725   return E.Str;
9726 }
9727 
9728 /// The XCore ABI includes a type information section that communicates symbol
9729 /// type information to the linker. The linker uses this information to verify
9730 /// safety/correctness of things such as array bound and pointers et al.
9731 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9732 /// This type information (TypeString) is emitted into meta data for all global
9733 /// symbols: definitions, declarations, functions & variables.
9734 ///
9735 /// The TypeString carries type, qualifier, name, size & value details.
9736 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9737 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9738 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9739 ///
9740 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9741                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
9742 
9743 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9744 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9745                                           CodeGen::CodeGenModule &CGM) const {
9746   SmallStringEnc Enc;
9747   if (getTypeString(Enc, D, CGM, TSC)) {
9748     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9749     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9750                                 llvm::MDString::get(Ctx, Enc.str())};
9751     llvm::NamedMDNode *MD =
9752       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9753     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9754   }
9755 }
9756 
9757 //===----------------------------------------------------------------------===//
9758 // SPIR ABI Implementation
9759 //===----------------------------------------------------------------------===//
9760 
9761 namespace {
9762 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9763 public:
9764   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9765       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
9766   unsigned getOpenCLKernelCallingConv() const override;
9767 };
9768 
9769 } // End anonymous namespace.
9770 
9771 namespace clang {
9772 namespace CodeGen {
9773 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9774   DefaultABIInfo SPIRABI(CGM.getTypes());
9775   SPIRABI.computeInfo(FI);
9776 }
9777 }
9778 }
9779 
9780 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9781   return llvm::CallingConv::SPIR_KERNEL;
9782 }
9783 
9784 static bool appendType(SmallStringEnc &Enc, QualType QType,
9785                        const CodeGen::CodeGenModule &CGM,
9786                        TypeStringCache &TSC);
9787 
9788 /// Helper function for appendRecordType().
9789 /// Builds a SmallVector containing the encoded field types in declaration
9790 /// order.
9791 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9792                              const RecordDecl *RD,
9793                              const CodeGen::CodeGenModule &CGM,
9794                              TypeStringCache &TSC) {
9795   for (const auto *Field : RD->fields()) {
9796     SmallStringEnc Enc;
9797     Enc += "m(";
9798     Enc += Field->getName();
9799     Enc += "){";
9800     if (Field->isBitField()) {
9801       Enc += "b(";
9802       llvm::raw_svector_ostream OS(Enc);
9803       OS << Field->getBitWidthValue(CGM.getContext());
9804       Enc += ':';
9805     }
9806     if (!appendType(Enc, Field->getType(), CGM, TSC))
9807       return false;
9808     if (Field->isBitField())
9809       Enc += ')';
9810     Enc += '}';
9811     FE.emplace_back(!Field->getName().empty(), Enc);
9812   }
9813   return true;
9814 }
9815 
9816 /// Appends structure and union types to Enc and adds encoding to cache.
9817 /// Recursively calls appendType (via extractFieldType) for each field.
9818 /// Union types have their fields ordered according to the ABI.
9819 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9820                              const CodeGen::CodeGenModule &CGM,
9821                              TypeStringCache &TSC, const IdentifierInfo *ID) {
9822   // Append the cached TypeString if we have one.
9823   StringRef TypeString = TSC.lookupStr(ID);
9824   if (!TypeString.empty()) {
9825     Enc += TypeString;
9826     return true;
9827   }
9828 
9829   // Start to emit an incomplete TypeString.
9830   size_t Start = Enc.size();
9831   Enc += (RT->isUnionType()? 'u' : 's');
9832   Enc += '(';
9833   if (ID)
9834     Enc += ID->getName();
9835   Enc += "){";
9836 
9837   // We collect all encoded fields and order as necessary.
9838   bool IsRecursive = false;
9839   const RecordDecl *RD = RT->getDecl()->getDefinition();
9840   if (RD && !RD->field_empty()) {
9841     // An incomplete TypeString stub is placed in the cache for this RecordType
9842     // so that recursive calls to this RecordType will use it whilst building a
9843     // complete TypeString for this RecordType.
9844     SmallVector<FieldEncoding, 16> FE;
9845     std::string StubEnc(Enc.substr(Start).str());
9846     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
9847     TSC.addIncomplete(ID, std::move(StubEnc));
9848     if (!extractFieldType(FE, RD, CGM, TSC)) {
9849       (void) TSC.removeIncomplete(ID);
9850       return false;
9851     }
9852     IsRecursive = TSC.removeIncomplete(ID);
9853     // The ABI requires unions to be sorted but not structures.
9854     // See FieldEncoding::operator< for sort algorithm.
9855     if (RT->isUnionType())
9856       llvm::sort(FE);
9857     // We can now complete the TypeString.
9858     unsigned E = FE.size();
9859     for (unsigned I = 0; I != E; ++I) {
9860       if (I)
9861         Enc += ',';
9862       Enc += FE[I].str();
9863     }
9864   }
9865   Enc += '}';
9866   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
9867   return true;
9868 }
9869 
9870 /// Appends enum types to Enc and adds the encoding to the cache.
9871 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
9872                            TypeStringCache &TSC,
9873                            const IdentifierInfo *ID) {
9874   // Append the cached TypeString if we have one.
9875   StringRef TypeString = TSC.lookupStr(ID);
9876   if (!TypeString.empty()) {
9877     Enc += TypeString;
9878     return true;
9879   }
9880 
9881   size_t Start = Enc.size();
9882   Enc += "e(";
9883   if (ID)
9884     Enc += ID->getName();
9885   Enc += "){";
9886 
9887   // We collect all encoded enumerations and order them alphanumerically.
9888   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
9889     SmallVector<FieldEncoding, 16> FE;
9890     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
9891          ++I) {
9892       SmallStringEnc EnumEnc;
9893       EnumEnc += "m(";
9894       EnumEnc += I->getName();
9895       EnumEnc += "){";
9896       I->getInitVal().toString(EnumEnc);
9897       EnumEnc += '}';
9898       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
9899     }
9900     llvm::sort(FE);
9901     unsigned E = FE.size();
9902     for (unsigned I = 0; I != E; ++I) {
9903       if (I)
9904         Enc += ',';
9905       Enc += FE[I].str();
9906     }
9907   }
9908   Enc += '}';
9909   TSC.addIfComplete(ID, Enc.substr(Start), false);
9910   return true;
9911 }
9912 
9913 /// Appends type's qualifier to Enc.
9914 /// This is done prior to appending the type's encoding.
9915 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
9916   // Qualifiers are emitted in alphabetical order.
9917   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
9918   int Lookup = 0;
9919   if (QT.isConstQualified())
9920     Lookup += 1<<0;
9921   if (QT.isRestrictQualified())
9922     Lookup += 1<<1;
9923   if (QT.isVolatileQualified())
9924     Lookup += 1<<2;
9925   Enc += Table[Lookup];
9926 }
9927 
9928 /// Appends built-in types to Enc.
9929 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9930   const char *EncType;
9931   switch (BT->getKind()) {
9932     case BuiltinType::Void:
9933       EncType = "0";
9934       break;
9935     case BuiltinType::Bool:
9936       EncType = "b";
9937       break;
9938     case BuiltinType::Char_U:
9939       EncType = "uc";
9940       break;
9941     case BuiltinType::UChar:
9942       EncType = "uc";
9943       break;
9944     case BuiltinType::SChar:
9945       EncType = "sc";
9946       break;
9947     case BuiltinType::UShort:
9948       EncType = "us";
9949       break;
9950     case BuiltinType::Short:
9951       EncType = "ss";
9952       break;
9953     case BuiltinType::UInt:
9954       EncType = "ui";
9955       break;
9956     case BuiltinType::Int:
9957       EncType = "si";
9958       break;
9959     case BuiltinType::ULong:
9960       EncType = "ul";
9961       break;
9962     case BuiltinType::Long:
9963       EncType = "sl";
9964       break;
9965     case BuiltinType::ULongLong:
9966       EncType = "ull";
9967       break;
9968     case BuiltinType::LongLong:
9969       EncType = "sll";
9970       break;
9971     case BuiltinType::Float:
9972       EncType = "ft";
9973       break;
9974     case BuiltinType::Double:
9975       EncType = "d";
9976       break;
9977     case BuiltinType::LongDouble:
9978       EncType = "ld";
9979       break;
9980     default:
9981       return false;
9982   }
9983   Enc += EncType;
9984   return true;
9985 }
9986 
9987 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
9988 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9989                               const CodeGen::CodeGenModule &CGM,
9990                               TypeStringCache &TSC) {
9991   Enc += "p(";
9992   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9993     return false;
9994   Enc += ')';
9995   return true;
9996 }
9997 
9998 /// Appends array encoding to Enc before calling appendType for the element.
9999 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10000                             const ArrayType *AT,
10001                             const CodeGen::CodeGenModule &CGM,
10002                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10003   if (AT->getSizeModifier() != ArrayType::Normal)
10004     return false;
10005   Enc += "a(";
10006   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10007     CAT->getSize().toStringUnsigned(Enc);
10008   else
10009     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10010   Enc += ':';
10011   // The Qualifiers should be attached to the type rather than the array.
10012   appendQualifier(Enc, QT);
10013   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10014     return false;
10015   Enc += ')';
10016   return true;
10017 }
10018 
10019 /// Appends a function encoding to Enc, calling appendType for the return type
10020 /// and the arguments.
10021 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10022                              const CodeGen::CodeGenModule &CGM,
10023                              TypeStringCache &TSC) {
10024   Enc += "f{";
10025   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10026     return false;
10027   Enc += "}(";
10028   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10029     // N.B. we are only interested in the adjusted param types.
10030     auto I = FPT->param_type_begin();
10031     auto E = FPT->param_type_end();
10032     if (I != E) {
10033       do {
10034         if (!appendType(Enc, *I, CGM, TSC))
10035           return false;
10036         ++I;
10037         if (I != E)
10038           Enc += ',';
10039       } while (I != E);
10040       if (FPT->isVariadic())
10041         Enc += ",va";
10042     } else {
10043       if (FPT->isVariadic())
10044         Enc += "va";
10045       else
10046         Enc += '0';
10047     }
10048   }
10049   Enc += ')';
10050   return true;
10051 }
10052 
10053 /// Handles the type's qualifier before dispatching a call to handle specific
10054 /// type encodings.
10055 static bool appendType(SmallStringEnc &Enc, QualType QType,
10056                        const CodeGen::CodeGenModule &CGM,
10057                        TypeStringCache &TSC) {
10058 
10059   QualType QT = QType.getCanonicalType();
10060 
10061   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10062     // The Qualifiers should be attached to the type rather than the array.
10063     // Thus we don't call appendQualifier() here.
10064     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10065 
10066   appendQualifier(Enc, QT);
10067 
10068   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10069     return appendBuiltinType(Enc, BT);
10070 
10071   if (const PointerType *PT = QT->getAs<PointerType>())
10072     return appendPointerType(Enc, PT, CGM, TSC);
10073 
10074   if (const EnumType *ET = QT->getAs<EnumType>())
10075     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10076 
10077   if (const RecordType *RT = QT->getAsStructureType())
10078     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10079 
10080   if (const RecordType *RT = QT->getAsUnionType())
10081     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10082 
10083   if (const FunctionType *FT = QT->getAs<FunctionType>())
10084     return appendFunctionType(Enc, FT, CGM, TSC);
10085 
10086   return false;
10087 }
10088 
10089 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10090                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
10091   if (!D)
10092     return false;
10093 
10094   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10095     if (FD->getLanguageLinkage() != CLanguageLinkage)
10096       return false;
10097     return appendType(Enc, FD->getType(), CGM, TSC);
10098   }
10099 
10100   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10101     if (VD->getLanguageLinkage() != CLanguageLinkage)
10102       return false;
10103     QualType QT = VD->getType().getCanonicalType();
10104     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10105       // Global ArrayTypes are given a size of '*' if the size is unknown.
10106       // The Qualifiers should be attached to the type rather than the array.
10107       // Thus we don't call appendQualifier() here.
10108       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10109     }
10110     return appendType(Enc, QT, CGM, TSC);
10111   }
10112   return false;
10113 }
10114 
10115 //===----------------------------------------------------------------------===//
10116 // RISCV ABI Implementation
10117 //===----------------------------------------------------------------------===//
10118 
10119 namespace {
10120 class RISCVABIInfo : public DefaultABIInfo {
10121 private:
10122   // Size of the integer ('x') registers in bits.
10123   unsigned XLen;
10124   // Size of the floating point ('f') registers in bits. Note that the target
10125   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10126   // with soft float ABI has FLen==0).
10127   unsigned FLen;
10128   static const int NumArgGPRs = 8;
10129   static const int NumArgFPRs = 8;
10130   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10131                                       llvm::Type *&Field1Ty,
10132                                       CharUnits &Field1Off,
10133                                       llvm::Type *&Field2Ty,
10134                                       CharUnits &Field2Off) const;
10135 
10136 public:
10137   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10138       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10139 
10140   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10141   // non-virtual, but computeInfo is virtual, so we overload it.
10142   void computeInfo(CGFunctionInfo &FI) const override;
10143 
10144   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10145                                   int &ArgFPRsLeft) const;
10146   ABIArgInfo classifyReturnType(QualType RetTy) const;
10147 
10148   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10149                     QualType Ty) const override;
10150 
10151   ABIArgInfo extendType(QualType Ty) const;
10152 
10153   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10154                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10155                                 CharUnits &Field2Off, int &NeededArgGPRs,
10156                                 int &NeededArgFPRs) const;
10157   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10158                                                CharUnits Field1Off,
10159                                                llvm::Type *Field2Ty,
10160                                                CharUnits Field2Off) const;
10161 };
10162 } // end anonymous namespace
10163 
10164 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10165   QualType RetTy = FI.getReturnType();
10166   if (!getCXXABI().classifyReturnType(FI))
10167     FI.getReturnInfo() = classifyReturnType(RetTy);
10168 
10169   // IsRetIndirect is true if classifyArgumentType indicated the value should
10170   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10171   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10172   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10173   // list and pass indirectly on RV32.
10174   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10175   if (!IsRetIndirect && RetTy->isScalarType() &&
10176       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10177     if (RetTy->isComplexType() && FLen) {
10178       QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
10179       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10180     } else {
10181       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10182       IsRetIndirect = true;
10183     }
10184   }
10185 
10186   // We must track the number of GPRs used in order to conform to the RISC-V
10187   // ABI, as integer scalars passed in registers should have signext/zeroext
10188   // when promoted, but are anyext if passed on the stack. As GPR usage is
10189   // different for variadic arguments, we must also track whether we are
10190   // examining a vararg or not.
10191   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10192   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10193   int NumFixedArgs = FI.getNumRequiredArgs();
10194 
10195   int ArgNum = 0;
10196   for (auto &ArgInfo : FI.arguments()) {
10197     bool IsFixed = ArgNum < NumFixedArgs;
10198     ArgInfo.info =
10199         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10200     ArgNum++;
10201   }
10202 }
10203 
10204 // Returns true if the struct is a potential candidate for the floating point
10205 // calling convention. If this function returns true, the caller is
10206 // responsible for checking that if there is only a single field then that
10207 // field is a float.
10208 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10209                                                   llvm::Type *&Field1Ty,
10210                                                   CharUnits &Field1Off,
10211                                                   llvm::Type *&Field2Ty,
10212                                                   CharUnits &Field2Off) const {
10213   bool IsInt = Ty->isIntegralOrEnumerationType();
10214   bool IsFloat = Ty->isRealFloatingType();
10215 
10216   if (IsInt || IsFloat) {
10217     uint64_t Size = getContext().getTypeSize(Ty);
10218     if (IsInt && Size > XLen)
10219       return false;
10220     // Can't be eligible if larger than the FP registers. Half precision isn't
10221     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10222     // default to the integer ABI in that case.
10223     if (IsFloat && (Size > FLen || Size < 32))
10224       return false;
10225     // Can't be eligible if an integer type was already found (int+int pairs
10226     // are not eligible).
10227     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10228       return false;
10229     if (!Field1Ty) {
10230       Field1Ty = CGT.ConvertType(Ty);
10231       Field1Off = CurOff;
10232       return true;
10233     }
10234     if (!Field2Ty) {
10235       Field2Ty = CGT.ConvertType(Ty);
10236       Field2Off = CurOff;
10237       return true;
10238     }
10239     return false;
10240   }
10241 
10242   if (auto CTy = Ty->getAs<ComplexType>()) {
10243     if (Field1Ty)
10244       return false;
10245     QualType EltTy = CTy->getElementType();
10246     if (getContext().getTypeSize(EltTy) > FLen)
10247       return false;
10248     Field1Ty = CGT.ConvertType(EltTy);
10249     Field1Off = CurOff;
10250     assert(CurOff.isZero() && "Unexpected offset for first field");
10251     Field2Ty = Field1Ty;
10252     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10253     return true;
10254   }
10255 
10256   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10257     uint64_t ArraySize = ATy->getSize().getZExtValue();
10258     QualType EltTy = ATy->getElementType();
10259     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10260     for (uint64_t i = 0; i < ArraySize; ++i) {
10261       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10262                                                 Field1Off, Field2Ty, Field2Off);
10263       if (!Ret)
10264         return false;
10265       CurOff += EltSize;
10266     }
10267     return true;
10268   }
10269 
10270   if (const auto *RTy = Ty->getAs<RecordType>()) {
10271     // Structures with either a non-trivial destructor or a non-trivial
10272     // copy constructor are not eligible for the FP calling convention.
10273     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10274       return false;
10275     if (isEmptyRecord(getContext(), Ty, true))
10276       return true;
10277     const RecordDecl *RD = RTy->getDecl();
10278     // Unions aren't eligible unless they're empty (which is caught above).
10279     if (RD->isUnion())
10280       return false;
10281     int ZeroWidthBitFieldCount = 0;
10282     for (const FieldDecl *FD : RD->fields()) {
10283       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10284       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10285       QualType QTy = FD->getType();
10286       if (FD->isBitField()) {
10287         unsigned BitWidth = FD->getBitWidthValue(getContext());
10288         // Allow a bitfield with a type greater than XLen as long as the
10289         // bitwidth is XLen or less.
10290         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10291           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10292         if (BitWidth == 0) {
10293           ZeroWidthBitFieldCount++;
10294           continue;
10295         }
10296       }
10297 
10298       bool Ret = detectFPCCEligibleStructHelper(
10299           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10300           Field1Ty, Field1Off, Field2Ty, Field2Off);
10301       if (!Ret)
10302         return false;
10303 
10304       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10305       // or int+fp structs, but are ignored for a struct with an fp field and
10306       // any number of zero-width bitfields.
10307       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10308         return false;
10309     }
10310     return Field1Ty != nullptr;
10311   }
10312 
10313   return false;
10314 }
10315 
10316 // Determine if a struct is eligible for passing according to the floating
10317 // point calling convention (i.e., when flattened it contains a single fp
10318 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10319 // NeededArgGPRs are incremented appropriately.
10320 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10321                                             CharUnits &Field1Off,
10322                                             llvm::Type *&Field2Ty,
10323                                             CharUnits &Field2Off,
10324                                             int &NeededArgGPRs,
10325                                             int &NeededArgFPRs) const {
10326   Field1Ty = nullptr;
10327   Field2Ty = nullptr;
10328   NeededArgGPRs = 0;
10329   NeededArgFPRs = 0;
10330   bool IsCandidate = detectFPCCEligibleStructHelper(
10331       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10332   // Not really a candidate if we have a single int but no float.
10333   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10334     return false;
10335   if (!IsCandidate)
10336     return false;
10337   if (Field1Ty && Field1Ty->isFloatingPointTy())
10338     NeededArgFPRs++;
10339   else if (Field1Ty)
10340     NeededArgGPRs++;
10341   if (Field2Ty && Field2Ty->isFloatingPointTy())
10342     NeededArgFPRs++;
10343   else if (Field2Ty)
10344     NeededArgGPRs++;
10345   return IsCandidate;
10346 }
10347 
10348 // Call getCoerceAndExpand for the two-element flattened struct described by
10349 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10350 // appropriate coerceToType and unpaddedCoerceToType.
10351 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10352     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10353     CharUnits Field2Off) const {
10354   SmallVector<llvm::Type *, 3> CoerceElts;
10355   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10356   if (!Field1Off.isZero())
10357     CoerceElts.push_back(llvm::ArrayType::get(
10358         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10359 
10360   CoerceElts.push_back(Field1Ty);
10361   UnpaddedCoerceElts.push_back(Field1Ty);
10362 
10363   if (!Field2Ty) {
10364     return ABIArgInfo::getCoerceAndExpand(
10365         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10366         UnpaddedCoerceElts[0]);
10367   }
10368 
10369   CharUnits Field2Align =
10370       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10371   CharUnits Field1Size =
10372       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10373   CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
10374 
10375   CharUnits Padding = CharUnits::Zero();
10376   if (Field2Off > Field2OffNoPadNoPack)
10377     Padding = Field2Off - Field2OffNoPadNoPack;
10378   else if (Field2Off != Field2Align && Field2Off > Field1Size)
10379     Padding = Field2Off - Field1Size;
10380 
10381   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10382 
10383   if (!Padding.isZero())
10384     CoerceElts.push_back(llvm::ArrayType::get(
10385         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10386 
10387   CoerceElts.push_back(Field2Ty);
10388   UnpaddedCoerceElts.push_back(Field2Ty);
10389 
10390   auto CoerceToType =
10391       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10392   auto UnpaddedCoerceToType =
10393       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10394 
10395   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10396 }
10397 
10398 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10399                                               int &ArgGPRsLeft,
10400                                               int &ArgFPRsLeft) const {
10401   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10402   Ty = useFirstFieldIfTransparentUnion(Ty);
10403 
10404   // Structures with either a non-trivial destructor or a non-trivial
10405   // copy constructor are always passed indirectly.
10406   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10407     if (ArgGPRsLeft)
10408       ArgGPRsLeft -= 1;
10409     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10410                                            CGCXXABI::RAA_DirectInMemory);
10411   }
10412 
10413   // Ignore empty structs/unions.
10414   if (isEmptyRecord(getContext(), Ty, true))
10415     return ABIArgInfo::getIgnore();
10416 
10417   uint64_t Size = getContext().getTypeSize(Ty);
10418 
10419   // Pass floating point values via FPRs if possible.
10420   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10421       FLen >= Size && ArgFPRsLeft) {
10422     ArgFPRsLeft--;
10423     return ABIArgInfo::getDirect();
10424   }
10425 
10426   // Complex types for the hard float ABI must be passed direct rather than
10427   // using CoerceAndExpand.
10428   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10429     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10430     if (getContext().getTypeSize(EltTy) <= FLen) {
10431       ArgFPRsLeft -= 2;
10432       return ABIArgInfo::getDirect();
10433     }
10434   }
10435 
10436   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10437     llvm::Type *Field1Ty = nullptr;
10438     llvm::Type *Field2Ty = nullptr;
10439     CharUnits Field1Off = CharUnits::Zero();
10440     CharUnits Field2Off = CharUnits::Zero();
10441     int NeededArgGPRs;
10442     int NeededArgFPRs;
10443     bool IsCandidate =
10444         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10445                                  NeededArgGPRs, NeededArgFPRs);
10446     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10447         NeededArgFPRs <= ArgFPRsLeft) {
10448       ArgGPRsLeft -= NeededArgGPRs;
10449       ArgFPRsLeft -= NeededArgFPRs;
10450       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10451                                                Field2Off);
10452     }
10453   }
10454 
10455   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10456   bool MustUseStack = false;
10457   // Determine the number of GPRs needed to pass the current argument
10458   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10459   // register pairs, so may consume 3 registers.
10460   int NeededArgGPRs = 1;
10461   if (!IsFixed && NeededAlign == 2 * XLen)
10462     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10463   else if (Size > XLen && Size <= 2 * XLen)
10464     NeededArgGPRs = 2;
10465 
10466   if (NeededArgGPRs > ArgGPRsLeft) {
10467     MustUseStack = true;
10468     NeededArgGPRs = ArgGPRsLeft;
10469   }
10470 
10471   ArgGPRsLeft -= NeededArgGPRs;
10472 
10473   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10474     // Treat an enum type as its underlying type.
10475     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10476       Ty = EnumTy->getDecl()->getIntegerType();
10477 
10478     // All integral types are promoted to XLen width, unless passed on the
10479     // stack.
10480     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10481       return extendType(Ty);
10482     }
10483 
10484     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10485       if (EIT->getNumBits() < XLen && !MustUseStack)
10486         return extendType(Ty);
10487       if (EIT->getNumBits() > 128 ||
10488           (!getContext().getTargetInfo().hasInt128Type() &&
10489            EIT->getNumBits() > 64))
10490         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10491     }
10492 
10493     return ABIArgInfo::getDirect();
10494   }
10495 
10496   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10497   // so coerce to integers.
10498   if (Size <= 2 * XLen) {
10499     unsigned Alignment = getContext().getTypeAlign(Ty);
10500 
10501     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10502     // required, and a 2-element XLen array if only XLen alignment is required.
10503     if (Size <= XLen) {
10504       return ABIArgInfo::getDirect(
10505           llvm::IntegerType::get(getVMContext(), XLen));
10506     } else if (Alignment == 2 * XLen) {
10507       return ABIArgInfo::getDirect(
10508           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10509     } else {
10510       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10511           llvm::IntegerType::get(getVMContext(), XLen), 2));
10512     }
10513   }
10514   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10515 }
10516 
10517 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10518   if (RetTy->isVoidType())
10519     return ABIArgInfo::getIgnore();
10520 
10521   int ArgGPRsLeft = 2;
10522   int ArgFPRsLeft = FLen ? 2 : 0;
10523 
10524   // The rules for return and argument types are the same, so defer to
10525   // classifyArgumentType.
10526   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10527                               ArgFPRsLeft);
10528 }
10529 
10530 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10531                                 QualType Ty) const {
10532   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10533 
10534   // Empty records are ignored for parameter passing purposes.
10535   if (isEmptyRecord(getContext(), Ty, true)) {
10536     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10537     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10538     return Addr;
10539   }
10540 
10541   std::pair<CharUnits, CharUnits> SizeAndAlign =
10542       getContext().getTypeInfoInChars(Ty);
10543 
10544   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10545   bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
10546 
10547   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
10548                           SlotSize, /*AllowHigherAlign=*/true);
10549 }
10550 
10551 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10552   int TySize = getContext().getTypeSize(Ty);
10553   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10554   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10555     return ABIArgInfo::getSignExtend(Ty);
10556   return ABIArgInfo::getExtend(Ty);
10557 }
10558 
10559 namespace {
10560 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10561 public:
10562   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10563                          unsigned FLen)
10564       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10565 
10566   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10567                            CodeGen::CodeGenModule &CGM) const override {
10568     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10569     if (!FD) return;
10570 
10571     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10572     if (!Attr)
10573       return;
10574 
10575     const char *Kind;
10576     switch (Attr->getInterrupt()) {
10577     case RISCVInterruptAttr::user: Kind = "user"; break;
10578     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10579     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10580     }
10581 
10582     auto *Fn = cast<llvm::Function>(GV);
10583 
10584     Fn->addFnAttr("interrupt", Kind);
10585   }
10586 };
10587 } // namespace
10588 
10589 //===----------------------------------------------------------------------===//
10590 // Driver code
10591 //===----------------------------------------------------------------------===//
10592 
10593 bool CodeGenModule::supportsCOMDAT() const {
10594   return getTriple().supportsCOMDAT();
10595 }
10596 
10597 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10598   if (TheTargetCodeGenInfo)
10599     return *TheTargetCodeGenInfo;
10600 
10601   // Helper to set the unique_ptr while still keeping the return value.
10602   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10603     this->TheTargetCodeGenInfo.reset(P);
10604     return *P;
10605   };
10606 
10607   const llvm::Triple &Triple = getTarget().getTriple();
10608   switch (Triple.getArch()) {
10609   default:
10610     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10611 
10612   case llvm::Triple::le32:
10613     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10614   case llvm::Triple::mips:
10615   case llvm::Triple::mipsel:
10616     if (Triple.getOS() == llvm::Triple::NaCl)
10617       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10618     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10619 
10620   case llvm::Triple::mips64:
10621   case llvm::Triple::mips64el:
10622     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10623 
10624   case llvm::Triple::avr:
10625     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10626 
10627   case llvm::Triple::aarch64:
10628   case llvm::Triple::aarch64_32:
10629   case llvm::Triple::aarch64_be: {
10630     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10631     if (getTarget().getABI() == "darwinpcs")
10632       Kind = AArch64ABIInfo::DarwinPCS;
10633     else if (Triple.isOSWindows())
10634       return SetCGInfo(
10635           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10636 
10637     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10638   }
10639 
10640   case llvm::Triple::wasm32:
10641   case llvm::Triple::wasm64: {
10642     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10643     if (getTarget().getABI() == "experimental-mv")
10644       Kind = WebAssemblyABIInfo::ExperimentalMV;
10645     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10646   }
10647 
10648   case llvm::Triple::arm:
10649   case llvm::Triple::armeb:
10650   case llvm::Triple::thumb:
10651   case llvm::Triple::thumbeb: {
10652     if (Triple.getOS() == llvm::Triple::Win32) {
10653       return SetCGInfo(
10654           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10655     }
10656 
10657     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10658     StringRef ABIStr = getTarget().getABI();
10659     if (ABIStr == "apcs-gnu")
10660       Kind = ARMABIInfo::APCS;
10661     else if (ABIStr == "aapcs16")
10662       Kind = ARMABIInfo::AAPCS16_VFP;
10663     else if (CodeGenOpts.FloatABI == "hard" ||
10664              (CodeGenOpts.FloatABI != "soft" &&
10665               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10666                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10667                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10668       Kind = ARMABIInfo::AAPCS_VFP;
10669 
10670     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10671   }
10672 
10673   case llvm::Triple::ppc: {
10674     if (Triple.isOSAIX())
10675       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10676 
10677     bool IsSoftFloat =
10678         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10679     bool RetSmallStructInRegABI =
10680         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10681     return SetCGInfo(
10682         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10683   }
10684   case llvm::Triple::ppc64:
10685     if (Triple.isOSAIX())
10686       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10687 
10688     if (Triple.isOSBinFormatELF()) {
10689       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10690       if (getTarget().getABI() == "elfv2")
10691         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10692       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10693       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10694 
10695       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10696                                                         IsSoftFloat));
10697     }
10698     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10699   case llvm::Triple::ppc64le: {
10700     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10701     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10702     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
10703       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10704     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10705     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10706 
10707     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10708                                                       IsSoftFloat));
10709   }
10710 
10711   case llvm::Triple::nvptx:
10712   case llvm::Triple::nvptx64:
10713     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10714 
10715   case llvm::Triple::msp430:
10716     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10717 
10718   case llvm::Triple::riscv32:
10719   case llvm::Triple::riscv64: {
10720     StringRef ABIStr = getTarget().getABI();
10721     unsigned XLen = getTarget().getPointerWidth(0);
10722     unsigned ABIFLen = 0;
10723     if (ABIStr.endswith("f"))
10724       ABIFLen = 32;
10725     else if (ABIStr.endswith("d"))
10726       ABIFLen = 64;
10727     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10728   }
10729 
10730   case llvm::Triple::systemz: {
10731     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
10732     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
10733     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
10734   }
10735 
10736   case llvm::Triple::tce:
10737   case llvm::Triple::tcele:
10738     return SetCGInfo(new TCETargetCodeGenInfo(Types));
10739 
10740   case llvm::Triple::x86: {
10741     bool IsDarwinVectorABI = Triple.isOSDarwin();
10742     bool RetSmallStructInRegABI =
10743         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10744     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
10745 
10746     if (Triple.getOS() == llvm::Triple::Win32) {
10747       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
10748           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10749           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
10750     } else {
10751       return SetCGInfo(new X86_32TargetCodeGenInfo(
10752           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10753           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
10754           CodeGenOpts.FloatABI == "soft"));
10755     }
10756   }
10757 
10758   case llvm::Triple::x86_64: {
10759     StringRef ABI = getTarget().getABI();
10760     X86AVXABILevel AVXLevel =
10761         (ABI == "avx512"
10762              ? X86AVXABILevel::AVX512
10763              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
10764 
10765     switch (Triple.getOS()) {
10766     case llvm::Triple::Win32:
10767       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
10768     default:
10769       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
10770     }
10771   }
10772   case llvm::Triple::hexagon:
10773     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
10774   case llvm::Triple::lanai:
10775     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
10776   case llvm::Triple::r600:
10777     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10778   case llvm::Triple::amdgcn:
10779     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10780   case llvm::Triple::sparc:
10781     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
10782   case llvm::Triple::sparcv9:
10783     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
10784   case llvm::Triple::xcore:
10785     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
10786   case llvm::Triple::arc:
10787     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
10788   case llvm::Triple::spir:
10789   case llvm::Triple::spir64:
10790     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
10791   }
10792 }
10793 
10794 /// Create an OpenCL kernel for an enqueued block.
10795 ///
10796 /// The kernel has the same function type as the block invoke function. Its
10797 /// name is the name of the block invoke function postfixed with "_kernel".
10798 /// It simply calls the block invoke function then returns.
10799 llvm::Function *
10800 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
10801                                              llvm::Function *Invoke,
10802                                              llvm::Value *BlockLiteral) const {
10803   auto *InvokeFT = Invoke->getFunctionType();
10804   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10805   for (auto &P : InvokeFT->params())
10806     ArgTys.push_back(P);
10807   auto &C = CGF.getLLVMContext();
10808   std::string Name = Invoke->getName().str() + "_kernel";
10809   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10810   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10811                                    &CGF.CGM.getModule());
10812   auto IP = CGF.Builder.saveIP();
10813   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10814   auto &Builder = CGF.Builder;
10815   Builder.SetInsertPoint(BB);
10816   llvm::SmallVector<llvm::Value *, 2> Args;
10817   for (auto &A : F->args())
10818     Args.push_back(&A);
10819   Builder.CreateCall(Invoke, Args);
10820   Builder.CreateRetVoid();
10821   Builder.restoreIP(IP);
10822   return F;
10823 }
10824 
10825 /// Create an OpenCL kernel for an enqueued block.
10826 ///
10827 /// The type of the first argument (the block literal) is the struct type
10828 /// of the block literal instead of a pointer type. The first argument
10829 /// (block literal) is passed directly by value to the kernel. The kernel
10830 /// allocates the same type of struct on stack and stores the block literal
10831 /// to it and passes its pointer to the block invoke function. The kernel
10832 /// has "enqueued-block" function attribute and kernel argument metadata.
10833 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
10834     CodeGenFunction &CGF, llvm::Function *Invoke,
10835     llvm::Value *BlockLiteral) const {
10836   auto &Builder = CGF.Builder;
10837   auto &C = CGF.getLLVMContext();
10838 
10839   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
10840   auto *InvokeFT = Invoke->getFunctionType();
10841   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10842   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
10843   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
10844   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
10845   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
10846   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
10847   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
10848 
10849   ArgTys.push_back(BlockTy);
10850   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10851   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
10852   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10853   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10854   AccessQuals.push_back(llvm::MDString::get(C, "none"));
10855   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
10856   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
10857     ArgTys.push_back(InvokeFT->getParamType(I));
10858     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
10859     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
10860     AccessQuals.push_back(llvm::MDString::get(C, "none"));
10861     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
10862     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10863     ArgNames.push_back(
10864         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
10865   }
10866   std::string Name = Invoke->getName().str() + "_kernel";
10867   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10868   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10869                                    &CGF.CGM.getModule());
10870   F->addFnAttr("enqueued-block");
10871   auto IP = CGF.Builder.saveIP();
10872   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10873   Builder.SetInsertPoint(BB);
10874   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
10875   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
10876   BlockPtr->setAlignment(BlockAlign);
10877   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
10878   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
10879   llvm::SmallVector<llvm::Value *, 2> Args;
10880   Args.push_back(Cast);
10881   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
10882     Args.push_back(I);
10883   Builder.CreateCall(Invoke, Args);
10884   Builder.CreateRetVoid();
10885   Builder.restoreIP(IP);
10886 
10887   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
10888   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
10889   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
10890   F->setMetadata("kernel_arg_base_type",
10891                  llvm::MDNode::get(C, ArgBaseTypeNames));
10892   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
10893   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
10894     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
10895 
10896   return F;
10897 }
10898