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