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