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