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