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