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