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