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