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     llvm::Value *V =
3552       CGF.Builder.CreateDefaultAlignedLoad(
3553                                CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3554     CGF.Builder.CreateStore(V,
3555                     CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3556 
3557     // Copy the second element.
3558     V = CGF.Builder.CreateDefaultAlignedLoad(
3559                                CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3560     CharUnits Offset = CharUnits::fromQuantity(
3561                    getDataLayout().getStructLayout(ST)->getElementOffset(1));
3562     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3563 
3564     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3565   } else if (neededInt) {
3566     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3567                       CharUnits::fromQuantity(8));
3568     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3569 
3570     // Copy to a temporary if necessary to ensure the appropriate alignment.
3571     std::pair<CharUnits, CharUnits> SizeAlign =
3572         getContext().getTypeInfoInChars(Ty);
3573     uint64_t TySize = SizeAlign.first.getQuantity();
3574     CharUnits TyAlign = SizeAlign.second;
3575 
3576     // Copy into a temporary if the type is more aligned than the
3577     // register save area.
3578     if (TyAlign.getQuantity() > 8) {
3579       Address Tmp = CGF.CreateMemTemp(Ty);
3580       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3581       RegAddr = Tmp;
3582     }
3583 
3584   } else if (neededSSE == 1) {
3585     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3586                       CharUnits::fromQuantity(16));
3587     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3588   } else {
3589     assert(neededSSE == 2 && "Invalid number of needed registers!");
3590     // SSE registers are spaced 16 bytes apart in the register save
3591     // area, we need to collect the two eightbytes together.
3592     // The ABI isn't explicit about this, but it seems reasonable
3593     // to assume that the slots are 16-byte aligned, since the stack is
3594     // naturally 16-byte aligned and the prologue is expected to store
3595     // all the SSE registers to the RSA.
3596     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3597                                 CharUnits::fromQuantity(16));
3598     Address RegAddrHi =
3599       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3600                                              CharUnits::fromQuantity(16));
3601     llvm::Type *DoubleTy = CGF.DoubleTy;
3602     llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
3603     llvm::Value *V;
3604     Address Tmp = CGF.CreateMemTemp(Ty);
3605     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3606     V = CGF.Builder.CreateLoad(
3607                    CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3608     CGF.Builder.CreateStore(V,
3609                    CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3610     V = CGF.Builder.CreateLoad(
3611                    CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3612     CGF.Builder.CreateStore(V,
3613           CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3614 
3615     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3616   }
3617 
3618   // AMD64-ABI 3.5.7p5: Step 5. Set:
3619   // l->gp_offset = l->gp_offset + num_gp * 8
3620   // l->fp_offset = l->fp_offset + num_fp * 16.
3621   if (neededInt) {
3622     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3623     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3624                             gp_offset_p);
3625   }
3626   if (neededSSE) {
3627     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3628     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3629                             fp_offset_p);
3630   }
3631   CGF.EmitBranch(ContBlock);
3632 
3633   // Emit code to load the value if it was passed in memory.
3634 
3635   CGF.EmitBlock(InMemBlock);
3636   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3637 
3638   // Return the appropriate result.
3639 
3640   CGF.EmitBlock(ContBlock);
3641   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3642                                  "vaarg.addr");
3643   return ResAddr;
3644 }
3645 
3646 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3647                                    QualType Ty) const {
3648   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3649                           CGF.getContext().getTypeInfoInChars(Ty),
3650                           CharUnits::fromQuantity(8),
3651                           /*allowHigherAlign*/ false);
3652 }
3653 
3654 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3655                                       bool IsReturnType) const {
3656 
3657   if (Ty->isVoidType())
3658     return ABIArgInfo::getIgnore();
3659 
3660   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3661     Ty = EnumTy->getDecl()->getIntegerType();
3662 
3663   TypeInfo Info = getContext().getTypeInfo(Ty);
3664   uint64_t Width = Info.Width;
3665   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3666 
3667   const RecordType *RT = Ty->getAs<RecordType>();
3668   if (RT) {
3669     if (!IsReturnType) {
3670       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3671         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3672     }
3673 
3674     if (RT->getDecl()->hasFlexibleArrayMember())
3675       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3676 
3677   }
3678 
3679   // vectorcall adds the concept of a homogenous vector aggregate, similar to
3680   // other targets.
3681   const Type *Base = nullptr;
3682   uint64_t NumElts = 0;
3683   if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3684     if (FreeSSERegs >= NumElts) {
3685       FreeSSERegs -= NumElts;
3686       if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3687         return ABIArgInfo::getDirect();
3688       return ABIArgInfo::getExpand();
3689     }
3690     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3691   }
3692 
3693 
3694   if (Ty->isMemberPointerType()) {
3695     // If the member pointer is represented by an LLVM int or ptr, pass it
3696     // directly.
3697     llvm::Type *LLTy = CGT.ConvertType(Ty);
3698     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3699       return ABIArgInfo::getDirect();
3700   }
3701 
3702   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3703     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3704     // not 1, 2, 4, or 8 bytes, must be passed by reference."
3705     if (Width > 64 || !llvm::isPowerOf2_64(Width))
3706       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3707 
3708     // Otherwise, coerce it to a small integer.
3709     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3710   }
3711 
3712   // Bool type is always extended to the ABI, other builtin types are not
3713   // extended.
3714   const BuiltinType *BT = Ty->getAs<BuiltinType>();
3715   if (BT && BT->getKind() == BuiltinType::Bool)
3716     return ABIArgInfo::getExtend();
3717 
3718   // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3719   // passes them indirectly through memory.
3720   if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3721     const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3722     if (LDF == &llvm::APFloat::x87DoubleExtended)
3723       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3724   }
3725 
3726   return ABIArgInfo::getDirect();
3727 }
3728 
3729 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3730   bool IsVectorCall =
3731       FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3732   bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3733 
3734   unsigned FreeSSERegs = 0;
3735   if (IsVectorCall) {
3736     // We can use up to 4 SSE return registers with vectorcall.
3737     FreeSSERegs = 4;
3738   } else if (IsRegCall) {
3739     // RegCall gives us 16 SSE registers.
3740     FreeSSERegs = 16;
3741   }
3742 
3743   if (!getCXXABI().classifyReturnType(FI))
3744     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3745 
3746   if (IsVectorCall) {
3747     // We can use up to 6 SSE register parameters with vectorcall.
3748     FreeSSERegs = 6;
3749   } else if (IsRegCall) {
3750     FreeSSERegs = 16;
3751   }
3752 
3753   for (auto &I : FI.arguments())
3754     I.info = classify(I.type, FreeSSERegs, false);
3755 }
3756 
3757 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3758                                     QualType Ty) const {
3759 
3760   bool IsIndirect = false;
3761 
3762   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3763   // not 1, 2, 4, or 8 bytes, must be passed by reference."
3764   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3765     uint64_t Width = getContext().getTypeSize(Ty);
3766     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3767   }
3768 
3769   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3770                           CGF.getContext().getTypeInfoInChars(Ty),
3771                           CharUnits::fromQuantity(8),
3772                           /*allowHigherAlign*/ false);
3773 }
3774 
3775 // PowerPC-32
3776 namespace {
3777 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3778 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
3779 bool IsSoftFloatABI;
3780 public:
3781   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3782       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
3783 
3784   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3785                     QualType Ty) const override;
3786 };
3787 
3788 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3789 public:
3790   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3791       : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
3792 
3793   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3794     // This is recovered from gcc output.
3795     return 1; // r1 is the dedicated stack pointer
3796   }
3797 
3798   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3799                                llvm::Value *Address) const override;
3800 };
3801 
3802 }
3803 
3804 // TODO: this implementation is now likely redundant with
3805 // DefaultABIInfo::EmitVAArg.
3806 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3807                                       QualType Ty) const {
3808   const unsigned OverflowLimit = 8;
3809   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3810     // TODO: Implement this. For now ignore.
3811     (void)CTy;
3812     return Address::invalid(); // FIXME?
3813   }
3814 
3815   // struct __va_list_tag {
3816   //   unsigned char gpr;
3817   //   unsigned char fpr;
3818   //   unsigned short reserved;
3819   //   void *overflow_arg_area;
3820   //   void *reg_save_area;
3821   // };
3822 
3823   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3824   bool isInt =
3825       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3826   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
3827 
3828   // All aggregates are passed indirectly?  That doesn't seem consistent
3829   // with the argument-lowering code.
3830   bool isIndirect = Ty->isAggregateType();
3831 
3832   CGBuilderTy &Builder = CGF.Builder;
3833 
3834   // The calling convention either uses 1-2 GPRs or 1 FPR.
3835   Address NumRegsAddr = Address::invalid();
3836   if (isInt || IsSoftFloatABI) {
3837     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3838   } else {
3839     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
3840   }
3841 
3842   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3843 
3844   // "Align" the register count when TY is i64.
3845   if (isI64 || (isF64 && IsSoftFloatABI)) {
3846     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3847     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3848   }
3849 
3850   llvm::Value *CC =
3851       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
3852 
3853   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3854   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3855   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3856 
3857   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3858 
3859   llvm::Type *DirectTy = CGF.ConvertType(Ty);
3860   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
3861 
3862   // Case 1: consume registers.
3863   Address RegAddr = Address::invalid();
3864   {
3865     CGF.EmitBlock(UsingRegs);
3866 
3867     Address RegSaveAreaPtr =
3868       Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3869     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3870                       CharUnits::fromQuantity(8));
3871     assert(RegAddr.getElementType() == CGF.Int8Ty);
3872 
3873     // Floating-point registers start after the general-purpose registers.
3874     if (!(isInt || IsSoftFloatABI)) {
3875       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3876                                                    CharUnits::fromQuantity(32));
3877     }
3878 
3879     // Get the address of the saved value by scaling the number of
3880     // registers we've used by the number of
3881     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
3882     llvm::Value *RegOffset =
3883       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3884     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3885                                             RegAddr.getPointer(), RegOffset),
3886                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3887     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3888 
3889     // Increase the used-register count.
3890     NumRegs =
3891       Builder.CreateAdd(NumRegs,
3892                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
3893     Builder.CreateStore(NumRegs, NumRegsAddr);
3894 
3895     CGF.EmitBranch(Cont);
3896   }
3897 
3898   // Case 2: consume space in the overflow area.
3899   Address MemAddr = Address::invalid();
3900   {
3901     CGF.EmitBlock(UsingOverflow);
3902 
3903     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3904 
3905     // Everything in the overflow area is rounded up to a size of at least 4.
3906     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3907 
3908     CharUnits Size;
3909     if (!isIndirect) {
3910       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
3911       Size = TypeInfo.first.alignTo(OverflowAreaAlign);
3912     } else {
3913       Size = CGF.getPointerSize();
3914     }
3915 
3916     Address OverflowAreaAddr =
3917       Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
3918     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
3919                          OverflowAreaAlign);
3920     // Round up address of argument to alignment
3921     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3922     if (Align > OverflowAreaAlign) {
3923       llvm::Value *Ptr = OverflowArea.getPointer();
3924       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3925                                                            Align);
3926     }
3927 
3928     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3929 
3930     // Increase the overflow area.
3931     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3932     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3933     CGF.EmitBranch(Cont);
3934   }
3935 
3936   CGF.EmitBlock(Cont);
3937 
3938   // Merge the cases with a phi.
3939   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3940                                 "vaarg.addr");
3941 
3942   // Load the pointer if the argument was passed indirectly.
3943   if (isIndirect) {
3944     Result = Address(Builder.CreateLoad(Result, "aggr"),
3945                      getContext().getTypeAlignInChars(Ty));
3946   }
3947 
3948   return Result;
3949 }
3950 
3951 bool
3952 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3953                                                 llvm::Value *Address) const {
3954   // This is calculated from the LLVM and GCC tables and verified
3955   // against gcc output.  AFAIK all ABIs use the same encoding.
3956 
3957   CodeGen::CGBuilderTy &Builder = CGF.Builder;
3958 
3959   llvm::IntegerType *i8 = CGF.Int8Ty;
3960   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3961   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3962   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3963 
3964   // 0-31: r0-31, the 4-byte general-purpose registers
3965   AssignToArrayRange(Builder, Address, Four8, 0, 31);
3966 
3967   // 32-63: fp0-31, the 8-byte floating-point registers
3968   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3969 
3970   // 64-76 are various 4-byte special-purpose registers:
3971   // 64: mq
3972   // 65: lr
3973   // 66: ctr
3974   // 67: ap
3975   // 68-75 cr0-7
3976   // 76: xer
3977   AssignToArrayRange(Builder, Address, Four8, 64, 76);
3978 
3979   // 77-108: v0-31, the 16-byte vector registers
3980   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3981 
3982   // 109: vrsave
3983   // 110: vscr
3984   // 111: spe_acc
3985   // 112: spefscr
3986   // 113: sfp
3987   AssignToArrayRange(Builder, Address, Four8, 109, 113);
3988 
3989   return false;
3990 }
3991 
3992 // PowerPC-64
3993 
3994 namespace {
3995 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3996 class PPC64_SVR4_ABIInfo : public ABIInfo {
3997 public:
3998   enum ABIKind {
3999     ELFv1 = 0,
4000     ELFv2
4001   };
4002 
4003 private:
4004   static const unsigned GPRBits = 64;
4005   ABIKind Kind;
4006   bool HasQPX;
4007   bool IsSoftFloatABI;
4008 
4009   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4010   // will be passed in a QPX register.
4011   bool IsQPXVectorTy(const Type *Ty) const {
4012     if (!HasQPX)
4013       return false;
4014 
4015     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4016       unsigned NumElements = VT->getNumElements();
4017       if (NumElements == 1)
4018         return false;
4019 
4020       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4021         if (getContext().getTypeSize(Ty) <= 256)
4022           return true;
4023       } else if (VT->getElementType()->
4024                    isSpecificBuiltinType(BuiltinType::Float)) {
4025         if (getContext().getTypeSize(Ty) <= 128)
4026           return true;
4027       }
4028     }
4029 
4030     return false;
4031   }
4032 
4033   bool IsQPXVectorTy(QualType Ty) const {
4034     return IsQPXVectorTy(Ty.getTypePtr());
4035   }
4036 
4037 public:
4038   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4039                      bool SoftFloatABI)
4040       : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4041         IsSoftFloatABI(SoftFloatABI) {}
4042 
4043   bool isPromotableTypeForABI(QualType Ty) const;
4044   CharUnits getParamTypeAlignment(QualType Ty) const;
4045 
4046   ABIArgInfo classifyReturnType(QualType RetTy) const;
4047   ABIArgInfo classifyArgumentType(QualType Ty) const;
4048 
4049   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4050   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4051                                          uint64_t Members) const override;
4052 
4053   // TODO: We can add more logic to computeInfo to improve performance.
4054   // Example: For aggregate arguments that fit in a register, we could
4055   // use getDirectInReg (as is done below for structs containing a single
4056   // floating-point value) to avoid pushing them to memory on function
4057   // entry.  This would require changing the logic in PPCISelLowering
4058   // when lowering the parameters in the caller and args in the callee.
4059   void computeInfo(CGFunctionInfo &FI) const override {
4060     if (!getCXXABI().classifyReturnType(FI))
4061       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4062     for (auto &I : FI.arguments()) {
4063       // We rely on the default argument classification for the most part.
4064       // One exception:  An aggregate containing a single floating-point
4065       // or vector item must be passed in a register if one is available.
4066       const Type *T = isSingleElementStruct(I.type, getContext());
4067       if (T) {
4068         const BuiltinType *BT = T->getAs<BuiltinType>();
4069         if (IsQPXVectorTy(T) ||
4070             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4071             (BT && BT->isFloatingPoint())) {
4072           QualType QT(T, 0);
4073           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4074           continue;
4075         }
4076       }
4077       I.info = classifyArgumentType(I.type);
4078     }
4079   }
4080 
4081   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4082                     QualType Ty) const override;
4083 };
4084 
4085 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4086 
4087 public:
4088   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4089                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4090                                bool SoftFloatABI)
4091       : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4092                                                  SoftFloatABI)) {}
4093 
4094   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4095     // This is recovered from gcc output.
4096     return 1; // r1 is the dedicated stack pointer
4097   }
4098 
4099   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4100                                llvm::Value *Address) const override;
4101 };
4102 
4103 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4104 public:
4105   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4106 
4107   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4108     // This is recovered from gcc output.
4109     return 1; // r1 is the dedicated stack pointer
4110   }
4111 
4112   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4113                                llvm::Value *Address) const override;
4114 };
4115 
4116 }
4117 
4118 // Return true if the ABI requires Ty to be passed sign- or zero-
4119 // extended to 64 bits.
4120 bool
4121 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4122   // Treat an enum type as its underlying type.
4123   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4124     Ty = EnumTy->getDecl()->getIntegerType();
4125 
4126   // Promotable integer types are required to be promoted by the ABI.
4127   if (Ty->isPromotableIntegerType())
4128     return true;
4129 
4130   // In addition to the usual promotable integer types, we also need to
4131   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4132   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4133     switch (BT->getKind()) {
4134     case BuiltinType::Int:
4135     case BuiltinType::UInt:
4136       return true;
4137     default:
4138       break;
4139     }
4140 
4141   return false;
4142 }
4143 
4144 /// isAlignedParamType - Determine whether a type requires 16-byte or
4145 /// higher alignment in the parameter area.  Always returns at least 8.
4146 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4147   // Complex types are passed just like their elements.
4148   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4149     Ty = CTy->getElementType();
4150 
4151   // Only vector types of size 16 bytes need alignment (larger types are
4152   // passed via reference, smaller types are not aligned).
4153   if (IsQPXVectorTy(Ty)) {
4154     if (getContext().getTypeSize(Ty) > 128)
4155       return CharUnits::fromQuantity(32);
4156 
4157     return CharUnits::fromQuantity(16);
4158   } else if (Ty->isVectorType()) {
4159     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4160   }
4161 
4162   // For single-element float/vector structs, we consider the whole type
4163   // to have the same alignment requirements as its single element.
4164   const Type *AlignAsType = nullptr;
4165   const Type *EltType = isSingleElementStruct(Ty, getContext());
4166   if (EltType) {
4167     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4168     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4169          getContext().getTypeSize(EltType) == 128) ||
4170         (BT && BT->isFloatingPoint()))
4171       AlignAsType = EltType;
4172   }
4173 
4174   // Likewise for ELFv2 homogeneous aggregates.
4175   const Type *Base = nullptr;
4176   uint64_t Members = 0;
4177   if (!AlignAsType && Kind == ELFv2 &&
4178       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4179     AlignAsType = Base;
4180 
4181   // With special case aggregates, only vector base types need alignment.
4182   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4183     if (getContext().getTypeSize(AlignAsType) > 128)
4184       return CharUnits::fromQuantity(32);
4185 
4186     return CharUnits::fromQuantity(16);
4187   } else if (AlignAsType) {
4188     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4189   }
4190 
4191   // Otherwise, we only need alignment for any aggregate type that
4192   // has an alignment requirement of >= 16 bytes.
4193   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4194     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4195       return CharUnits::fromQuantity(32);
4196     return CharUnits::fromQuantity(16);
4197   }
4198 
4199   return CharUnits::fromQuantity(8);
4200 }
4201 
4202 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4203 /// aggregate.  Base is set to the base element type, and Members is set
4204 /// to the number of base elements.
4205 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4206                                      uint64_t &Members) const {
4207   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4208     uint64_t NElements = AT->getSize().getZExtValue();
4209     if (NElements == 0)
4210       return false;
4211     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4212       return false;
4213     Members *= NElements;
4214   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4215     const RecordDecl *RD = RT->getDecl();
4216     if (RD->hasFlexibleArrayMember())
4217       return false;
4218 
4219     Members = 0;
4220 
4221     // If this is a C++ record, check the bases first.
4222     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4223       for (const auto &I : CXXRD->bases()) {
4224         // Ignore empty records.
4225         if (isEmptyRecord(getContext(), I.getType(), true))
4226           continue;
4227 
4228         uint64_t FldMembers;
4229         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4230           return false;
4231 
4232         Members += FldMembers;
4233       }
4234     }
4235 
4236     for (const auto *FD : RD->fields()) {
4237       // Ignore (non-zero arrays of) empty records.
4238       QualType FT = FD->getType();
4239       while (const ConstantArrayType *AT =
4240              getContext().getAsConstantArrayType(FT)) {
4241         if (AT->getSize().getZExtValue() == 0)
4242           return false;
4243         FT = AT->getElementType();
4244       }
4245       if (isEmptyRecord(getContext(), FT, true))
4246         continue;
4247 
4248       // For compatibility with GCC, ignore empty bitfields in C++ mode.
4249       if (getContext().getLangOpts().CPlusPlus &&
4250           FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4251         continue;
4252 
4253       uint64_t FldMembers;
4254       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4255         return false;
4256 
4257       Members = (RD->isUnion() ?
4258                  std::max(Members, FldMembers) : Members + FldMembers);
4259     }
4260 
4261     if (!Base)
4262       return false;
4263 
4264     // Ensure there is no padding.
4265     if (getContext().getTypeSize(Base) * Members !=
4266         getContext().getTypeSize(Ty))
4267       return false;
4268   } else {
4269     Members = 1;
4270     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4271       Members = 2;
4272       Ty = CT->getElementType();
4273     }
4274 
4275     // Most ABIs only support float, double, and some vector type widths.
4276     if (!isHomogeneousAggregateBaseType(Ty))
4277       return false;
4278 
4279     // The base type must be the same for all members.  Types that
4280     // agree in both total size and mode (float vs. vector) are
4281     // treated as being equivalent here.
4282     const Type *TyPtr = Ty.getTypePtr();
4283     if (!Base) {
4284       Base = TyPtr;
4285       // If it's a non-power-of-2 vector, its size is already a power-of-2,
4286       // so make sure to widen it explicitly.
4287       if (const VectorType *VT = Base->getAs<VectorType>()) {
4288         QualType EltTy = VT->getElementType();
4289         unsigned NumElements =
4290             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4291         Base = getContext()
4292                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
4293                    .getTypePtr();
4294       }
4295     }
4296 
4297     if (Base->isVectorType() != TyPtr->isVectorType() ||
4298         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4299       return false;
4300   }
4301   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4302 }
4303 
4304 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4305   // Homogeneous aggregates for ELFv2 must have base types of float,
4306   // double, long double, or 128-bit vectors.
4307   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4308     if (BT->getKind() == BuiltinType::Float ||
4309         BT->getKind() == BuiltinType::Double ||
4310         BT->getKind() == BuiltinType::LongDouble) {
4311       if (IsSoftFloatABI)
4312         return false;
4313       return true;
4314     }
4315   }
4316   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4317     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4318       return true;
4319   }
4320   return false;
4321 }
4322 
4323 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4324     const Type *Base, uint64_t Members) const {
4325   // Vector types require one register, floating point types require one
4326   // or two registers depending on their size.
4327   uint32_t NumRegs =
4328       Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
4329 
4330   // Homogeneous Aggregates may occupy at most 8 registers.
4331   return Members * NumRegs <= 8;
4332 }
4333 
4334 ABIArgInfo
4335 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4336   Ty = useFirstFieldIfTransparentUnion(Ty);
4337 
4338   if (Ty->isAnyComplexType())
4339     return ABIArgInfo::getDirect();
4340 
4341   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4342   // or via reference (larger than 16 bytes).
4343   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4344     uint64_t Size = getContext().getTypeSize(Ty);
4345     if (Size > 128)
4346       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4347     else if (Size < 128) {
4348       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4349       return ABIArgInfo::getDirect(CoerceTy);
4350     }
4351   }
4352 
4353   if (isAggregateTypeForABI(Ty)) {
4354     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4355       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4356 
4357     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4358     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4359 
4360     // ELFv2 homogeneous aggregates are passed as array types.
4361     const Type *Base = nullptr;
4362     uint64_t Members = 0;
4363     if (Kind == ELFv2 &&
4364         isHomogeneousAggregate(Ty, Base, Members)) {
4365       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4366       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4367       return ABIArgInfo::getDirect(CoerceTy);
4368     }
4369 
4370     // If an aggregate may end up fully in registers, we do not
4371     // use the ByVal method, but pass the aggregate as array.
4372     // This is usually beneficial since we avoid forcing the
4373     // back-end to store the argument to memory.
4374     uint64_t Bits = getContext().getTypeSize(Ty);
4375     if (Bits > 0 && Bits <= 8 * GPRBits) {
4376       llvm::Type *CoerceTy;
4377 
4378       // Types up to 8 bytes are passed as integer type (which will be
4379       // properly aligned in the argument save area doubleword).
4380       if (Bits <= GPRBits)
4381         CoerceTy =
4382             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4383       // Larger types are passed as arrays, with the base type selected
4384       // according to the required alignment in the save area.
4385       else {
4386         uint64_t RegBits = ABIAlign * 8;
4387         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4388         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4389         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4390       }
4391 
4392       return ABIArgInfo::getDirect(CoerceTy);
4393     }
4394 
4395     // All other aggregates are passed ByVal.
4396     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4397                                    /*ByVal=*/true,
4398                                    /*Realign=*/TyAlign > ABIAlign);
4399   }
4400 
4401   return (isPromotableTypeForABI(Ty) ?
4402           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4403 }
4404 
4405 ABIArgInfo
4406 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4407   if (RetTy->isVoidType())
4408     return ABIArgInfo::getIgnore();
4409 
4410   if (RetTy->isAnyComplexType())
4411     return ABIArgInfo::getDirect();
4412 
4413   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4414   // or via reference (larger than 16 bytes).
4415   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4416     uint64_t Size = getContext().getTypeSize(RetTy);
4417     if (Size > 128)
4418       return getNaturalAlignIndirect(RetTy);
4419     else if (Size < 128) {
4420       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4421       return ABIArgInfo::getDirect(CoerceTy);
4422     }
4423   }
4424 
4425   if (isAggregateTypeForABI(RetTy)) {
4426     // ELFv2 homogeneous aggregates are returned as array types.
4427     const Type *Base = nullptr;
4428     uint64_t Members = 0;
4429     if (Kind == ELFv2 &&
4430         isHomogeneousAggregate(RetTy, Base, Members)) {
4431       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4432       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4433       return ABIArgInfo::getDirect(CoerceTy);
4434     }
4435 
4436     // ELFv2 small aggregates are returned in up to two registers.
4437     uint64_t Bits = getContext().getTypeSize(RetTy);
4438     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4439       if (Bits == 0)
4440         return ABIArgInfo::getIgnore();
4441 
4442       llvm::Type *CoerceTy;
4443       if (Bits > GPRBits) {
4444         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4445         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
4446       } else
4447         CoerceTy =
4448             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4449       return ABIArgInfo::getDirect(CoerceTy);
4450     }
4451 
4452     // All other aggregates are returned indirectly.
4453     return getNaturalAlignIndirect(RetTy);
4454   }
4455 
4456   return (isPromotableTypeForABI(RetTy) ?
4457           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4458 }
4459 
4460 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4461 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4462                                       QualType Ty) const {
4463   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4464   TypeInfo.second = getParamTypeAlignment(Ty);
4465 
4466   CharUnits SlotSize = CharUnits::fromQuantity(8);
4467 
4468   // If we have a complex type and the base type is smaller than 8 bytes,
4469   // the ABI calls for the real and imaginary parts to be right-adjusted
4470   // in separate doublewords.  However, Clang expects us to produce a
4471   // pointer to a structure with the two parts packed tightly.  So generate
4472   // loads of the real and imaginary parts relative to the va_list pointer,
4473   // and store them to a temporary structure.
4474   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4475     CharUnits EltSize = TypeInfo.first / 2;
4476     if (EltSize < SlotSize) {
4477       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4478                                             SlotSize * 2, SlotSize,
4479                                             SlotSize, /*AllowHigher*/ true);
4480 
4481       Address RealAddr = Addr;
4482       Address ImagAddr = RealAddr;
4483       if (CGF.CGM.getDataLayout().isBigEndian()) {
4484         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4485                                                           SlotSize - EltSize);
4486         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4487                                                       2 * SlotSize - EltSize);
4488       } else {
4489         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4490       }
4491 
4492       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4493       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4494       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4495       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4496       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4497 
4498       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4499       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4500                              /*init*/ true);
4501       return Temp;
4502     }
4503   }
4504 
4505   // Otherwise, just use the general rule.
4506   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4507                           TypeInfo, SlotSize, /*AllowHigher*/ true);
4508 }
4509 
4510 static bool
4511 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4512                               llvm::Value *Address) {
4513   // This is calculated from the LLVM and GCC tables and verified
4514   // against gcc output.  AFAIK all ABIs use the same encoding.
4515 
4516   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4517 
4518   llvm::IntegerType *i8 = CGF.Int8Ty;
4519   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4520   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4521   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4522 
4523   // 0-31: r0-31, the 8-byte general-purpose registers
4524   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4525 
4526   // 32-63: fp0-31, the 8-byte floating-point registers
4527   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4528 
4529   // 64-67 are various 8-byte special-purpose registers:
4530   // 64: mq
4531   // 65: lr
4532   // 66: ctr
4533   // 67: ap
4534   AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4535 
4536   // 68-76 are various 4-byte special-purpose registers:
4537   // 68-75 cr0-7
4538   // 76: xer
4539   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4540 
4541   // 77-108: v0-31, the 16-byte vector registers
4542   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4543 
4544   // 109: vrsave
4545   // 110: vscr
4546   // 111: spe_acc
4547   // 112: spefscr
4548   // 113: sfp
4549   // 114: tfhar
4550   // 115: tfiar
4551   // 116: texasr
4552   AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4553 
4554   return false;
4555 }
4556 
4557 bool
4558 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4559   CodeGen::CodeGenFunction &CGF,
4560   llvm::Value *Address) const {
4561 
4562   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4563 }
4564 
4565 bool
4566 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4567                                                 llvm::Value *Address) const {
4568 
4569   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4570 }
4571 
4572 //===----------------------------------------------------------------------===//
4573 // AArch64 ABI Implementation
4574 //===----------------------------------------------------------------------===//
4575 
4576 namespace {
4577 
4578 class AArch64ABIInfo : public SwiftABIInfo {
4579 public:
4580   enum ABIKind {
4581     AAPCS = 0,
4582     DarwinPCS
4583   };
4584 
4585 private:
4586   ABIKind Kind;
4587 
4588 public:
4589   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4590     : SwiftABIInfo(CGT), Kind(Kind) {}
4591 
4592 private:
4593   ABIKind getABIKind() const { return Kind; }
4594   bool isDarwinPCS() const { return Kind == DarwinPCS; }
4595 
4596   ABIArgInfo classifyReturnType(QualType RetTy) const;
4597   ABIArgInfo classifyArgumentType(QualType RetTy) const;
4598   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4599   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4600                                          uint64_t Members) const override;
4601 
4602   bool isIllegalVectorType(QualType Ty) const;
4603 
4604   void computeInfo(CGFunctionInfo &FI) const override {
4605     if (!getCXXABI().classifyReturnType(FI))
4606       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4607 
4608     for (auto &it : FI.arguments())
4609       it.info = classifyArgumentType(it.type);
4610   }
4611 
4612   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4613                           CodeGenFunction &CGF) const;
4614 
4615   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4616                          CodeGenFunction &CGF) const;
4617 
4618   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4619                     QualType Ty) const override {
4620     return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4621                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4622   }
4623 
4624   bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4625                                     ArrayRef<llvm::Type*> scalars,
4626                                     bool asReturnValue) const override {
4627     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4628   }
4629 };
4630 
4631 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4632 public:
4633   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4634       : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4635 
4636   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4637     return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4638   }
4639 
4640   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4641     return 31;
4642   }
4643 
4644   bool doesReturnSlotInterfereWithArgs() const override { return false; }
4645 };
4646 }
4647 
4648 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4649   Ty = useFirstFieldIfTransparentUnion(Ty);
4650 
4651   // Handle illegal vector types here.
4652   if (isIllegalVectorType(Ty)) {
4653     uint64_t Size = getContext().getTypeSize(Ty);
4654     // Android promotes <2 x i8> to i16, not i32
4655     if (isAndroid() && (Size <= 16)) {
4656       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4657       return ABIArgInfo::getDirect(ResType);
4658     }
4659     if (Size <= 32) {
4660       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4661       return ABIArgInfo::getDirect(ResType);
4662     }
4663     if (Size == 64) {
4664       llvm::Type *ResType =
4665           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4666       return ABIArgInfo::getDirect(ResType);
4667     }
4668     if (Size == 128) {
4669       llvm::Type *ResType =
4670           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4671       return ABIArgInfo::getDirect(ResType);
4672     }
4673     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4674   }
4675 
4676   if (!isAggregateTypeForABI(Ty)) {
4677     // Treat an enum type as its underlying type.
4678     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4679       Ty = EnumTy->getDecl()->getIntegerType();
4680 
4681     return (Ty->isPromotableIntegerType() && isDarwinPCS()
4682                 ? ABIArgInfo::getExtend()
4683                 : ABIArgInfo::getDirect());
4684   }
4685 
4686   // Structures with either a non-trivial destructor or a non-trivial
4687   // copy constructor are always indirect.
4688   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4689     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4690                                      CGCXXABI::RAA_DirectInMemory);
4691   }
4692 
4693   // Empty records are always ignored on Darwin, but actually passed in C++ mode
4694   // elsewhere for GNU compatibility.
4695   if (isEmptyRecord(getContext(), Ty, true)) {
4696     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4697       return ABIArgInfo::getIgnore();
4698 
4699     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4700   }
4701 
4702   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4703   const Type *Base = nullptr;
4704   uint64_t Members = 0;
4705   if (isHomogeneousAggregate(Ty, Base, Members)) {
4706     return ABIArgInfo::getDirect(
4707         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4708   }
4709 
4710   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4711   uint64_t Size = getContext().getTypeSize(Ty);
4712   if (Size <= 128) {
4713     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4714     // same size and alignment.
4715     if (getTarget().isRenderScriptTarget()) {
4716       return coerceToIntArray(Ty, getContext(), getVMContext());
4717     }
4718     unsigned Alignment = getContext().getTypeAlign(Ty);
4719     Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4720 
4721     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4722     // For aggregates with 16-byte alignment, we use i128.
4723     if (Alignment < 128 && Size == 128) {
4724       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4725       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4726     }
4727     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4728   }
4729 
4730   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4731 }
4732 
4733 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4734   if (RetTy->isVoidType())
4735     return ABIArgInfo::getIgnore();
4736 
4737   // Large vector types should be returned via memory.
4738   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4739     return getNaturalAlignIndirect(RetTy);
4740 
4741   if (!isAggregateTypeForABI(RetTy)) {
4742     // Treat an enum type as its underlying type.
4743     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4744       RetTy = EnumTy->getDecl()->getIntegerType();
4745 
4746     return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4747                 ? ABIArgInfo::getExtend()
4748                 : ABIArgInfo::getDirect());
4749   }
4750 
4751   if (isEmptyRecord(getContext(), RetTy, true))
4752     return ABIArgInfo::getIgnore();
4753 
4754   const Type *Base = nullptr;
4755   uint64_t Members = 0;
4756   if (isHomogeneousAggregate(RetTy, Base, Members))
4757     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4758     return ABIArgInfo::getDirect();
4759 
4760   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4761   uint64_t Size = getContext().getTypeSize(RetTy);
4762   if (Size <= 128) {
4763     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4764     // same size and alignment.
4765     if (getTarget().isRenderScriptTarget()) {
4766       return coerceToIntArray(RetTy, getContext(), getVMContext());
4767     }
4768     unsigned Alignment = getContext().getTypeAlign(RetTy);
4769     Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4770 
4771     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4772     // For aggregates with 16-byte alignment, we use i128.
4773     if (Alignment < 128 && Size == 128) {
4774       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4775       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4776     }
4777     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4778   }
4779 
4780   return getNaturalAlignIndirect(RetTy);
4781 }
4782 
4783 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4784 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4785   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4786     // Check whether VT is legal.
4787     unsigned NumElements = VT->getNumElements();
4788     uint64_t Size = getContext().getTypeSize(VT);
4789     // NumElements should be power of 2.
4790     if (!llvm::isPowerOf2_32(NumElements))
4791       return true;
4792     return Size != 64 && (Size != 128 || NumElements == 1);
4793   }
4794   return false;
4795 }
4796 
4797 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4798   // Homogeneous aggregates for AAPCS64 must have base types of a floating
4799   // point type or a short-vector type. This is the same as the 32-bit ABI,
4800   // but with the difference that any floating-point type is allowed,
4801   // including __fp16.
4802   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4803     if (BT->isFloatingPoint())
4804       return true;
4805   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4806     unsigned VecSize = getContext().getTypeSize(VT);
4807     if (VecSize == 64 || VecSize == 128)
4808       return true;
4809   }
4810   return false;
4811 }
4812 
4813 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4814                                                        uint64_t Members) const {
4815   return Members <= 4;
4816 }
4817 
4818 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
4819                                             QualType Ty,
4820                                             CodeGenFunction &CGF) const {
4821   ABIArgInfo AI = classifyArgumentType(Ty);
4822   bool IsIndirect = AI.isIndirect();
4823 
4824   llvm::Type *BaseTy = CGF.ConvertType(Ty);
4825   if (IsIndirect)
4826     BaseTy = llvm::PointerType::getUnqual(BaseTy);
4827   else if (AI.getCoerceToType())
4828     BaseTy = AI.getCoerceToType();
4829 
4830   unsigned NumRegs = 1;
4831   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4832     BaseTy = ArrTy->getElementType();
4833     NumRegs = ArrTy->getNumElements();
4834   }
4835   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4836 
4837   // The AArch64 va_list type and handling is specified in the Procedure Call
4838   // Standard, section B.4:
4839   //
4840   // struct {
4841   //   void *__stack;
4842   //   void *__gr_top;
4843   //   void *__vr_top;
4844   //   int __gr_offs;
4845   //   int __vr_offs;
4846   // };
4847 
4848   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4849   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4850   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4851   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4852 
4853   auto TyInfo = getContext().getTypeInfoInChars(Ty);
4854   CharUnits TyAlign = TyInfo.second;
4855 
4856   Address reg_offs_p = Address::invalid();
4857   llvm::Value *reg_offs = nullptr;
4858   int reg_top_index;
4859   CharUnits reg_top_offset;
4860   int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
4861   if (!IsFPR) {
4862     // 3 is the field number of __gr_offs
4863     reg_offs_p =
4864         CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4865                                     "gr_offs_p");
4866     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4867     reg_top_index = 1; // field number for __gr_top
4868     reg_top_offset = CharUnits::fromQuantity(8);
4869     RegSize = llvm::alignTo(RegSize, 8);
4870   } else {
4871     // 4 is the field number of __vr_offs.
4872     reg_offs_p =
4873         CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4874                                     "vr_offs_p");
4875     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4876     reg_top_index = 2; // field number for __vr_top
4877     reg_top_offset = CharUnits::fromQuantity(16);
4878     RegSize = 16 * NumRegs;
4879   }
4880 
4881   //=======================================
4882   // Find out where argument was passed
4883   //=======================================
4884 
4885   // If reg_offs >= 0 we're already using the stack for this type of
4886   // argument. We don't want to keep updating reg_offs (in case it overflows,
4887   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4888   // whatever they get).
4889   llvm::Value *UsingStack = nullptr;
4890   UsingStack = CGF.Builder.CreateICmpSGE(
4891       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4892 
4893   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4894 
4895   // Otherwise, at least some kind of argument could go in these registers, the
4896   // question is whether this particular type is too big.
4897   CGF.EmitBlock(MaybeRegBlock);
4898 
4899   // Integer arguments may need to correct register alignment (for example a
4900   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4901   // align __gr_offs to calculate the potential address.
4902   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4903     int Align = TyAlign.getQuantity();
4904 
4905     reg_offs = CGF.Builder.CreateAdd(
4906         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4907         "align_regoffs");
4908     reg_offs = CGF.Builder.CreateAnd(
4909         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4910         "aligned_regoffs");
4911   }
4912 
4913   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4914   // The fact that this is done unconditionally reflects the fact that
4915   // allocating an argument to the stack also uses up all the remaining
4916   // registers of the appropriate kind.
4917   llvm::Value *NewOffset = nullptr;
4918   NewOffset = CGF.Builder.CreateAdd(
4919       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4920   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4921 
4922   // Now we're in a position to decide whether this argument really was in
4923   // registers or not.
4924   llvm::Value *InRegs = nullptr;
4925   InRegs = CGF.Builder.CreateICmpSLE(
4926       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4927 
4928   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4929 
4930   //=======================================
4931   // Argument was in registers
4932   //=======================================
4933 
4934   // Now we emit the code for if the argument was originally passed in
4935   // registers. First start the appropriate block:
4936   CGF.EmitBlock(InRegBlock);
4937 
4938   llvm::Value *reg_top = nullptr;
4939   Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4940                                                   reg_top_offset, "reg_top_p");
4941   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4942   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4943                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
4944   Address RegAddr = Address::invalid();
4945   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
4946 
4947   if (IsIndirect) {
4948     // If it's been passed indirectly (actually a struct), whatever we find from
4949     // stored registers or on the stack will actually be a struct **.
4950     MemTy = llvm::PointerType::getUnqual(MemTy);
4951   }
4952 
4953   const Type *Base = nullptr;
4954   uint64_t NumMembers = 0;
4955   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
4956   if (IsHFA && NumMembers > 1) {
4957     // Homogeneous aggregates passed in registers will have their elements split
4958     // and stored 16-bytes apart regardless of size (they're notionally in qN,
4959     // qN+1, ...). We reload and store into a temporary local variable
4960     // contiguously.
4961     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4962     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
4963     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4964     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4965     Address Tmp = CGF.CreateTempAlloca(HFATy,
4966                                        std::max(TyAlign, BaseTyInfo.second));
4967 
4968     // On big-endian platforms, the value will be right-aligned in its slot.
4969     int Offset = 0;
4970     if (CGF.CGM.getDataLayout().isBigEndian() &&
4971         BaseTyInfo.first.getQuantity() < 16)
4972       Offset = 16 - BaseTyInfo.first.getQuantity();
4973 
4974     for (unsigned i = 0; i < NumMembers; ++i) {
4975       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4976       Address LoadAddr =
4977         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4978       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4979 
4980       Address StoreAddr =
4981         CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
4982 
4983       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4984       CGF.Builder.CreateStore(Elem, StoreAddr);
4985     }
4986 
4987     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
4988   } else {
4989     // Otherwise the object is contiguous in memory.
4990 
4991     // It might be right-aligned in its slot.
4992     CharUnits SlotSize = BaseAddr.getAlignment();
4993     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
4994         (IsHFA || !isAggregateTypeForABI(Ty)) &&
4995         TyInfo.first < SlotSize) {
4996       CharUnits Offset = SlotSize - TyInfo.first;
4997       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
4998     }
4999 
5000     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5001   }
5002 
5003   CGF.EmitBranch(ContBlock);
5004 
5005   //=======================================
5006   // Argument was on the stack
5007   //=======================================
5008   CGF.EmitBlock(OnStackBlock);
5009 
5010   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5011                                                 CharUnits::Zero(), "stack_p");
5012   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5013 
5014   // Again, stack arguments may need realignment. In this case both integer and
5015   // floating-point ones might be affected.
5016   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5017     int Align = TyAlign.getQuantity();
5018 
5019     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5020 
5021     OnStackPtr = CGF.Builder.CreateAdd(
5022         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5023         "align_stack");
5024     OnStackPtr = CGF.Builder.CreateAnd(
5025         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5026         "align_stack");
5027 
5028     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5029   }
5030   Address OnStackAddr(OnStackPtr,
5031                       std::max(CharUnits::fromQuantity(8), TyAlign));
5032 
5033   // All stack slots are multiples of 8 bytes.
5034   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5035   CharUnits StackSize;
5036   if (IsIndirect)
5037     StackSize = StackSlotSize;
5038   else
5039     StackSize = TyInfo.first.alignTo(StackSlotSize);
5040 
5041   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5042   llvm::Value *NewStack =
5043       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5044 
5045   // Write the new value of __stack for the next call to va_arg
5046   CGF.Builder.CreateStore(NewStack, stack_p);
5047 
5048   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5049       TyInfo.first < StackSlotSize) {
5050     CharUnits Offset = StackSlotSize - TyInfo.first;
5051     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5052   }
5053 
5054   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5055 
5056   CGF.EmitBranch(ContBlock);
5057 
5058   //=======================================
5059   // Tidy up
5060   //=======================================
5061   CGF.EmitBlock(ContBlock);
5062 
5063   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5064                                  OnStackAddr, OnStackBlock, "vaargs.addr");
5065 
5066   if (IsIndirect)
5067     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5068                    TyInfo.second);
5069 
5070   return ResAddr;
5071 }
5072 
5073 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5074                                         CodeGenFunction &CGF) const {
5075   // The backend's lowering doesn't support va_arg for aggregates or
5076   // illegal vector types.  Lower VAArg here for these cases and use
5077   // the LLVM va_arg instruction for everything else.
5078   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5079     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5080 
5081   CharUnits SlotSize = CharUnits::fromQuantity(8);
5082 
5083   // Empty records are ignored for parameter passing purposes.
5084   if (isEmptyRecord(getContext(), Ty, true)) {
5085     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5086     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5087     return Addr;
5088   }
5089 
5090   // The size of the actual thing passed, which might end up just
5091   // being a pointer for indirect types.
5092   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5093 
5094   // Arguments bigger than 16 bytes which aren't homogeneous
5095   // aggregates should be passed indirectly.
5096   bool IsIndirect = false;
5097   if (TyInfo.first.getQuantity() > 16) {
5098     const Type *Base = nullptr;
5099     uint64_t Members = 0;
5100     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5101   }
5102 
5103   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5104                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5105 }
5106 
5107 //===----------------------------------------------------------------------===//
5108 // ARM ABI Implementation
5109 //===----------------------------------------------------------------------===//
5110 
5111 namespace {
5112 
5113 class ARMABIInfo : public SwiftABIInfo {
5114 public:
5115   enum ABIKind {
5116     APCS = 0,
5117     AAPCS = 1,
5118     AAPCS_VFP = 2,
5119     AAPCS16_VFP = 3,
5120   };
5121 
5122 private:
5123   ABIKind Kind;
5124 
5125 public:
5126   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5127       : SwiftABIInfo(CGT), Kind(_Kind) {
5128     setCCs();
5129   }
5130 
5131   bool isEABI() const {
5132     switch (getTarget().getTriple().getEnvironment()) {
5133     case llvm::Triple::Android:
5134     case llvm::Triple::EABI:
5135     case llvm::Triple::EABIHF:
5136     case llvm::Triple::GNUEABI:
5137     case llvm::Triple::GNUEABIHF:
5138     case llvm::Triple::MuslEABI:
5139     case llvm::Triple::MuslEABIHF:
5140       return true;
5141     default:
5142       return false;
5143     }
5144   }
5145 
5146   bool isEABIHF() const {
5147     switch (getTarget().getTriple().getEnvironment()) {
5148     case llvm::Triple::EABIHF:
5149     case llvm::Triple::GNUEABIHF:
5150     case llvm::Triple::MuslEABIHF:
5151       return true;
5152     default:
5153       return false;
5154     }
5155   }
5156 
5157   ABIKind getABIKind() const { return Kind; }
5158 
5159 private:
5160   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5161   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5162   bool isIllegalVectorType(QualType Ty) const;
5163 
5164   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5165   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5166                                          uint64_t Members) const override;
5167 
5168   void computeInfo(CGFunctionInfo &FI) const override;
5169 
5170   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5171                     QualType Ty) const override;
5172 
5173   llvm::CallingConv::ID getLLVMDefaultCC() const;
5174   llvm::CallingConv::ID getABIDefaultCC() const;
5175   void setCCs();
5176 
5177   bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5178                                     ArrayRef<llvm::Type*> scalars,
5179                                     bool asReturnValue) const override {
5180     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5181   }
5182 };
5183 
5184 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5185 public:
5186   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5187     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5188 
5189   const ARMABIInfo &getABIInfo() const {
5190     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5191   }
5192 
5193   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5194     return 13;
5195   }
5196 
5197   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5198     return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5199   }
5200 
5201   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5202                                llvm::Value *Address) const override {
5203     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5204 
5205     // 0-15 are the 16 integer registers.
5206     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5207     return false;
5208   }
5209 
5210   unsigned getSizeOfUnwindException() const override {
5211     if (getABIInfo().isEABI()) return 88;
5212     return TargetCodeGenInfo::getSizeOfUnwindException();
5213   }
5214 
5215   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5216                            CodeGen::CodeGenModule &CGM) const override {
5217     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5218     if (!FD)
5219       return;
5220 
5221     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5222     if (!Attr)
5223       return;
5224 
5225     const char *Kind;
5226     switch (Attr->getInterrupt()) {
5227     case ARMInterruptAttr::Generic: Kind = ""; break;
5228     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
5229     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
5230     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
5231     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
5232     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
5233     }
5234 
5235     llvm::Function *Fn = cast<llvm::Function>(GV);
5236 
5237     Fn->addFnAttr("interrupt", Kind);
5238 
5239     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5240     if (ABI == ARMABIInfo::APCS)
5241       return;
5242 
5243     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5244     // however this is not necessarily true on taking any interrupt. Instruct
5245     // the backend to perform a realignment as part of the function prologue.
5246     llvm::AttrBuilder B;
5247     B.addStackAlignmentAttr(8);
5248     Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5249                       llvm::AttributeSet::get(CGM.getLLVMContext(),
5250                                               llvm::AttributeSet::FunctionIndex,
5251                                               B));
5252   }
5253 };
5254 
5255 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5256 public:
5257   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5258       : ARMTargetCodeGenInfo(CGT, K) {}
5259 
5260   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5261                            CodeGen::CodeGenModule &CGM) const override;
5262 
5263   void getDependentLibraryOption(llvm::StringRef Lib,
5264                                  llvm::SmallString<24> &Opt) const override {
5265     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5266   }
5267 
5268   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5269                                llvm::SmallString<32> &Opt) const override {
5270     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5271   }
5272 };
5273 
5274 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5275     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5276   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5277   addStackProbeSizeTargetAttribute(D, GV, CGM);
5278 }
5279 }
5280 
5281 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5282   if (!getCXXABI().classifyReturnType(FI))
5283     FI.getReturnInfo() =
5284         classifyReturnType(FI.getReturnType(), FI.isVariadic());
5285 
5286   for (auto &I : FI.arguments())
5287     I.info = classifyArgumentType(I.type, FI.isVariadic());
5288 
5289   // Always honor user-specified calling convention.
5290   if (FI.getCallingConvention() != llvm::CallingConv::C)
5291     return;
5292 
5293   llvm::CallingConv::ID cc = getRuntimeCC();
5294   if (cc != llvm::CallingConv::C)
5295     FI.setEffectiveCallingConvention(cc);
5296 }
5297 
5298 /// Return the default calling convention that LLVM will use.
5299 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5300   // The default calling convention that LLVM will infer.
5301   if (isEABIHF() || getTarget().getTriple().isWatchABI())
5302     return llvm::CallingConv::ARM_AAPCS_VFP;
5303   else if (isEABI())
5304     return llvm::CallingConv::ARM_AAPCS;
5305   else
5306     return llvm::CallingConv::ARM_APCS;
5307 }
5308 
5309 /// Return the calling convention that our ABI would like us to use
5310 /// as the C calling convention.
5311 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5312   switch (getABIKind()) {
5313   case APCS: return llvm::CallingConv::ARM_APCS;
5314   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5315   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5316   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5317   }
5318   llvm_unreachable("bad ABI kind");
5319 }
5320 
5321 void ARMABIInfo::setCCs() {
5322   assert(getRuntimeCC() == llvm::CallingConv::C);
5323 
5324   // Don't muddy up the IR with a ton of explicit annotations if
5325   // they'd just match what LLVM will infer from the triple.
5326   llvm::CallingConv::ID abiCC = getABIDefaultCC();
5327   if (abiCC != getLLVMDefaultCC())
5328     RuntimeCC = abiCC;
5329 
5330   // AAPCS apparently requires runtime support functions to be soft-float, but
5331   // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5332   // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5333   switch (getABIKind()) {
5334   case APCS:
5335   case AAPCS16_VFP:
5336     if (abiCC != getLLVMDefaultCC())
5337       BuiltinCC = abiCC;
5338     break;
5339   case AAPCS:
5340   case AAPCS_VFP:
5341     BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5342     break;
5343   }
5344 }
5345 
5346 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5347                                             bool isVariadic) const {
5348   // 6.1.2.1 The following argument types are VFP CPRCs:
5349   //   A single-precision floating-point type (including promoted
5350   //   half-precision types); A double-precision floating-point type;
5351   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5352   //   with a Base Type of a single- or double-precision floating-point type,
5353   //   64-bit containerized vectors or 128-bit containerized vectors with one
5354   //   to four Elements.
5355   bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5356 
5357   Ty = useFirstFieldIfTransparentUnion(Ty);
5358 
5359   // Handle illegal vector types here.
5360   if (isIllegalVectorType(Ty)) {
5361     uint64_t Size = getContext().getTypeSize(Ty);
5362     if (Size <= 32) {
5363       llvm::Type *ResType =
5364           llvm::Type::getInt32Ty(getVMContext());
5365       return ABIArgInfo::getDirect(ResType);
5366     }
5367     if (Size == 64) {
5368       llvm::Type *ResType = llvm::VectorType::get(
5369           llvm::Type::getInt32Ty(getVMContext()), 2);
5370       return ABIArgInfo::getDirect(ResType);
5371     }
5372     if (Size == 128) {
5373       llvm::Type *ResType = llvm::VectorType::get(
5374           llvm::Type::getInt32Ty(getVMContext()), 4);
5375       return ABIArgInfo::getDirect(ResType);
5376     }
5377     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5378   }
5379 
5380   // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5381   // unspecified. This is not done for OpenCL as it handles the half type
5382   // natively, and does not need to interwork with AAPCS code.
5383   if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5384     llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5385       llvm::Type::getFloatTy(getVMContext()) :
5386       llvm::Type::getInt32Ty(getVMContext());
5387     return ABIArgInfo::getDirect(ResType);
5388   }
5389 
5390   if (!isAggregateTypeForABI(Ty)) {
5391     // Treat an enum type as its underlying type.
5392     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5393       Ty = EnumTy->getDecl()->getIntegerType();
5394     }
5395 
5396     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5397                                           : ABIArgInfo::getDirect());
5398   }
5399 
5400   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5401     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5402   }
5403 
5404   // Ignore empty records.
5405   if (isEmptyRecord(getContext(), Ty, true))
5406     return ABIArgInfo::getIgnore();
5407 
5408   if (IsEffectivelyAAPCS_VFP) {
5409     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5410     // into VFP registers.
5411     const Type *Base = nullptr;
5412     uint64_t Members = 0;
5413     if (isHomogeneousAggregate(Ty, Base, Members)) {
5414       assert(Base && "Base class should be set for homogeneous aggregate");
5415       // Base can be a floating-point or a vector.
5416       return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5417     }
5418   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5419     // WatchOS does have homogeneous aggregates. Note that we intentionally use
5420     // this convention even for a variadic function: the backend will use GPRs
5421     // if needed.
5422     const Type *Base = nullptr;
5423     uint64_t Members = 0;
5424     if (isHomogeneousAggregate(Ty, Base, Members)) {
5425       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5426       llvm::Type *Ty =
5427         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5428       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5429     }
5430   }
5431 
5432   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5433       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5434     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5435     // bigger than 128-bits, they get placed in space allocated by the caller,
5436     // and a pointer is passed.
5437     return ABIArgInfo::getIndirect(
5438         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5439   }
5440 
5441   // Support byval for ARM.
5442   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5443   // most 8-byte. We realign the indirect argument if type alignment is bigger
5444   // than ABI alignment.
5445   uint64_t ABIAlign = 4;
5446   uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5447   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5448        getABIKind() == ARMABIInfo::AAPCS)
5449     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5450 
5451   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5452     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5453     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5454                                    /*ByVal=*/true,
5455                                    /*Realign=*/TyAlign > ABIAlign);
5456   }
5457 
5458   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5459   // same size and alignment.
5460   if (getTarget().isRenderScriptTarget()) {
5461     return coerceToIntArray(Ty, getContext(), getVMContext());
5462   }
5463 
5464   // Otherwise, pass by coercing to a structure of the appropriate size.
5465   llvm::Type* ElemTy;
5466   unsigned SizeRegs;
5467   // FIXME: Try to match the types of the arguments more accurately where
5468   // we can.
5469   if (getContext().getTypeAlign(Ty) <= 32) {
5470     ElemTy = llvm::Type::getInt32Ty(getVMContext());
5471     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5472   } else {
5473     ElemTy = llvm::Type::getInt64Ty(getVMContext());
5474     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5475   }
5476 
5477   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5478 }
5479 
5480 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5481                               llvm::LLVMContext &VMContext) {
5482   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5483   // is called integer-like if its size is less than or equal to one word, and
5484   // the offset of each of its addressable sub-fields is zero.
5485 
5486   uint64_t Size = Context.getTypeSize(Ty);
5487 
5488   // Check that the type fits in a word.
5489   if (Size > 32)
5490     return false;
5491 
5492   // FIXME: Handle vector types!
5493   if (Ty->isVectorType())
5494     return false;
5495 
5496   // Float types are never treated as "integer like".
5497   if (Ty->isRealFloatingType())
5498     return false;
5499 
5500   // If this is a builtin or pointer type then it is ok.
5501   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5502     return true;
5503 
5504   // Small complex integer types are "integer like".
5505   if (const ComplexType *CT = Ty->getAs<ComplexType>())
5506     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5507 
5508   // Single element and zero sized arrays should be allowed, by the definition
5509   // above, but they are not.
5510 
5511   // Otherwise, it must be a record type.
5512   const RecordType *RT = Ty->getAs<RecordType>();
5513   if (!RT) return false;
5514 
5515   // Ignore records with flexible arrays.
5516   const RecordDecl *RD = RT->getDecl();
5517   if (RD->hasFlexibleArrayMember())
5518     return false;
5519 
5520   // Check that all sub-fields are at offset 0, and are themselves "integer
5521   // like".
5522   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5523 
5524   bool HadField = false;
5525   unsigned idx = 0;
5526   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5527        i != e; ++i, ++idx) {
5528     const FieldDecl *FD = *i;
5529 
5530     // Bit-fields are not addressable, we only need to verify they are "integer
5531     // like". We still have to disallow a subsequent non-bitfield, for example:
5532     //   struct { int : 0; int x }
5533     // is non-integer like according to gcc.
5534     if (FD->isBitField()) {
5535       if (!RD->isUnion())
5536         HadField = true;
5537 
5538       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5539         return false;
5540 
5541       continue;
5542     }
5543 
5544     // Check if this field is at offset 0.
5545     if (Layout.getFieldOffset(idx) != 0)
5546       return false;
5547 
5548     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5549       return false;
5550 
5551     // Only allow at most one field in a structure. This doesn't match the
5552     // wording above, but follows gcc in situations with a field following an
5553     // empty structure.
5554     if (!RD->isUnion()) {
5555       if (HadField)
5556         return false;
5557 
5558       HadField = true;
5559     }
5560   }
5561 
5562   return true;
5563 }
5564 
5565 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5566                                           bool isVariadic) const {
5567   bool IsEffectivelyAAPCS_VFP =
5568       (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5569 
5570   if (RetTy->isVoidType())
5571     return ABIArgInfo::getIgnore();
5572 
5573   // Large vector types should be returned via memory.
5574   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5575     return getNaturalAlignIndirect(RetTy);
5576   }
5577 
5578   // __fp16 gets returned as if it were an int or float, but with the top 16
5579   // bits unspecified. This is not done for OpenCL as it handles the half type
5580   // natively, and does not need to interwork with AAPCS code.
5581   if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5582     llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5583       llvm::Type::getFloatTy(getVMContext()) :
5584       llvm::Type::getInt32Ty(getVMContext());
5585     return ABIArgInfo::getDirect(ResType);
5586   }
5587 
5588   if (!isAggregateTypeForABI(RetTy)) {
5589     // Treat an enum type as its underlying type.
5590     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5591       RetTy = EnumTy->getDecl()->getIntegerType();
5592 
5593     return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5594                                             : ABIArgInfo::getDirect();
5595   }
5596 
5597   // Are we following APCS?
5598   if (getABIKind() == APCS) {
5599     if (isEmptyRecord(getContext(), RetTy, false))
5600       return ABIArgInfo::getIgnore();
5601 
5602     // Complex types are all returned as packed integers.
5603     //
5604     // FIXME: Consider using 2 x vector types if the back end handles them
5605     // correctly.
5606     if (RetTy->isAnyComplexType())
5607       return ABIArgInfo::getDirect(llvm::IntegerType::get(
5608           getVMContext(), getContext().getTypeSize(RetTy)));
5609 
5610     // Integer like structures are returned in r0.
5611     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5612       // Return in the smallest viable integer type.
5613       uint64_t Size = getContext().getTypeSize(RetTy);
5614       if (Size <= 8)
5615         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5616       if (Size <= 16)
5617         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5618       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5619     }
5620 
5621     // Otherwise return in memory.
5622     return getNaturalAlignIndirect(RetTy);
5623   }
5624 
5625   // Otherwise this is an AAPCS variant.
5626 
5627   if (isEmptyRecord(getContext(), RetTy, true))
5628     return ABIArgInfo::getIgnore();
5629 
5630   // Check for homogeneous aggregates with AAPCS-VFP.
5631   if (IsEffectivelyAAPCS_VFP) {
5632     const Type *Base = nullptr;
5633     uint64_t Members = 0;
5634     if (isHomogeneousAggregate(RetTy, Base, Members)) {
5635       assert(Base && "Base class should be set for homogeneous aggregate");
5636       // Homogeneous Aggregates are returned directly.
5637       return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5638     }
5639   }
5640 
5641   // Aggregates <= 4 bytes are returned in r0; other aggregates
5642   // are returned indirectly.
5643   uint64_t Size = getContext().getTypeSize(RetTy);
5644   if (Size <= 32) {
5645     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5646     // same size and alignment.
5647     if (getTarget().isRenderScriptTarget()) {
5648       return coerceToIntArray(RetTy, getContext(), getVMContext());
5649     }
5650     if (getDataLayout().isBigEndian())
5651       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5652       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5653 
5654     // Return in the smallest viable integer type.
5655     if (Size <= 8)
5656       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5657     if (Size <= 16)
5658       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5659     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5660   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5661     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5662     llvm::Type *CoerceTy =
5663         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5664     return ABIArgInfo::getDirect(CoerceTy);
5665   }
5666 
5667   return getNaturalAlignIndirect(RetTy);
5668 }
5669 
5670 /// isIllegalVector - check whether Ty is an illegal vector type.
5671 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5672   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5673     if (isAndroid()) {
5674       // Android shipped using Clang 3.1, which supported a slightly different
5675       // vector ABI. The primary differences were that 3-element vector types
5676       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5677       // accepts that legacy behavior for Android only.
5678       // Check whether VT is legal.
5679       unsigned NumElements = VT->getNumElements();
5680       // NumElements should be power of 2 or equal to 3.
5681       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5682         return true;
5683     } else {
5684       // Check whether VT is legal.
5685       unsigned NumElements = VT->getNumElements();
5686       uint64_t Size = getContext().getTypeSize(VT);
5687       // NumElements should be power of 2.
5688       if (!llvm::isPowerOf2_32(NumElements))
5689         return true;
5690       // Size should be greater than 32 bits.
5691       return Size <= 32;
5692     }
5693   }
5694   return false;
5695 }
5696 
5697 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5698   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5699   // double, or 64-bit or 128-bit vectors.
5700   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5701     if (BT->getKind() == BuiltinType::Float ||
5702         BT->getKind() == BuiltinType::Double ||
5703         BT->getKind() == BuiltinType::LongDouble)
5704       return true;
5705   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5706     unsigned VecSize = getContext().getTypeSize(VT);
5707     if (VecSize == 64 || VecSize == 128)
5708       return true;
5709   }
5710   return false;
5711 }
5712 
5713 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5714                                                    uint64_t Members) const {
5715   return Members <= 4;
5716 }
5717 
5718 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5719                               QualType Ty) const {
5720   CharUnits SlotSize = CharUnits::fromQuantity(4);
5721 
5722   // Empty records are ignored for parameter passing purposes.
5723   if (isEmptyRecord(getContext(), Ty, true)) {
5724     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5725     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5726     return Addr;
5727   }
5728 
5729   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5730   CharUnits TyAlignForABI = TyInfo.second;
5731 
5732   // Use indirect if size of the illegal vector is bigger than 16 bytes.
5733   bool IsIndirect = false;
5734   const Type *Base = nullptr;
5735   uint64_t Members = 0;
5736   if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5737     IsIndirect = true;
5738 
5739   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5740   // allocated by the caller.
5741   } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5742              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5743              !isHomogeneousAggregate(Ty, Base, Members)) {
5744     IsIndirect = true;
5745 
5746   // Otherwise, bound the type's ABI alignment.
5747   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5748   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5749   // Our callers should be prepared to handle an under-aligned address.
5750   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5751              getABIKind() == ARMABIInfo::AAPCS) {
5752     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5753     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5754   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5755     // ARMv7k allows type alignment up to 16 bytes.
5756     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5757     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5758   } else {
5759     TyAlignForABI = CharUnits::fromQuantity(4);
5760   }
5761   TyInfo.second = TyAlignForABI;
5762 
5763   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5764                           SlotSize, /*AllowHigherAlign*/ true);
5765 }
5766 
5767 //===----------------------------------------------------------------------===//
5768 // NVPTX ABI Implementation
5769 //===----------------------------------------------------------------------===//
5770 
5771 namespace {
5772 
5773 class NVPTXABIInfo : public ABIInfo {
5774 public:
5775   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5776 
5777   ABIArgInfo classifyReturnType(QualType RetTy) const;
5778   ABIArgInfo classifyArgumentType(QualType Ty) const;
5779 
5780   void computeInfo(CGFunctionInfo &FI) const override;
5781   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5782                     QualType Ty) const override;
5783 };
5784 
5785 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
5786 public:
5787   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5788     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
5789 
5790   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5791                            CodeGen::CodeGenModule &M) const override;
5792 private:
5793   // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5794   // resulting MDNode to the nvvm.annotations MDNode.
5795   static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
5796 };
5797 
5798 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
5799   if (RetTy->isVoidType())
5800     return ABIArgInfo::getIgnore();
5801 
5802   // note: this is different from default ABI
5803   if (!RetTy->isScalarType())
5804     return ABIArgInfo::getDirect();
5805 
5806   // Treat an enum type as its underlying type.
5807   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5808     RetTy = EnumTy->getDecl()->getIntegerType();
5809 
5810   return (RetTy->isPromotableIntegerType() ?
5811           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5812 }
5813 
5814 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
5815   // Treat an enum type as its underlying type.
5816   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5817     Ty = EnumTy->getDecl()->getIntegerType();
5818 
5819   // Return aggregates type as indirect by value
5820   if (isAggregateTypeForABI(Ty))
5821     return getNaturalAlignIndirect(Ty, /* byval */ true);
5822 
5823   return (Ty->isPromotableIntegerType() ?
5824           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5825 }
5826 
5827 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
5828   if (!getCXXABI().classifyReturnType(FI))
5829     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5830   for (auto &I : FI.arguments())
5831     I.info = classifyArgumentType(I.type);
5832 
5833   // Always honor user-specified calling convention.
5834   if (FI.getCallingConvention() != llvm::CallingConv::C)
5835     return;
5836 
5837   FI.setEffectiveCallingConvention(getRuntimeCC());
5838 }
5839 
5840 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5841                                 QualType Ty) const {
5842   llvm_unreachable("NVPTX does not support varargs");
5843 }
5844 
5845 void NVPTXTargetCodeGenInfo::
5846 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5847                     CodeGen::CodeGenModule &M) const{
5848   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5849   if (!FD) return;
5850 
5851   llvm::Function *F = cast<llvm::Function>(GV);
5852 
5853   // Perform special handling in OpenCL mode
5854   if (M.getLangOpts().OpenCL) {
5855     // Use OpenCL function attributes to check for kernel functions
5856     // By default, all functions are device functions
5857     if (FD->hasAttr<OpenCLKernelAttr>()) {
5858       // OpenCL __kernel functions get kernel metadata
5859       // Create !{<func-ref>, metadata !"kernel", i32 1} node
5860       addNVVMMetadata(F, "kernel", 1);
5861       // And kernel functions are not subject to inlining
5862       F->addFnAttr(llvm::Attribute::NoInline);
5863     }
5864   }
5865 
5866   // Perform special handling in CUDA mode.
5867   if (M.getLangOpts().CUDA) {
5868     // CUDA __global__ functions get a kernel metadata entry.  Since
5869     // __global__ functions cannot be called from the device, we do not
5870     // need to set the noinline attribute.
5871     if (FD->hasAttr<CUDAGlobalAttr>()) {
5872       // Create !{<func-ref>, metadata !"kernel", i32 1} node
5873       addNVVMMetadata(F, "kernel", 1);
5874     }
5875     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
5876       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5877       llvm::APSInt MaxThreads(32);
5878       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5879       if (MaxThreads > 0)
5880         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5881 
5882       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5883       // not specified in __launch_bounds__ or if the user specified a 0 value,
5884       // we don't have to add a PTX directive.
5885       if (Attr->getMinBlocks()) {
5886         llvm::APSInt MinBlocks(32);
5887         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5888         if (MinBlocks > 0)
5889           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5890           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
5891       }
5892     }
5893   }
5894 }
5895 
5896 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5897                                              int Operand) {
5898   llvm::Module *M = F->getParent();
5899   llvm::LLVMContext &Ctx = M->getContext();
5900 
5901   // Get "nvvm.annotations" metadata node
5902   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5903 
5904   llvm::Metadata *MDVals[] = {
5905       llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5906       llvm::ConstantAsMetadata::get(
5907           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
5908   // Append metadata to nvvm.annotations
5909   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5910 }
5911 }
5912 
5913 //===----------------------------------------------------------------------===//
5914 // SystemZ ABI Implementation
5915 //===----------------------------------------------------------------------===//
5916 
5917 namespace {
5918 
5919 class SystemZABIInfo : public SwiftABIInfo {
5920   bool HasVector;
5921 
5922 public:
5923   SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5924     : SwiftABIInfo(CGT), HasVector(HV) {}
5925 
5926   bool isPromotableIntegerType(QualType Ty) const;
5927   bool isCompoundType(QualType Ty) const;
5928   bool isVectorArgumentType(QualType Ty) const;
5929   bool isFPArgumentType(QualType Ty) const;
5930   QualType GetSingleElementType(QualType Ty) const;
5931 
5932   ABIArgInfo classifyReturnType(QualType RetTy) const;
5933   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5934 
5935   void computeInfo(CGFunctionInfo &FI) const override {
5936     if (!getCXXABI().classifyReturnType(FI))
5937       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5938     for (auto &I : FI.arguments())
5939       I.info = classifyArgumentType(I.type);
5940   }
5941 
5942   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5943                     QualType Ty) const override;
5944 
5945   bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5946                                     ArrayRef<llvm::Type*> scalars,
5947                                     bool asReturnValue) const override {
5948     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5949   }
5950 };
5951 
5952 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5953 public:
5954   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5955     : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
5956 };
5957 
5958 }
5959 
5960 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5961   // Treat an enum type as its underlying type.
5962   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5963     Ty = EnumTy->getDecl()->getIntegerType();
5964 
5965   // Promotable integer types are required to be promoted by the ABI.
5966   if (Ty->isPromotableIntegerType())
5967     return true;
5968 
5969   // 32-bit values must also be promoted.
5970   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5971     switch (BT->getKind()) {
5972     case BuiltinType::Int:
5973     case BuiltinType::UInt:
5974       return true;
5975     default:
5976       return false;
5977     }
5978   return false;
5979 }
5980 
5981 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5982   return (Ty->isAnyComplexType() ||
5983           Ty->isVectorType() ||
5984           isAggregateTypeForABI(Ty));
5985 }
5986 
5987 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5988   return (HasVector &&
5989           Ty->isVectorType() &&
5990           getContext().getTypeSize(Ty) <= 128);
5991 }
5992 
5993 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5994   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5995     switch (BT->getKind()) {
5996     case BuiltinType::Float:
5997     case BuiltinType::Double:
5998       return true;
5999     default:
6000       return false;
6001     }
6002 
6003   return false;
6004 }
6005 
6006 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6007   if (const RecordType *RT = Ty->getAsStructureType()) {
6008     const RecordDecl *RD = RT->getDecl();
6009     QualType Found;
6010 
6011     // If this is a C++ record, check the bases first.
6012     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6013       for (const auto &I : CXXRD->bases()) {
6014         QualType Base = I.getType();
6015 
6016         // Empty bases don't affect things either way.
6017         if (isEmptyRecord(getContext(), Base, true))
6018           continue;
6019 
6020         if (!Found.isNull())
6021           return Ty;
6022         Found = GetSingleElementType(Base);
6023       }
6024 
6025     // Check the fields.
6026     for (const auto *FD : RD->fields()) {
6027       // For compatibility with GCC, ignore empty bitfields in C++ mode.
6028       // Unlike isSingleElementStruct(), empty structure and array fields
6029       // do count.  So do anonymous bitfields that aren't zero-sized.
6030       if (getContext().getLangOpts().CPlusPlus &&
6031           FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6032         continue;
6033 
6034       // Unlike isSingleElementStruct(), arrays do not count.
6035       // Nested structures still do though.
6036       if (!Found.isNull())
6037         return Ty;
6038       Found = GetSingleElementType(FD->getType());
6039     }
6040 
6041     // Unlike isSingleElementStruct(), trailing padding is allowed.
6042     // An 8-byte aligned struct s { float f; } is passed as a double.
6043     if (!Found.isNull())
6044       return Found;
6045   }
6046 
6047   return Ty;
6048 }
6049 
6050 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6051                                   QualType Ty) const {
6052   // Assume that va_list type is correct; should be pointer to LLVM type:
6053   // struct {
6054   //   i64 __gpr;
6055   //   i64 __fpr;
6056   //   i8 *__overflow_arg_area;
6057   //   i8 *__reg_save_area;
6058   // };
6059 
6060   // Every non-vector argument occupies 8 bytes and is passed by preference
6061   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
6062   // always passed on the stack.
6063   Ty = getContext().getCanonicalType(Ty);
6064   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6065   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6066   llvm::Type *DirectTy = ArgTy;
6067   ABIArgInfo AI = classifyArgumentType(Ty);
6068   bool IsIndirect = AI.isIndirect();
6069   bool InFPRs = false;
6070   bool IsVector = false;
6071   CharUnits UnpaddedSize;
6072   CharUnits DirectAlign;
6073   if (IsIndirect) {
6074     DirectTy = llvm::PointerType::getUnqual(DirectTy);
6075     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6076   } else {
6077     if (AI.getCoerceToType())
6078       ArgTy = AI.getCoerceToType();
6079     InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6080     IsVector = ArgTy->isVectorTy();
6081     UnpaddedSize = TyInfo.first;
6082     DirectAlign = TyInfo.second;
6083   }
6084   CharUnits PaddedSize = CharUnits::fromQuantity(8);
6085   if (IsVector && UnpaddedSize > PaddedSize)
6086     PaddedSize = CharUnits::fromQuantity(16);
6087   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6088 
6089   CharUnits Padding = (PaddedSize - UnpaddedSize);
6090 
6091   llvm::Type *IndexTy = CGF.Int64Ty;
6092   llvm::Value *PaddedSizeV =
6093     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6094 
6095   if (IsVector) {
6096     // Work out the address of a vector argument on the stack.
6097     // Vector arguments are always passed in the high bits of a
6098     // single (8 byte) or double (16 byte) stack slot.
6099     Address OverflowArgAreaPtr =
6100       CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6101                                   "overflow_arg_area_ptr");
6102     Address OverflowArgArea =
6103       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6104               TyInfo.second);
6105     Address MemAddr =
6106       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6107 
6108     // Update overflow_arg_area_ptr pointer
6109     llvm::Value *NewOverflowArgArea =
6110       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6111                             "overflow_arg_area");
6112     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6113 
6114     return MemAddr;
6115   }
6116 
6117   assert(PaddedSize.getQuantity() == 8);
6118 
6119   unsigned MaxRegs, RegCountField, RegSaveIndex;
6120   CharUnits RegPadding;
6121   if (InFPRs) {
6122     MaxRegs = 4; // Maximum of 4 FPR arguments
6123     RegCountField = 1; // __fpr
6124     RegSaveIndex = 16; // save offset for f0
6125     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6126   } else {
6127     MaxRegs = 5; // Maximum of 5 GPR arguments
6128     RegCountField = 0; // __gpr
6129     RegSaveIndex = 2; // save offset for r2
6130     RegPadding = Padding; // values are passed in the low bits of a GPR
6131   }
6132 
6133   Address RegCountPtr = CGF.Builder.CreateStructGEP(
6134       VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6135       "reg_count_ptr");
6136   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6137   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6138   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6139                                                  "fits_in_regs");
6140 
6141   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6142   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6143   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6144   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6145 
6146   // Emit code to load the value if it was passed in registers.
6147   CGF.EmitBlock(InRegBlock);
6148 
6149   // Work out the address of an argument register.
6150   llvm::Value *ScaledRegCount =
6151     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6152   llvm::Value *RegBase =
6153     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6154                                       + RegPadding.getQuantity());
6155   llvm::Value *RegOffset =
6156     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6157   Address RegSaveAreaPtr =
6158       CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6159                                   "reg_save_area_ptr");
6160   llvm::Value *RegSaveArea =
6161     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6162   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6163                                            "raw_reg_addr"),
6164                      PaddedSize);
6165   Address RegAddr =
6166     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6167 
6168   // Update the register count
6169   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6170   llvm::Value *NewRegCount =
6171     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6172   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6173   CGF.EmitBranch(ContBlock);
6174 
6175   // Emit code to load the value if it was passed in memory.
6176   CGF.EmitBlock(InMemBlock);
6177 
6178   // Work out the address of a stack argument.
6179   Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6180       VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6181   Address OverflowArgArea =
6182     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6183             PaddedSize);
6184   Address RawMemAddr =
6185     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6186   Address MemAddr =
6187     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6188 
6189   // Update overflow_arg_area_ptr pointer
6190   llvm::Value *NewOverflowArgArea =
6191     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6192                           "overflow_arg_area");
6193   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6194   CGF.EmitBranch(ContBlock);
6195 
6196   // Return the appropriate result.
6197   CGF.EmitBlock(ContBlock);
6198   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6199                                  MemAddr, InMemBlock, "va_arg.addr");
6200 
6201   if (IsIndirect)
6202     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6203                       TyInfo.second);
6204 
6205   return ResAddr;
6206 }
6207 
6208 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6209   if (RetTy->isVoidType())
6210     return ABIArgInfo::getIgnore();
6211   if (isVectorArgumentType(RetTy))
6212     return ABIArgInfo::getDirect();
6213   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6214     return getNaturalAlignIndirect(RetTy);
6215   return (isPromotableIntegerType(RetTy) ?
6216           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6217 }
6218 
6219 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6220   // Handle the generic C++ ABI.
6221   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6222     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6223 
6224   // Integers and enums are extended to full register width.
6225   if (isPromotableIntegerType(Ty))
6226     return ABIArgInfo::getExtend();
6227 
6228   // Handle vector types and vector-like structure types.  Note that
6229   // as opposed to float-like structure types, we do not allow any
6230   // padding for vector-like structures, so verify the sizes match.
6231   uint64_t Size = getContext().getTypeSize(Ty);
6232   QualType SingleElementTy = GetSingleElementType(Ty);
6233   if (isVectorArgumentType(SingleElementTy) &&
6234       getContext().getTypeSize(SingleElementTy) == Size)
6235     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6236 
6237   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6238   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6239     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6240 
6241   // Handle small structures.
6242   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6243     // Structures with flexible arrays have variable length, so really
6244     // fail the size test above.
6245     const RecordDecl *RD = RT->getDecl();
6246     if (RD->hasFlexibleArrayMember())
6247       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6248 
6249     // The structure is passed as an unextended integer, a float, or a double.
6250     llvm::Type *PassTy;
6251     if (isFPArgumentType(SingleElementTy)) {
6252       assert(Size == 32 || Size == 64);
6253       if (Size == 32)
6254         PassTy = llvm::Type::getFloatTy(getVMContext());
6255       else
6256         PassTy = llvm::Type::getDoubleTy(getVMContext());
6257     } else
6258       PassTy = llvm::IntegerType::get(getVMContext(), Size);
6259     return ABIArgInfo::getDirect(PassTy);
6260   }
6261 
6262   // Non-structure compounds are passed indirectly.
6263   if (isCompoundType(Ty))
6264     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6265 
6266   return ABIArgInfo::getDirect(nullptr);
6267 }
6268 
6269 //===----------------------------------------------------------------------===//
6270 // MSP430 ABI Implementation
6271 //===----------------------------------------------------------------------===//
6272 
6273 namespace {
6274 
6275 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6276 public:
6277   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6278     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6279   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6280                            CodeGen::CodeGenModule &M) const override;
6281 };
6282 
6283 }
6284 
6285 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6286                                                   llvm::GlobalValue *GV,
6287                                              CodeGen::CodeGenModule &M) const {
6288   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6289     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6290       // Handle 'interrupt' attribute:
6291       llvm::Function *F = cast<llvm::Function>(GV);
6292 
6293       // Step 1: Set ISR calling convention.
6294       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6295 
6296       // Step 2: Add attributes goodness.
6297       F->addFnAttr(llvm::Attribute::NoInline);
6298 
6299       // Step 3: Emit ISR vector alias.
6300       unsigned Num = attr->getNumber() / 2;
6301       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6302                                 "__isr_" + Twine(Num), F);
6303     }
6304   }
6305 }
6306 
6307 //===----------------------------------------------------------------------===//
6308 // MIPS ABI Implementation.  This works for both little-endian and
6309 // big-endian variants.
6310 //===----------------------------------------------------------------------===//
6311 
6312 namespace {
6313 class MipsABIInfo : public ABIInfo {
6314   bool IsO32;
6315   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6316   void CoerceToIntArgs(uint64_t TySize,
6317                        SmallVectorImpl<llvm::Type *> &ArgList) const;
6318   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6319   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6320   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6321 public:
6322   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6323     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6324     StackAlignInBytes(IsO32 ? 8 : 16) {}
6325 
6326   ABIArgInfo classifyReturnType(QualType RetTy) const;
6327   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6328   void computeInfo(CGFunctionInfo &FI) const override;
6329   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6330                     QualType Ty) const override;
6331   bool shouldSignExtUnsignedType(QualType Ty) const override;
6332 };
6333 
6334 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6335   unsigned SizeOfUnwindException;
6336 public:
6337   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6338     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6339       SizeOfUnwindException(IsO32 ? 24 : 32) {}
6340 
6341   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6342     return 29;
6343   }
6344 
6345   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6346                            CodeGen::CodeGenModule &CGM) const override {
6347     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6348     if (!FD) return;
6349     llvm::Function *Fn = cast<llvm::Function>(GV);
6350     if (FD->hasAttr<Mips16Attr>()) {
6351       Fn->addFnAttr("mips16");
6352     }
6353     else if (FD->hasAttr<NoMips16Attr>()) {
6354       Fn->addFnAttr("nomips16");
6355     }
6356 
6357     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6358     if (!Attr)
6359       return;
6360 
6361     const char *Kind;
6362     switch (Attr->getInterrupt()) {
6363     case MipsInterruptAttr::eic:     Kind = "eic"; break;
6364     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
6365     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
6366     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
6367     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
6368     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
6369     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
6370     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
6371     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
6372     }
6373 
6374     Fn->addFnAttr("interrupt", Kind);
6375 
6376   }
6377 
6378   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6379                                llvm::Value *Address) const override;
6380 
6381   unsigned getSizeOfUnwindException() const override {
6382     return SizeOfUnwindException;
6383   }
6384 };
6385 }
6386 
6387 void MipsABIInfo::CoerceToIntArgs(
6388     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6389   llvm::IntegerType *IntTy =
6390     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6391 
6392   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6393   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6394     ArgList.push_back(IntTy);
6395 
6396   // If necessary, add one more integer type to ArgList.
6397   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6398 
6399   if (R)
6400     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6401 }
6402 
6403 // In N32/64, an aligned double precision floating point field is passed in
6404 // a register.
6405 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6406   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6407 
6408   if (IsO32) {
6409     CoerceToIntArgs(TySize, ArgList);
6410     return llvm::StructType::get(getVMContext(), ArgList);
6411   }
6412 
6413   if (Ty->isComplexType())
6414     return CGT.ConvertType(Ty);
6415 
6416   const RecordType *RT = Ty->getAs<RecordType>();
6417 
6418   // Unions/vectors are passed in integer registers.
6419   if (!RT || !RT->isStructureOrClassType()) {
6420     CoerceToIntArgs(TySize, ArgList);
6421     return llvm::StructType::get(getVMContext(), ArgList);
6422   }
6423 
6424   const RecordDecl *RD = RT->getDecl();
6425   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6426   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6427 
6428   uint64_t LastOffset = 0;
6429   unsigned idx = 0;
6430   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6431 
6432   // Iterate over fields in the struct/class and check if there are any aligned
6433   // double fields.
6434   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6435        i != e; ++i, ++idx) {
6436     const QualType Ty = i->getType();
6437     const BuiltinType *BT = Ty->getAs<BuiltinType>();
6438 
6439     if (!BT || BT->getKind() != BuiltinType::Double)
6440       continue;
6441 
6442     uint64_t Offset = Layout.getFieldOffset(idx);
6443     if (Offset % 64) // Ignore doubles that are not aligned.
6444       continue;
6445 
6446     // Add ((Offset - LastOffset) / 64) args of type i64.
6447     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6448       ArgList.push_back(I64);
6449 
6450     // Add double type.
6451     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6452     LastOffset = Offset + 64;
6453   }
6454 
6455   CoerceToIntArgs(TySize - LastOffset, IntArgList);
6456   ArgList.append(IntArgList.begin(), IntArgList.end());
6457 
6458   return llvm::StructType::get(getVMContext(), ArgList);
6459 }
6460 
6461 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6462                                         uint64_t Offset) const {
6463   if (OrigOffset + MinABIStackAlignInBytes > Offset)
6464     return nullptr;
6465 
6466   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6467 }
6468 
6469 ABIArgInfo
6470 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6471   Ty = useFirstFieldIfTransparentUnion(Ty);
6472 
6473   uint64_t OrigOffset = Offset;
6474   uint64_t TySize = getContext().getTypeSize(Ty);
6475   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6476 
6477   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6478                    (uint64_t)StackAlignInBytes);
6479   unsigned CurrOffset = llvm::alignTo(Offset, Align);
6480   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6481 
6482   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6483     // Ignore empty aggregates.
6484     if (TySize == 0)
6485       return ABIArgInfo::getIgnore();
6486 
6487     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6488       Offset = OrigOffset + MinABIStackAlignInBytes;
6489       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6490     }
6491 
6492     // If we have reached here, aggregates are passed directly by coercing to
6493     // another structure type. Padding is inserted if the offset of the
6494     // aggregate is unaligned.
6495     ABIArgInfo ArgInfo =
6496         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6497                               getPaddingType(OrigOffset, CurrOffset));
6498     ArgInfo.setInReg(true);
6499     return ArgInfo;
6500   }
6501 
6502   // Treat an enum type as its underlying type.
6503   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6504     Ty = EnumTy->getDecl()->getIntegerType();
6505 
6506   // All integral types are promoted to the GPR width.
6507   if (Ty->isIntegralOrEnumerationType())
6508     return ABIArgInfo::getExtend();
6509 
6510   return ABIArgInfo::getDirect(
6511       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6512 }
6513 
6514 llvm::Type*
6515 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6516   const RecordType *RT = RetTy->getAs<RecordType>();
6517   SmallVector<llvm::Type*, 8> RTList;
6518 
6519   if (RT && RT->isStructureOrClassType()) {
6520     const RecordDecl *RD = RT->getDecl();
6521     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6522     unsigned FieldCnt = Layout.getFieldCount();
6523 
6524     // N32/64 returns struct/classes in floating point registers if the
6525     // following conditions are met:
6526     // 1. The size of the struct/class is no larger than 128-bit.
6527     // 2. The struct/class has one or two fields all of which are floating
6528     //    point types.
6529     // 3. The offset of the first field is zero (this follows what gcc does).
6530     //
6531     // Any other composite results are returned in integer registers.
6532     //
6533     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6534       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6535       for (; b != e; ++b) {
6536         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6537 
6538         if (!BT || !BT->isFloatingPoint())
6539           break;
6540 
6541         RTList.push_back(CGT.ConvertType(b->getType()));
6542       }
6543 
6544       if (b == e)
6545         return llvm::StructType::get(getVMContext(), RTList,
6546                                      RD->hasAttr<PackedAttr>());
6547 
6548       RTList.clear();
6549     }
6550   }
6551 
6552   CoerceToIntArgs(Size, RTList);
6553   return llvm::StructType::get(getVMContext(), RTList);
6554 }
6555 
6556 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6557   uint64_t Size = getContext().getTypeSize(RetTy);
6558 
6559   if (RetTy->isVoidType())
6560     return ABIArgInfo::getIgnore();
6561 
6562   // O32 doesn't treat zero-sized structs differently from other structs.
6563   // However, N32/N64 ignores zero sized return values.
6564   if (!IsO32 && Size == 0)
6565     return ABIArgInfo::getIgnore();
6566 
6567   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6568     if (Size <= 128) {
6569       if (RetTy->isAnyComplexType())
6570         return ABIArgInfo::getDirect();
6571 
6572       // O32 returns integer vectors in registers and N32/N64 returns all small
6573       // aggregates in registers.
6574       if (!IsO32 ||
6575           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6576         ABIArgInfo ArgInfo =
6577             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6578         ArgInfo.setInReg(true);
6579         return ArgInfo;
6580       }
6581     }
6582 
6583     return getNaturalAlignIndirect(RetTy);
6584   }
6585 
6586   // Treat an enum type as its underlying type.
6587   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6588     RetTy = EnumTy->getDecl()->getIntegerType();
6589 
6590   return (RetTy->isPromotableIntegerType() ?
6591           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6592 }
6593 
6594 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6595   ABIArgInfo &RetInfo = FI.getReturnInfo();
6596   if (!getCXXABI().classifyReturnType(FI))
6597     RetInfo = classifyReturnType(FI.getReturnType());
6598 
6599   // Check if a pointer to an aggregate is passed as a hidden argument.
6600   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6601 
6602   for (auto &I : FI.arguments())
6603     I.info = classifyArgumentType(I.type, Offset);
6604 }
6605 
6606 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6607                                QualType OrigTy) const {
6608   QualType Ty = OrigTy;
6609 
6610   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6611   // Pointers are also promoted in the same way but this only matters for N32.
6612   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6613   unsigned PtrWidth = getTarget().getPointerWidth(0);
6614   bool DidPromote = false;
6615   if ((Ty->isIntegerType() &&
6616           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6617       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6618     DidPromote = true;
6619     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6620                                             Ty->isSignedIntegerType());
6621   }
6622 
6623   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6624 
6625   // The alignment of things in the argument area is never larger than
6626   // StackAlignInBytes.
6627   TyInfo.second =
6628     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6629 
6630   // MinABIStackAlignInBytes is the size of argument slots on the stack.
6631   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6632 
6633   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6634                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6635 
6636 
6637   // If there was a promotion, "unpromote" into a temporary.
6638   // TODO: can we just use a pointer into a subset of the original slot?
6639   if (DidPromote) {
6640     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6641     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6642 
6643     // Truncate down to the right width.
6644     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6645                                                  : CGF.IntPtrTy);
6646     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6647     if (OrigTy->isPointerType())
6648       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6649 
6650     CGF.Builder.CreateStore(V, Temp);
6651     Addr = Temp;
6652   }
6653 
6654   return Addr;
6655 }
6656 
6657 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6658   int TySize = getContext().getTypeSize(Ty);
6659 
6660   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6661   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6662     return true;
6663 
6664   return false;
6665 }
6666 
6667 bool
6668 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6669                                                llvm::Value *Address) const {
6670   // This information comes from gcc's implementation, which seems to
6671   // as canonical as it gets.
6672 
6673   // Everything on MIPS is 4 bytes.  Double-precision FP registers
6674   // are aliased to pairs of single-precision FP registers.
6675   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6676 
6677   // 0-31 are the general purpose registers, $0 - $31.
6678   // 32-63 are the floating-point registers, $f0 - $f31.
6679   // 64 and 65 are the multiply/divide registers, $hi and $lo.
6680   // 66 is the (notional, I think) register for signal-handler return.
6681   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6682 
6683   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6684   // They are one bit wide and ignored here.
6685 
6686   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6687   // (coprocessor 1 is the FP unit)
6688   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6689   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6690   // 176-181 are the DSP accumulator registers.
6691   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6692   return false;
6693 }
6694 
6695 //===----------------------------------------------------------------------===//
6696 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6697 // Currently subclassed only to implement custom OpenCL C function attribute
6698 // handling.
6699 //===----------------------------------------------------------------------===//
6700 
6701 namespace {
6702 
6703 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6704 public:
6705   TCETargetCodeGenInfo(CodeGenTypes &CGT)
6706     : DefaultTargetCodeGenInfo(CGT) {}
6707 
6708   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6709                            CodeGen::CodeGenModule &M) const override;
6710 };
6711 
6712 void TCETargetCodeGenInfo::setTargetAttributes(
6713     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6714   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6715   if (!FD) return;
6716 
6717   llvm::Function *F = cast<llvm::Function>(GV);
6718 
6719   if (M.getLangOpts().OpenCL) {
6720     if (FD->hasAttr<OpenCLKernelAttr>()) {
6721       // OpenCL C Kernel functions are not subject to inlining
6722       F->addFnAttr(llvm::Attribute::NoInline);
6723       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6724       if (Attr) {
6725         // Convert the reqd_work_group_size() attributes to metadata.
6726         llvm::LLVMContext &Context = F->getContext();
6727         llvm::NamedMDNode *OpenCLMetadata =
6728             M.getModule().getOrInsertNamedMetadata(
6729                 "opencl.kernel_wg_size_info");
6730 
6731         SmallVector<llvm::Metadata *, 5> Operands;
6732         Operands.push_back(llvm::ConstantAsMetadata::get(F));
6733 
6734         Operands.push_back(
6735             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6736                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6737         Operands.push_back(
6738             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6739                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6740         Operands.push_back(
6741             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6742                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
6743 
6744         // Add a boolean constant operand for "required" (true) or "hint"
6745         // (false) for implementing the work_group_size_hint attr later.
6746         // Currently always true as the hint is not yet implemented.
6747         Operands.push_back(
6748             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
6749         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6750       }
6751     }
6752   }
6753 }
6754 
6755 }
6756 
6757 //===----------------------------------------------------------------------===//
6758 // Hexagon ABI Implementation
6759 //===----------------------------------------------------------------------===//
6760 
6761 namespace {
6762 
6763 class HexagonABIInfo : public ABIInfo {
6764 
6765 
6766 public:
6767   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6768 
6769 private:
6770 
6771   ABIArgInfo classifyReturnType(QualType RetTy) const;
6772   ABIArgInfo classifyArgumentType(QualType RetTy) const;
6773 
6774   void computeInfo(CGFunctionInfo &FI) const override;
6775 
6776   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6777                     QualType Ty) const override;
6778 };
6779 
6780 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6781 public:
6782   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6783     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6784 
6785   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6786     return 29;
6787   }
6788 };
6789 
6790 }
6791 
6792 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
6793   if (!getCXXABI().classifyReturnType(FI))
6794     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6795   for (auto &I : FI.arguments())
6796     I.info = classifyArgumentType(I.type);
6797 }
6798 
6799 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6800   if (!isAggregateTypeForABI(Ty)) {
6801     // Treat an enum type as its underlying type.
6802     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6803       Ty = EnumTy->getDecl()->getIntegerType();
6804 
6805     return (Ty->isPromotableIntegerType() ?
6806             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6807   }
6808 
6809   // Ignore empty records.
6810   if (isEmptyRecord(getContext(), Ty, true))
6811     return ABIArgInfo::getIgnore();
6812 
6813   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6814     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6815 
6816   uint64_t Size = getContext().getTypeSize(Ty);
6817   if (Size > 64)
6818     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6819     // Pass in the smallest viable integer type.
6820   else if (Size > 32)
6821       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6822   else if (Size > 16)
6823       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6824   else if (Size > 8)
6825       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6826   else
6827       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6828 }
6829 
6830 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6831   if (RetTy->isVoidType())
6832     return ABIArgInfo::getIgnore();
6833 
6834   // Large vector types should be returned via memory.
6835   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6836     return getNaturalAlignIndirect(RetTy);
6837 
6838   if (!isAggregateTypeForABI(RetTy)) {
6839     // Treat an enum type as its underlying type.
6840     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6841       RetTy = EnumTy->getDecl()->getIntegerType();
6842 
6843     return (RetTy->isPromotableIntegerType() ?
6844             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6845   }
6846 
6847   if (isEmptyRecord(getContext(), RetTy, true))
6848     return ABIArgInfo::getIgnore();
6849 
6850   // Aggregates <= 8 bytes are returned in r0; other aggregates
6851   // are returned indirectly.
6852   uint64_t Size = getContext().getTypeSize(RetTy);
6853   if (Size <= 64) {
6854     // Return in the smallest viable integer type.
6855     if (Size <= 8)
6856       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6857     if (Size <= 16)
6858       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6859     if (Size <= 32)
6860       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6861     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6862   }
6863 
6864   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
6865 }
6866 
6867 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6868                                   QualType Ty) const {
6869   // FIXME: Someone needs to audit that this handle alignment correctly.
6870   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6871                           getContext().getTypeInfoInChars(Ty),
6872                           CharUnits::fromQuantity(4),
6873                           /*AllowHigherAlign*/ true);
6874 }
6875 
6876 //===----------------------------------------------------------------------===//
6877 // Lanai ABI Implementation
6878 //===----------------------------------------------------------------------===//
6879 
6880 namespace {
6881 class LanaiABIInfo : public DefaultABIInfo {
6882 public:
6883   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6884 
6885   bool shouldUseInReg(QualType Ty, CCState &State) const;
6886 
6887   void computeInfo(CGFunctionInfo &FI) const override {
6888     CCState State(FI.getCallingConvention());
6889     // Lanai uses 4 registers to pass arguments unless the function has the
6890     // regparm attribute set.
6891     if (FI.getHasRegParm()) {
6892       State.FreeRegs = FI.getRegParm();
6893     } else {
6894       State.FreeRegs = 4;
6895     }
6896 
6897     if (!getCXXABI().classifyReturnType(FI))
6898       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6899     for (auto &I : FI.arguments())
6900       I.info = classifyArgumentType(I.type, State);
6901   }
6902 
6903   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
6904   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6905 };
6906 } // end anonymous namespace
6907 
6908 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6909   unsigned Size = getContext().getTypeSize(Ty);
6910   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6911 
6912   if (SizeInRegs == 0)
6913     return false;
6914 
6915   if (SizeInRegs > State.FreeRegs) {
6916     State.FreeRegs = 0;
6917     return false;
6918   }
6919 
6920   State.FreeRegs -= SizeInRegs;
6921 
6922   return true;
6923 }
6924 
6925 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6926                                            CCState &State) const {
6927   if (!ByVal) {
6928     if (State.FreeRegs) {
6929       --State.FreeRegs; // Non-byval indirects just use one pointer.
6930       return getNaturalAlignIndirectInReg(Ty);
6931     }
6932     return getNaturalAlignIndirect(Ty, false);
6933   }
6934 
6935   // Compute the byval alignment.
6936   const unsigned MinABIStackAlignInBytes = 4;
6937   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6938   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6939                                  /*Realign=*/TypeAlign >
6940                                      MinABIStackAlignInBytes);
6941 }
6942 
6943 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6944                                               CCState &State) const {
6945   // Check with the C++ ABI first.
6946   const RecordType *RT = Ty->getAs<RecordType>();
6947   if (RT) {
6948     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6949     if (RAA == CGCXXABI::RAA_Indirect) {
6950       return getIndirectResult(Ty, /*ByVal=*/false, State);
6951     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6952       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6953     }
6954   }
6955 
6956   if (isAggregateTypeForABI(Ty)) {
6957     // Structures with flexible arrays are always indirect.
6958     if (RT && RT->getDecl()->hasFlexibleArrayMember())
6959       return getIndirectResult(Ty, /*ByVal=*/true, State);
6960 
6961     // Ignore empty structs/unions.
6962     if (isEmptyRecord(getContext(), Ty, true))
6963       return ABIArgInfo::getIgnore();
6964 
6965     llvm::LLVMContext &LLVMContext = getVMContext();
6966     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6967     if (SizeInRegs <= State.FreeRegs) {
6968       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6969       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6970       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6971       State.FreeRegs -= SizeInRegs;
6972       return ABIArgInfo::getDirectInReg(Result);
6973     } else {
6974       State.FreeRegs = 0;
6975     }
6976     return getIndirectResult(Ty, true, State);
6977   }
6978 
6979   // Treat an enum type as its underlying type.
6980   if (const auto *EnumTy = Ty->getAs<EnumType>())
6981     Ty = EnumTy->getDecl()->getIntegerType();
6982 
6983   bool InReg = shouldUseInReg(Ty, State);
6984   if (Ty->isPromotableIntegerType()) {
6985     if (InReg)
6986       return ABIArgInfo::getDirectInReg();
6987     return ABIArgInfo::getExtend();
6988   }
6989   if (InReg)
6990     return ABIArgInfo::getDirectInReg();
6991   return ABIArgInfo::getDirect();
6992 }
6993 
6994 namespace {
6995 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6996 public:
6997   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6998       : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6999 };
7000 }
7001 
7002 //===----------------------------------------------------------------------===//
7003 // AMDGPU ABI Implementation
7004 //===----------------------------------------------------------------------===//
7005 
7006 namespace {
7007 
7008 class AMDGPUABIInfo final : public DefaultABIInfo {
7009 public:
7010   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7011 
7012 private:
7013   ABIArgInfo classifyArgumentType(QualType Ty) const;
7014 
7015   void computeInfo(CGFunctionInfo &FI) const override;
7016 };
7017 
7018 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7019   if (!getCXXABI().classifyReturnType(FI))
7020     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7021 
7022   unsigned CC = FI.getCallingConvention();
7023   for (auto &Arg : FI.arguments())
7024     if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7025       Arg.info = classifyArgumentType(Arg.type);
7026     else
7027       Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7028 }
7029 
7030 /// \brief Classify argument of given type \p Ty.
7031 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7032   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7033   if (!StrTy) {
7034     return DefaultABIInfo::classifyArgumentType(Ty);
7035   }
7036 
7037   // Coerce single element structs to its element.
7038   if (StrTy->getNumElements() == 1) {
7039     return ABIArgInfo::getDirect();
7040   }
7041 
7042   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7043   // individual elements, which confuses the Clover OpenCL backend; therefore we
7044   // have to set it to false here. Other args of getDirect() are just defaults.
7045   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7046 }
7047 
7048 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7049 public:
7050   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7051     : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7052   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7053                            CodeGen::CodeGenModule &M) const override;
7054   unsigned getOpenCLKernelCallingConv() const override;
7055 };
7056 
7057 }
7058 
7059 static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7060 
7061 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7062     const Decl *D,
7063     llvm::GlobalValue *GV,
7064     CodeGen::CodeGenModule &M) const {
7065   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7066   if (!FD)
7067     return;
7068 
7069   llvm::Function *F = cast<llvm::Function>(GV);
7070 
7071   if (const auto *Attr = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7072     unsigned Min = Attr->getMin();
7073     unsigned Max = Attr->getMax();
7074 
7075     if (Min != 0) {
7076       assert(Min <= Max && "Min must be less than or equal Max");
7077 
7078       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7079       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7080     } else
7081       assert(Max == 0 && "Max must be zero");
7082   }
7083 
7084   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7085     unsigned Min = Attr->getMin();
7086     unsigned Max = Attr->getMax();
7087 
7088     if (Min != 0) {
7089       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7090 
7091       std::string AttrVal = llvm::utostr(Min);
7092       if (Max != 0)
7093         AttrVal = AttrVal + "," + llvm::utostr(Max);
7094       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7095     } else
7096       assert(Max == 0 && "Max must be zero");
7097   }
7098 
7099   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7100     unsigned NumSGPR = Attr->getNumSGPR();
7101 
7102     if (NumSGPR != 0)
7103       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7104   }
7105 
7106   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7107     uint32_t NumVGPR = Attr->getNumVGPR();
7108 
7109     if (NumVGPR != 0)
7110       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7111   }
7112 
7113   appendOpenCLVersionMD(M);
7114 }
7115 
7116 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7117   return llvm::CallingConv::AMDGPU_KERNEL;
7118 }
7119 
7120 //===----------------------------------------------------------------------===//
7121 // SPARC v8 ABI Implementation.
7122 // Based on the SPARC Compliance Definition version 2.4.1.
7123 //
7124 // Ensures that complex values are passed in registers.
7125 //
7126 namespace {
7127 class SparcV8ABIInfo : public DefaultABIInfo {
7128 public:
7129   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7130 
7131 private:
7132   ABIArgInfo classifyReturnType(QualType RetTy) const;
7133   void computeInfo(CGFunctionInfo &FI) const override;
7134 };
7135 } // end anonymous namespace
7136 
7137 
7138 ABIArgInfo
7139 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7140   if (Ty->isAnyComplexType()) {
7141     return ABIArgInfo::getDirect();
7142   }
7143   else {
7144     return DefaultABIInfo::classifyReturnType(Ty);
7145   }
7146 }
7147 
7148 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7149 
7150   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7151   for (auto &Arg : FI.arguments())
7152     Arg.info = classifyArgumentType(Arg.type);
7153 }
7154 
7155 namespace {
7156 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7157 public:
7158   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7159     : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7160 };
7161 } // end anonymous namespace
7162 
7163 //===----------------------------------------------------------------------===//
7164 // SPARC v9 ABI Implementation.
7165 // Based on the SPARC Compliance Definition version 2.4.1.
7166 //
7167 // Function arguments a mapped to a nominal "parameter array" and promoted to
7168 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7169 // the array, structs larger than 16 bytes are passed indirectly.
7170 //
7171 // One case requires special care:
7172 //
7173 //   struct mixed {
7174 //     int i;
7175 //     float f;
7176 //   };
7177 //
7178 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7179 // parameter array, but the int is passed in an integer register, and the float
7180 // is passed in a floating point register. This is represented as two arguments
7181 // with the LLVM IR inreg attribute:
7182 //
7183 //   declare void f(i32 inreg %i, float inreg %f)
7184 //
7185 // The code generator will only allocate 4 bytes from the parameter array for
7186 // the inreg arguments. All other arguments are allocated a multiple of 8
7187 // bytes.
7188 //
7189 namespace {
7190 class SparcV9ABIInfo : public ABIInfo {
7191 public:
7192   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7193 
7194 private:
7195   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7196   void computeInfo(CGFunctionInfo &FI) const override;
7197   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7198                     QualType Ty) const override;
7199 
7200   // Coercion type builder for structs passed in registers. The coercion type
7201   // serves two purposes:
7202   //
7203   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7204   //    in registers.
7205   // 2. Expose aligned floating point elements as first-level elements, so the
7206   //    code generator knows to pass them in floating point registers.
7207   //
7208   // We also compute the InReg flag which indicates that the struct contains
7209   // aligned 32-bit floats.
7210   //
7211   struct CoerceBuilder {
7212     llvm::LLVMContext &Context;
7213     const llvm::DataLayout &DL;
7214     SmallVector<llvm::Type*, 8> Elems;
7215     uint64_t Size;
7216     bool InReg;
7217 
7218     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7219       : Context(c), DL(dl), Size(0), InReg(false) {}
7220 
7221     // Pad Elems with integers until Size is ToSize.
7222     void pad(uint64_t ToSize) {
7223       assert(ToSize >= Size && "Cannot remove elements");
7224       if (ToSize == Size)
7225         return;
7226 
7227       // Finish the current 64-bit word.
7228       uint64_t Aligned = llvm::alignTo(Size, 64);
7229       if (Aligned > Size && Aligned <= ToSize) {
7230         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7231         Size = Aligned;
7232       }
7233 
7234       // Add whole 64-bit words.
7235       while (Size + 64 <= ToSize) {
7236         Elems.push_back(llvm::Type::getInt64Ty(Context));
7237         Size += 64;
7238       }
7239 
7240       // Final in-word padding.
7241       if (Size < ToSize) {
7242         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7243         Size = ToSize;
7244       }
7245     }
7246 
7247     // Add a floating point element at Offset.
7248     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7249       // Unaligned floats are treated as integers.
7250       if (Offset % Bits)
7251         return;
7252       // The InReg flag is only required if there are any floats < 64 bits.
7253       if (Bits < 64)
7254         InReg = true;
7255       pad(Offset);
7256       Elems.push_back(Ty);
7257       Size = Offset + Bits;
7258     }
7259 
7260     // Add a struct type to the coercion type, starting at Offset (in bits).
7261     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7262       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7263       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7264         llvm::Type *ElemTy = StrTy->getElementType(i);
7265         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7266         switch (ElemTy->getTypeID()) {
7267         case llvm::Type::StructTyID:
7268           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7269           break;
7270         case llvm::Type::FloatTyID:
7271           addFloat(ElemOffset, ElemTy, 32);
7272           break;
7273         case llvm::Type::DoubleTyID:
7274           addFloat(ElemOffset, ElemTy, 64);
7275           break;
7276         case llvm::Type::FP128TyID:
7277           addFloat(ElemOffset, ElemTy, 128);
7278           break;
7279         case llvm::Type::PointerTyID:
7280           if (ElemOffset % 64 == 0) {
7281             pad(ElemOffset);
7282             Elems.push_back(ElemTy);
7283             Size += 64;
7284           }
7285           break;
7286         default:
7287           break;
7288         }
7289       }
7290     }
7291 
7292     // Check if Ty is a usable substitute for the coercion type.
7293     bool isUsableType(llvm::StructType *Ty) const {
7294       return llvm::makeArrayRef(Elems) == Ty->elements();
7295     }
7296 
7297     // Get the coercion type as a literal struct type.
7298     llvm::Type *getType() const {
7299       if (Elems.size() == 1)
7300         return Elems.front();
7301       else
7302         return llvm::StructType::get(Context, Elems);
7303     }
7304   };
7305 };
7306 } // end anonymous namespace
7307 
7308 ABIArgInfo
7309 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7310   if (Ty->isVoidType())
7311     return ABIArgInfo::getIgnore();
7312 
7313   uint64_t Size = getContext().getTypeSize(Ty);
7314 
7315   // Anything too big to fit in registers is passed with an explicit indirect
7316   // pointer / sret pointer.
7317   if (Size > SizeLimit)
7318     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7319 
7320   // Treat an enum type as its underlying type.
7321   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7322     Ty = EnumTy->getDecl()->getIntegerType();
7323 
7324   // Integer types smaller than a register are extended.
7325   if (Size < 64 && Ty->isIntegerType())
7326     return ABIArgInfo::getExtend();
7327 
7328   // Other non-aggregates go in registers.
7329   if (!isAggregateTypeForABI(Ty))
7330     return ABIArgInfo::getDirect();
7331 
7332   // If a C++ object has either a non-trivial copy constructor or a non-trivial
7333   // destructor, it is passed with an explicit indirect pointer / sret pointer.
7334   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7335     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7336 
7337   // This is a small aggregate type that should be passed in registers.
7338   // Build a coercion type from the LLVM struct type.
7339   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7340   if (!StrTy)
7341     return ABIArgInfo::getDirect();
7342 
7343   CoerceBuilder CB(getVMContext(), getDataLayout());
7344   CB.addStruct(0, StrTy);
7345   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7346 
7347   // Try to use the original type for coercion.
7348   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7349 
7350   if (CB.InReg)
7351     return ABIArgInfo::getDirectInReg(CoerceTy);
7352   else
7353     return ABIArgInfo::getDirect(CoerceTy);
7354 }
7355 
7356 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7357                                   QualType Ty) const {
7358   ABIArgInfo AI = classifyType(Ty, 16 * 8);
7359   llvm::Type *ArgTy = CGT.ConvertType(Ty);
7360   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7361     AI.setCoerceToType(ArgTy);
7362 
7363   CharUnits SlotSize = CharUnits::fromQuantity(8);
7364 
7365   CGBuilderTy &Builder = CGF.Builder;
7366   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7367   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7368 
7369   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7370 
7371   Address ArgAddr = Address::invalid();
7372   CharUnits Stride;
7373   switch (AI.getKind()) {
7374   case ABIArgInfo::Expand:
7375   case ABIArgInfo::CoerceAndExpand:
7376   case ABIArgInfo::InAlloca:
7377     llvm_unreachable("Unsupported ABI kind for va_arg");
7378 
7379   case ABIArgInfo::Extend: {
7380     Stride = SlotSize;
7381     CharUnits Offset = SlotSize - TypeInfo.first;
7382     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7383     break;
7384   }
7385 
7386   case ABIArgInfo::Direct: {
7387     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7388     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7389     ArgAddr = Addr;
7390     break;
7391   }
7392 
7393   case ABIArgInfo::Indirect:
7394     Stride = SlotSize;
7395     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7396     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7397                       TypeInfo.second);
7398     break;
7399 
7400   case ABIArgInfo::Ignore:
7401     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7402   }
7403 
7404   // Update VAList.
7405   llvm::Value *NextPtr =
7406     Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7407   Builder.CreateStore(NextPtr, VAListAddr);
7408 
7409   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7410 }
7411 
7412 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7413   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7414   for (auto &I : FI.arguments())
7415     I.info = classifyType(I.type, 16 * 8);
7416 }
7417 
7418 namespace {
7419 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7420 public:
7421   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7422     : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7423 
7424   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7425     return 14;
7426   }
7427 
7428   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7429                                llvm::Value *Address) const override;
7430 };
7431 } // end anonymous namespace
7432 
7433 bool
7434 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7435                                                 llvm::Value *Address) const {
7436   // This is calculated from the LLVM and GCC tables and verified
7437   // against gcc output.  AFAIK all ABIs use the same encoding.
7438 
7439   CodeGen::CGBuilderTy &Builder = CGF.Builder;
7440 
7441   llvm::IntegerType *i8 = CGF.Int8Ty;
7442   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7443   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7444 
7445   // 0-31: the 8-byte general-purpose registers
7446   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7447 
7448   // 32-63: f0-31, the 4-byte floating-point registers
7449   AssignToArrayRange(Builder, Address, Four8, 32, 63);
7450 
7451   //   Y   = 64
7452   //   PSR = 65
7453   //   WIM = 66
7454   //   TBR = 67
7455   //   PC  = 68
7456   //   NPC = 69
7457   //   FSR = 70
7458   //   CSR = 71
7459   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7460 
7461   // 72-87: d0-15, the 8-byte floating-point registers
7462   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7463 
7464   return false;
7465 }
7466 
7467 
7468 //===----------------------------------------------------------------------===//
7469 // XCore ABI Implementation
7470 //===----------------------------------------------------------------------===//
7471 
7472 namespace {
7473 
7474 /// A SmallStringEnc instance is used to build up the TypeString by passing
7475 /// it by reference between functions that append to it.
7476 typedef llvm::SmallString<128> SmallStringEnc;
7477 
7478 /// TypeStringCache caches the meta encodings of Types.
7479 ///
7480 /// The reason for caching TypeStrings is two fold:
7481 ///   1. To cache a type's encoding for later uses;
7482 ///   2. As a means to break recursive member type inclusion.
7483 ///
7484 /// A cache Entry can have a Status of:
7485 ///   NonRecursive:   The type encoding is not recursive;
7486 ///   Recursive:      The type encoding is recursive;
7487 ///   Incomplete:     An incomplete TypeString;
7488 ///   IncompleteUsed: An incomplete TypeString that has been used in a
7489 ///                   Recursive type encoding.
7490 ///
7491 /// A NonRecursive entry will have all of its sub-members expanded as fully
7492 /// as possible. Whilst it may contain types which are recursive, the type
7493 /// itself is not recursive and thus its encoding may be safely used whenever
7494 /// the type is encountered.
7495 ///
7496 /// A Recursive entry will have all of its sub-members expanded as fully as
7497 /// possible. The type itself is recursive and it may contain other types which
7498 /// are recursive. The Recursive encoding must not be used during the expansion
7499 /// of a recursive type's recursive branch. For simplicity the code uses
7500 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7501 ///
7502 /// An Incomplete entry is always a RecordType and only encodes its
7503 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7504 /// are placed into the cache during type expansion as a means to identify and
7505 /// handle recursive inclusion of types as sub-members. If there is recursion
7506 /// the entry becomes IncompleteUsed.
7507 ///
7508 /// During the expansion of a RecordType's members:
7509 ///
7510 ///   If the cache contains a NonRecursive encoding for the member type, the
7511 ///   cached encoding is used;
7512 ///
7513 ///   If the cache contains a Recursive encoding for the member type, the
7514 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
7515 ///
7516 ///   If the member is a RecordType, an Incomplete encoding is placed into the
7517 ///   cache to break potential recursive inclusion of itself as a sub-member;
7518 ///
7519 ///   Once a member RecordType has been expanded, its temporary incomplete
7520 ///   entry is removed from the cache. If a Recursive encoding was swapped out
7521 ///   it is swapped back in;
7522 ///
7523 ///   If an incomplete entry is used to expand a sub-member, the incomplete
7524 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
7525 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
7526 ///
7527 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
7528 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
7529 ///   Else the member is part of a recursive type and thus the recursion has
7530 ///   been exited too soon for the encoding to be correct for the member.
7531 ///
7532 class TypeStringCache {
7533   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7534   struct Entry {
7535     std::string Str;     // The encoded TypeString for the type.
7536     enum Status State;   // Information about the encoding in 'Str'.
7537     std::string Swapped; // A temporary place holder for a Recursive encoding
7538                          // during the expansion of RecordType's members.
7539   };
7540   std::map<const IdentifierInfo *, struct Entry> Map;
7541   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
7542   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7543 public:
7544   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7545   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7546   bool removeIncomplete(const IdentifierInfo *ID);
7547   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7548                      bool IsRecursive);
7549   StringRef lookupStr(const IdentifierInfo *ID);
7550 };
7551 
7552 /// TypeString encodings for enum & union fields must be order.
7553 /// FieldEncoding is a helper for this ordering process.
7554 class FieldEncoding {
7555   bool HasName;
7556   std::string Enc;
7557 public:
7558   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7559   StringRef str() { return Enc; }
7560   bool operator<(const FieldEncoding &rhs) const {
7561     if (HasName != rhs.HasName) return HasName;
7562     return Enc < rhs.Enc;
7563   }
7564 };
7565 
7566 class XCoreABIInfo : public DefaultABIInfo {
7567 public:
7568   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7569   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7570                     QualType Ty) const override;
7571 };
7572 
7573 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7574   mutable TypeStringCache TSC;
7575 public:
7576   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7577     :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7578   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7579                     CodeGen::CodeGenModule &M) const override;
7580 };
7581 
7582 } // End anonymous namespace.
7583 
7584 // TODO: this implementation is likely now redundant with the default
7585 // EmitVAArg.
7586 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7587                                 QualType Ty) const {
7588   CGBuilderTy &Builder = CGF.Builder;
7589 
7590   // Get the VAList.
7591   CharUnits SlotSize = CharUnits::fromQuantity(4);
7592   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7593 
7594   // Handle the argument.
7595   ABIArgInfo AI = classifyArgumentType(Ty);
7596   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7597   llvm::Type *ArgTy = CGT.ConvertType(Ty);
7598   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7599     AI.setCoerceToType(ArgTy);
7600   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7601 
7602   Address Val = Address::invalid();
7603   CharUnits ArgSize = CharUnits::Zero();
7604   switch (AI.getKind()) {
7605   case ABIArgInfo::Expand:
7606   case ABIArgInfo::CoerceAndExpand:
7607   case ABIArgInfo::InAlloca:
7608     llvm_unreachable("Unsupported ABI kind for va_arg");
7609   case ABIArgInfo::Ignore:
7610     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7611     ArgSize = CharUnits::Zero();
7612     break;
7613   case ABIArgInfo::Extend:
7614   case ABIArgInfo::Direct:
7615     Val = Builder.CreateBitCast(AP, ArgPtrTy);
7616     ArgSize = CharUnits::fromQuantity(
7617                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7618     ArgSize = ArgSize.alignTo(SlotSize);
7619     break;
7620   case ABIArgInfo::Indirect:
7621     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7622     Val = Address(Builder.CreateLoad(Val), TypeAlign);
7623     ArgSize = SlotSize;
7624     break;
7625   }
7626 
7627   // Increment the VAList.
7628   if (!ArgSize.isZero()) {
7629     llvm::Value *APN =
7630       Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7631     Builder.CreateStore(APN, VAListAddr);
7632   }
7633 
7634   return Val;
7635 }
7636 
7637 /// During the expansion of a RecordType, an incomplete TypeString is placed
7638 /// into the cache as a means to identify and break recursion.
7639 /// If there is a Recursive encoding in the cache, it is swapped out and will
7640 /// be reinserted by removeIncomplete().
7641 /// All other types of encoding should have been used rather than arriving here.
7642 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7643                                     std::string StubEnc) {
7644   if (!ID)
7645     return;
7646   Entry &E = Map[ID];
7647   assert( (E.Str.empty() || E.State == Recursive) &&
7648          "Incorrectly use of addIncomplete");
7649   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7650   E.Swapped.swap(E.Str); // swap out the Recursive
7651   E.Str.swap(StubEnc);
7652   E.State = Incomplete;
7653   ++IncompleteCount;
7654 }
7655 
7656 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7657 /// must be removed from the cache.
7658 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7659 /// Returns true if the RecordType was defined recursively.
7660 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7661   if (!ID)
7662     return false;
7663   auto I = Map.find(ID);
7664   assert(I != Map.end() && "Entry not present");
7665   Entry &E = I->second;
7666   assert( (E.State == Incomplete ||
7667            E.State == IncompleteUsed) &&
7668          "Entry must be an incomplete type");
7669   bool IsRecursive = false;
7670   if (E.State == IncompleteUsed) {
7671     // We made use of our Incomplete encoding, thus we are recursive.
7672     IsRecursive = true;
7673     --IncompleteUsedCount;
7674   }
7675   if (E.Swapped.empty())
7676     Map.erase(I);
7677   else {
7678     // Swap the Recursive back.
7679     E.Swapped.swap(E.Str);
7680     E.Swapped.clear();
7681     E.State = Recursive;
7682   }
7683   --IncompleteCount;
7684   return IsRecursive;
7685 }
7686 
7687 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7688 /// Recursive (viz: all sub-members were expanded as fully as possible).
7689 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7690                                     bool IsRecursive) {
7691   if (!ID || IncompleteUsedCount)
7692     return; // No key or it is is an incomplete sub-type so don't add.
7693   Entry &E = Map[ID];
7694   if (IsRecursive && !E.Str.empty()) {
7695     assert(E.State==Recursive && E.Str.size() == Str.size() &&
7696            "This is not the same Recursive entry");
7697     // The parent container was not recursive after all, so we could have used
7698     // this Recursive sub-member entry after all, but we assumed the worse when
7699     // we started viz: IncompleteCount!=0.
7700     return;
7701   }
7702   assert(E.Str.empty() && "Entry already present");
7703   E.Str = Str.str();
7704   E.State = IsRecursive? Recursive : NonRecursive;
7705 }
7706 
7707 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
7708 /// are recursively expanding a type (IncompleteCount != 0) and the cached
7709 /// encoding is Recursive, return an empty StringRef.
7710 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7711   if (!ID)
7712     return StringRef();   // We have no key.
7713   auto I = Map.find(ID);
7714   if (I == Map.end())
7715     return StringRef();   // We have no encoding.
7716   Entry &E = I->second;
7717   if (E.State == Recursive && IncompleteCount)
7718     return StringRef();   // We don't use Recursive encodings for member types.
7719 
7720   if (E.State == Incomplete) {
7721     // The incomplete type is being used to break out of recursion.
7722     E.State = IncompleteUsed;
7723     ++IncompleteUsedCount;
7724   }
7725   return E.Str;
7726 }
7727 
7728 /// The XCore ABI includes a type information section that communicates symbol
7729 /// type information to the linker. The linker uses this information to verify
7730 /// safety/correctness of things such as array bound and pointers et al.
7731 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
7732 /// This type information (TypeString) is emitted into meta data for all global
7733 /// symbols: definitions, declarations, functions & variables.
7734 ///
7735 /// The TypeString carries type, qualifier, name, size & value details.
7736 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
7737 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
7738 /// The output is tested by test/CodeGen/xcore-stringtype.c.
7739 ///
7740 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7741                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7742 
7743 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7744 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7745                                           CodeGen::CodeGenModule &CGM) const {
7746   SmallStringEnc Enc;
7747   if (getTypeString(Enc, D, CGM, TSC)) {
7748     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7749     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7750                                 llvm::MDString::get(Ctx, Enc.str())};
7751     llvm::NamedMDNode *MD =
7752       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7753     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7754   }
7755 }
7756 
7757 //===----------------------------------------------------------------------===//
7758 // SPIR ABI Implementation
7759 //===----------------------------------------------------------------------===//
7760 
7761 namespace {
7762 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7763 public:
7764   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7765     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7766   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7767                     CodeGen::CodeGenModule &M) const override;
7768   unsigned getOpenCLKernelCallingConv() const override;
7769 };
7770 } // End anonymous namespace.
7771 
7772 /// Emit SPIR specific metadata: OpenCL and SPIR version.
7773 void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7774                                          CodeGen::CodeGenModule &CGM) const {
7775   llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7776   llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7777   llvm::Module &M = CGM.getModule();
7778   // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7779   // opencl.spir.version named metadata.
7780   llvm::Metadata *SPIRVerElts[] = {
7781       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7782       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7783   llvm::NamedMDNode *SPIRVerMD =
7784       M.getOrInsertNamedMetadata("opencl.spir.version");
7785   SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7786   appendOpenCLVersionMD(CGM);
7787 }
7788 
7789 static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
7790   llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7791   llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7792   llvm::Module &M = CGM.getModule();
7793   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7794   // opencl.ocl.version named metadata node.
7795   llvm::Metadata *OCLVerElts[] = {
7796       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7797           Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7798       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7799           Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7800   llvm::NamedMDNode *OCLVerMD =
7801       M.getOrInsertNamedMetadata("opencl.ocl.version");
7802   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7803 }
7804 
7805 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7806   return llvm::CallingConv::SPIR_KERNEL;
7807 }
7808 
7809 static bool appendType(SmallStringEnc &Enc, QualType QType,
7810                        const CodeGen::CodeGenModule &CGM,
7811                        TypeStringCache &TSC);
7812 
7813 /// Helper function for appendRecordType().
7814 /// Builds a SmallVector containing the encoded field types in declaration
7815 /// order.
7816 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7817                              const RecordDecl *RD,
7818                              const CodeGen::CodeGenModule &CGM,
7819                              TypeStringCache &TSC) {
7820   for (const auto *Field : RD->fields()) {
7821     SmallStringEnc Enc;
7822     Enc += "m(";
7823     Enc += Field->getName();
7824     Enc += "){";
7825     if (Field->isBitField()) {
7826       Enc += "b(";
7827       llvm::raw_svector_ostream OS(Enc);
7828       OS << Field->getBitWidthValue(CGM.getContext());
7829       Enc += ':';
7830     }
7831     if (!appendType(Enc, Field->getType(), CGM, TSC))
7832       return false;
7833     if (Field->isBitField())
7834       Enc += ')';
7835     Enc += '}';
7836     FE.emplace_back(!Field->getName().empty(), Enc);
7837   }
7838   return true;
7839 }
7840 
7841 /// Appends structure and union types to Enc and adds encoding to cache.
7842 /// Recursively calls appendType (via extractFieldType) for each field.
7843 /// Union types have their fields ordered according to the ABI.
7844 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7845                              const CodeGen::CodeGenModule &CGM,
7846                              TypeStringCache &TSC, const IdentifierInfo *ID) {
7847   // Append the cached TypeString if we have one.
7848   StringRef TypeString = TSC.lookupStr(ID);
7849   if (!TypeString.empty()) {
7850     Enc += TypeString;
7851     return true;
7852   }
7853 
7854   // Start to emit an incomplete TypeString.
7855   size_t Start = Enc.size();
7856   Enc += (RT->isUnionType()? 'u' : 's');
7857   Enc += '(';
7858   if (ID)
7859     Enc += ID->getName();
7860   Enc += "){";
7861 
7862   // We collect all encoded fields and order as necessary.
7863   bool IsRecursive = false;
7864   const RecordDecl *RD = RT->getDecl()->getDefinition();
7865   if (RD && !RD->field_empty()) {
7866     // An incomplete TypeString stub is placed in the cache for this RecordType
7867     // so that recursive calls to this RecordType will use it whilst building a
7868     // complete TypeString for this RecordType.
7869     SmallVector<FieldEncoding, 16> FE;
7870     std::string StubEnc(Enc.substr(Start).str());
7871     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
7872     TSC.addIncomplete(ID, std::move(StubEnc));
7873     if (!extractFieldType(FE, RD, CGM, TSC)) {
7874       (void) TSC.removeIncomplete(ID);
7875       return false;
7876     }
7877     IsRecursive = TSC.removeIncomplete(ID);
7878     // The ABI requires unions to be sorted but not structures.
7879     // See FieldEncoding::operator< for sort algorithm.
7880     if (RT->isUnionType())
7881       std::sort(FE.begin(), FE.end());
7882     // We can now complete the TypeString.
7883     unsigned E = FE.size();
7884     for (unsigned I = 0; I != E; ++I) {
7885       if (I)
7886         Enc += ',';
7887       Enc += FE[I].str();
7888     }
7889   }
7890   Enc += '}';
7891   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7892   return true;
7893 }
7894 
7895 /// Appends enum types to Enc and adds the encoding to the cache.
7896 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7897                            TypeStringCache &TSC,
7898                            const IdentifierInfo *ID) {
7899   // Append the cached TypeString if we have one.
7900   StringRef TypeString = TSC.lookupStr(ID);
7901   if (!TypeString.empty()) {
7902     Enc += TypeString;
7903     return true;
7904   }
7905 
7906   size_t Start = Enc.size();
7907   Enc += "e(";
7908   if (ID)
7909     Enc += ID->getName();
7910   Enc += "){";
7911 
7912   // We collect all encoded enumerations and order them alphanumerically.
7913   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
7914     SmallVector<FieldEncoding, 16> FE;
7915     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7916          ++I) {
7917       SmallStringEnc EnumEnc;
7918       EnumEnc += "m(";
7919       EnumEnc += I->getName();
7920       EnumEnc += "){";
7921       I->getInitVal().toString(EnumEnc);
7922       EnumEnc += '}';
7923       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7924     }
7925     std::sort(FE.begin(), FE.end());
7926     unsigned E = FE.size();
7927     for (unsigned I = 0; I != E; ++I) {
7928       if (I)
7929         Enc += ',';
7930       Enc += FE[I].str();
7931     }
7932   }
7933   Enc += '}';
7934   TSC.addIfComplete(ID, Enc.substr(Start), false);
7935   return true;
7936 }
7937 
7938 /// Appends type's qualifier to Enc.
7939 /// This is done prior to appending the type's encoding.
7940 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7941   // Qualifiers are emitted in alphabetical order.
7942   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
7943   int Lookup = 0;
7944   if (QT.isConstQualified())
7945     Lookup += 1<<0;
7946   if (QT.isRestrictQualified())
7947     Lookup += 1<<1;
7948   if (QT.isVolatileQualified())
7949     Lookup += 1<<2;
7950   Enc += Table[Lookup];
7951 }
7952 
7953 /// Appends built-in types to Enc.
7954 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7955   const char *EncType;
7956   switch (BT->getKind()) {
7957     case BuiltinType::Void:
7958       EncType = "0";
7959       break;
7960     case BuiltinType::Bool:
7961       EncType = "b";
7962       break;
7963     case BuiltinType::Char_U:
7964       EncType = "uc";
7965       break;
7966     case BuiltinType::UChar:
7967       EncType = "uc";
7968       break;
7969     case BuiltinType::SChar:
7970       EncType = "sc";
7971       break;
7972     case BuiltinType::UShort:
7973       EncType = "us";
7974       break;
7975     case BuiltinType::Short:
7976       EncType = "ss";
7977       break;
7978     case BuiltinType::UInt:
7979       EncType = "ui";
7980       break;
7981     case BuiltinType::Int:
7982       EncType = "si";
7983       break;
7984     case BuiltinType::ULong:
7985       EncType = "ul";
7986       break;
7987     case BuiltinType::Long:
7988       EncType = "sl";
7989       break;
7990     case BuiltinType::ULongLong:
7991       EncType = "ull";
7992       break;
7993     case BuiltinType::LongLong:
7994       EncType = "sll";
7995       break;
7996     case BuiltinType::Float:
7997       EncType = "ft";
7998       break;
7999     case BuiltinType::Double:
8000       EncType = "d";
8001       break;
8002     case BuiltinType::LongDouble:
8003       EncType = "ld";
8004       break;
8005     default:
8006       return false;
8007   }
8008   Enc += EncType;
8009   return true;
8010 }
8011 
8012 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8013 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8014                               const CodeGen::CodeGenModule &CGM,
8015                               TypeStringCache &TSC) {
8016   Enc += "p(";
8017   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8018     return false;
8019   Enc += ')';
8020   return true;
8021 }
8022 
8023 /// Appends array encoding to Enc before calling appendType for the element.
8024 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8025                             const ArrayType *AT,
8026                             const CodeGen::CodeGenModule &CGM,
8027                             TypeStringCache &TSC, StringRef NoSizeEnc) {
8028   if (AT->getSizeModifier() != ArrayType::Normal)
8029     return false;
8030   Enc += "a(";
8031   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8032     CAT->getSize().toStringUnsigned(Enc);
8033   else
8034     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8035   Enc += ':';
8036   // The Qualifiers should be attached to the type rather than the array.
8037   appendQualifier(Enc, QT);
8038   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8039     return false;
8040   Enc += ')';
8041   return true;
8042 }
8043 
8044 /// Appends a function encoding to Enc, calling appendType for the return type
8045 /// and the arguments.
8046 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8047                              const CodeGen::CodeGenModule &CGM,
8048                              TypeStringCache &TSC) {
8049   Enc += "f{";
8050   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8051     return false;
8052   Enc += "}(";
8053   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8054     // N.B. we are only interested in the adjusted param types.
8055     auto I = FPT->param_type_begin();
8056     auto E = FPT->param_type_end();
8057     if (I != E) {
8058       do {
8059         if (!appendType(Enc, *I, CGM, TSC))
8060           return false;
8061         ++I;
8062         if (I != E)
8063           Enc += ',';
8064       } while (I != E);
8065       if (FPT->isVariadic())
8066         Enc += ",va";
8067     } else {
8068       if (FPT->isVariadic())
8069         Enc += "va";
8070       else
8071         Enc += '0';
8072     }
8073   }
8074   Enc += ')';
8075   return true;
8076 }
8077 
8078 /// Handles the type's qualifier before dispatching a call to handle specific
8079 /// type encodings.
8080 static bool appendType(SmallStringEnc &Enc, QualType QType,
8081                        const CodeGen::CodeGenModule &CGM,
8082                        TypeStringCache &TSC) {
8083 
8084   QualType QT = QType.getCanonicalType();
8085 
8086   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8087     // The Qualifiers should be attached to the type rather than the array.
8088     // Thus we don't call appendQualifier() here.
8089     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8090 
8091   appendQualifier(Enc, QT);
8092 
8093   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8094     return appendBuiltinType(Enc, BT);
8095 
8096   if (const PointerType *PT = QT->getAs<PointerType>())
8097     return appendPointerType(Enc, PT, CGM, TSC);
8098 
8099   if (const EnumType *ET = QT->getAs<EnumType>())
8100     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8101 
8102   if (const RecordType *RT = QT->getAsStructureType())
8103     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8104 
8105   if (const RecordType *RT = QT->getAsUnionType())
8106     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8107 
8108   if (const FunctionType *FT = QT->getAs<FunctionType>())
8109     return appendFunctionType(Enc, FT, CGM, TSC);
8110 
8111   return false;
8112 }
8113 
8114 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8115                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8116   if (!D)
8117     return false;
8118 
8119   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8120     if (FD->getLanguageLinkage() != CLanguageLinkage)
8121       return false;
8122     return appendType(Enc, FD->getType(), CGM, TSC);
8123   }
8124 
8125   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8126     if (VD->getLanguageLinkage() != CLanguageLinkage)
8127       return false;
8128     QualType QT = VD->getType().getCanonicalType();
8129     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8130       // Global ArrayTypes are given a size of '*' if the size is unknown.
8131       // The Qualifiers should be attached to the type rather than the array.
8132       // Thus we don't call appendQualifier() here.
8133       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8134     }
8135     return appendType(Enc, QT, CGM, TSC);
8136   }
8137   return false;
8138 }
8139 
8140 
8141 //===----------------------------------------------------------------------===//
8142 // Driver code
8143 //===----------------------------------------------------------------------===//
8144 
8145 bool CodeGenModule::supportsCOMDAT() const {
8146   return getTriple().supportsCOMDAT();
8147 }
8148 
8149 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8150   if (TheTargetCodeGenInfo)
8151     return *TheTargetCodeGenInfo;
8152 
8153   // Helper to set the unique_ptr while still keeping the return value.
8154   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8155     this->TheTargetCodeGenInfo.reset(P);
8156     return *P;
8157   };
8158 
8159   const llvm::Triple &Triple = getTarget().getTriple();
8160   switch (Triple.getArch()) {
8161   default:
8162     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8163 
8164   case llvm::Triple::le32:
8165     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8166   case llvm::Triple::mips:
8167   case llvm::Triple::mipsel:
8168     if (Triple.getOS() == llvm::Triple::NaCl)
8169       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8170     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8171 
8172   case llvm::Triple::mips64:
8173   case llvm::Triple::mips64el:
8174     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8175 
8176   case llvm::Triple::aarch64:
8177   case llvm::Triple::aarch64_be: {
8178     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8179     if (getTarget().getABI() == "darwinpcs")
8180       Kind = AArch64ABIInfo::DarwinPCS;
8181 
8182     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8183   }
8184 
8185   case llvm::Triple::wasm32:
8186   case llvm::Triple::wasm64:
8187     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8188 
8189   case llvm::Triple::arm:
8190   case llvm::Triple::armeb:
8191   case llvm::Triple::thumb:
8192   case llvm::Triple::thumbeb: {
8193     if (Triple.getOS() == llvm::Triple::Win32) {
8194       return SetCGInfo(
8195           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8196     }
8197 
8198     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8199     StringRef ABIStr = getTarget().getABI();
8200     if (ABIStr == "apcs-gnu")
8201       Kind = ARMABIInfo::APCS;
8202     else if (ABIStr == "aapcs16")
8203       Kind = ARMABIInfo::AAPCS16_VFP;
8204     else if (CodeGenOpts.FloatABI == "hard" ||
8205              (CodeGenOpts.FloatABI != "soft" &&
8206               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8207                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8208                Triple.getEnvironment() == llvm::Triple::EABIHF)))
8209       Kind = ARMABIInfo::AAPCS_VFP;
8210 
8211     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8212   }
8213 
8214   case llvm::Triple::ppc:
8215     return SetCGInfo(
8216         new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8217   case llvm::Triple::ppc64:
8218     if (Triple.isOSBinFormatELF()) {
8219       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8220       if (getTarget().getABI() == "elfv2")
8221         Kind = PPC64_SVR4_ABIInfo::ELFv2;
8222       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8223       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8224 
8225       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8226                                                         IsSoftFloat));
8227     } else
8228       return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8229   case llvm::Triple::ppc64le: {
8230     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8231     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8232     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8233       Kind = PPC64_SVR4_ABIInfo::ELFv1;
8234     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8235     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8236 
8237     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8238                                                       IsSoftFloat));
8239   }
8240 
8241   case llvm::Triple::nvptx:
8242   case llvm::Triple::nvptx64:
8243     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8244 
8245   case llvm::Triple::msp430:
8246     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8247 
8248   case llvm::Triple::systemz: {
8249     bool HasVector = getTarget().getABI() == "vector";
8250     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8251   }
8252 
8253   case llvm::Triple::tce:
8254   case llvm::Triple::tcele:
8255     return SetCGInfo(new TCETargetCodeGenInfo(Types));
8256 
8257   case llvm::Triple::x86: {
8258     bool IsDarwinVectorABI = Triple.isOSDarwin();
8259     bool RetSmallStructInRegABI =
8260         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8261     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8262 
8263     if (Triple.getOS() == llvm::Triple::Win32) {
8264       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8265           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8266           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8267     } else {
8268       return SetCGInfo(new X86_32TargetCodeGenInfo(
8269           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8270           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8271           CodeGenOpts.FloatABI == "soft"));
8272     }
8273   }
8274 
8275   case llvm::Triple::x86_64: {
8276     StringRef ABI = getTarget().getABI();
8277     X86AVXABILevel AVXLevel =
8278         (ABI == "avx512"
8279              ? X86AVXABILevel::AVX512
8280              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8281 
8282     switch (Triple.getOS()) {
8283     case llvm::Triple::Win32:
8284       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8285     case llvm::Triple::PS4:
8286       return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8287     default:
8288       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8289     }
8290   }
8291   case llvm::Triple::hexagon:
8292     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8293   case llvm::Triple::lanai:
8294     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8295   case llvm::Triple::r600:
8296     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8297   case llvm::Triple::amdgcn:
8298     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8299   case llvm::Triple::sparc:
8300     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8301   case llvm::Triple::sparcv9:
8302     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8303   case llvm::Triple::xcore:
8304     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8305   case llvm::Triple::spir:
8306   case llvm::Triple::spir64:
8307     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
8308   }
8309 }
8310