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