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