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