TargetInfo.cpp revision 2c585b991596859f39860b6094247ba027a03530
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 "CodeGenFunction.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Frontend/CodeGenOptions.h"
20#include "llvm/Type.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/Support/raw_ostream.h"
24using namespace clang;
25using namespace CodeGen;
26
27static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
28                               llvm::Value *Array,
29                               llvm::Value *Value,
30                               unsigned FirstIndex,
31                               unsigned LastIndex) {
32  // Alternatively, we could emit this as a loop in the source.
33  for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
34    llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
35    Builder.CreateStore(Value, Cell);
36  }
37}
38
39static bool isAggregateTypeForABI(QualType T) {
40  return CodeGenFunction::hasAggregateLLVMType(T) ||
41         T->isMemberFunctionPointerType();
42}
43
44ABIInfo::~ABIInfo() {}
45
46ASTContext &ABIInfo::getContext() const {
47  return CGT.getContext();
48}
49
50llvm::LLVMContext &ABIInfo::getVMContext() const {
51  return CGT.getLLVMContext();
52}
53
54const llvm::TargetData &ABIInfo::getTargetData() const {
55  return CGT.getTargetData();
56}
57
58
59void ABIArgInfo::dump() const {
60  raw_ostream &OS = llvm::errs();
61  OS << "(ABIArgInfo Kind=";
62  switch (TheKind) {
63  case Direct:
64    OS << "Direct Type=";
65    if (llvm::Type *Ty = getCoerceToType())
66      Ty->print(OS);
67    else
68      OS << "null";
69    break;
70  case Extend:
71    OS << "Extend";
72    break;
73  case Ignore:
74    OS << "Ignore";
75    break;
76  case Indirect:
77    OS << "Indirect Align=" << getIndirectAlign()
78       << " ByVal=" << getIndirectByVal()
79       << " Realign=" << getIndirectRealign();
80    break;
81  case Expand:
82    OS << "Expand";
83    break;
84  }
85  OS << ")\n";
86}
87
88TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
89
90// If someone can figure out a general rule for this, that would be great.
91// It's probably just doomed to be platform-dependent, though.
92unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
93  // Verified for:
94  //   x86-64     FreeBSD, Linux, Darwin
95  //   x86-32     FreeBSD, Linux, Darwin
96  //   PowerPC    Linux, Darwin
97  //   ARM        Darwin (*not* EABI)
98  return 32;
99}
100
101bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
102                                     const FunctionNoProtoType *fnType) const {
103  // The following conventions are known to require this to be false:
104  //   x86_stdcall
105  //   MIPS
106  // For everything else, we just prefer false unless we opt out.
107  return false;
108}
109
110static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
111
112/// isEmptyField - Return true iff a the field is "empty", that is it
113/// is an unnamed bit-field or an (array of) empty record(s).
114static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
115                         bool AllowArrays) {
116  if (FD->isUnnamedBitfield())
117    return true;
118
119  QualType FT = FD->getType();
120
121  // Constant arrays of empty records count as empty, strip them off.
122  // Constant arrays of zero length always count as empty.
123  if (AllowArrays)
124    while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
125      if (AT->getSize() == 0)
126        return true;
127      FT = AT->getElementType();
128    }
129
130  const RecordType *RT = FT->getAs<RecordType>();
131  if (!RT)
132    return false;
133
134  // C++ record fields are never empty, at least in the Itanium ABI.
135  //
136  // FIXME: We should use a predicate for whether this behavior is true in the
137  // current ABI.
138  if (isa<CXXRecordDecl>(RT->getDecl()))
139    return false;
140
141  return isEmptyRecord(Context, FT, AllowArrays);
142}
143
144/// isEmptyRecord - Return true iff a structure contains only empty
145/// fields. Note that a structure with a flexible array member is not
146/// considered empty.
147static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
148  const RecordType *RT = T->getAs<RecordType>();
149  if (!RT)
150    return 0;
151  const RecordDecl *RD = RT->getDecl();
152  if (RD->hasFlexibleArrayMember())
153    return false;
154
155  // If this is a C++ record, check the bases first.
156  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
157    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
158           e = CXXRD->bases_end(); i != e; ++i)
159      if (!isEmptyRecord(Context, i->getType(), true))
160        return false;
161
162  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
163         i != e; ++i)
164    if (!isEmptyField(Context, &*i, AllowArrays))
165      return false;
166  return true;
167}
168
169/// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
170/// a non-trivial destructor or a non-trivial copy constructor.
171static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
172  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
173  if (!RD)
174    return false;
175
176  return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
177}
178
179/// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
180/// a record type with either a non-trivial destructor or a non-trivial copy
181/// constructor.
182static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
183  const RecordType *RT = T->getAs<RecordType>();
184  if (!RT)
185    return false;
186
187  return hasNonTrivialDestructorOrCopyConstructor(RT);
188}
189
190/// isSingleElementStruct - Determine if a structure is a "single
191/// element struct", i.e. it has exactly one non-empty field or
192/// exactly one field which is itself a single element
193/// struct. Structures with flexible array members are never
194/// considered single element structs.
195///
196/// \return The field declaration for the single non-empty field, if
197/// it exists.
198static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
199  const RecordType *RT = T->getAsStructureType();
200  if (!RT)
201    return 0;
202
203  const RecordDecl *RD = RT->getDecl();
204  if (RD->hasFlexibleArrayMember())
205    return 0;
206
207  const Type *Found = 0;
208
209  // If this is a C++ record, check the bases first.
210  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
211    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
212           e = CXXRD->bases_end(); i != e; ++i) {
213      // Ignore empty records.
214      if (isEmptyRecord(Context, i->getType(), true))
215        continue;
216
217      // If we already found an element then this isn't a single-element struct.
218      if (Found)
219        return 0;
220
221      // If this is non-empty and not a single element struct, the composite
222      // cannot be a single element struct.
223      Found = isSingleElementStruct(i->getType(), Context);
224      if (!Found)
225        return 0;
226    }
227  }
228
229  // Check for single element.
230  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
231         i != e; ++i) {
232    const FieldDecl *FD = &*i;
233    QualType FT = FD->getType();
234
235    // Ignore empty fields.
236    if (isEmptyField(Context, FD, true))
237      continue;
238
239    // If we already found an element then this isn't a single-element
240    // struct.
241    if (Found)
242      return 0;
243
244    // Treat single element arrays as the element.
245    while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
246      if (AT->getSize().getZExtValue() != 1)
247        break;
248      FT = AT->getElementType();
249    }
250
251    if (!isAggregateTypeForABI(FT)) {
252      Found = FT.getTypePtr();
253    } else {
254      Found = isSingleElementStruct(FT, Context);
255      if (!Found)
256        return 0;
257    }
258  }
259
260  // We don't consider a struct a single-element struct if it has
261  // padding beyond the element type.
262  if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
263    return 0;
264
265  return Found;
266}
267
268static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
269  if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
270      !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
271      !Ty->isBlockPointerType())
272    return false;
273
274  uint64_t Size = Context.getTypeSize(Ty);
275  return Size == 32 || Size == 64;
276}
277
278/// canExpandIndirectArgument - Test whether an argument type which is to be
279/// passed indirectly (on the stack) would have the equivalent layout if it was
280/// expanded into separate arguments. If so, we prefer to do the latter to avoid
281/// inhibiting optimizations.
282///
283// FIXME: This predicate is missing many cases, currently it just follows
284// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
285// should probably make this smarter, or better yet make the LLVM backend
286// capable of handling it.
287static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
288  // We can only expand structure types.
289  const RecordType *RT = Ty->getAs<RecordType>();
290  if (!RT)
291    return false;
292
293  // We can only expand (C) structures.
294  //
295  // FIXME: This needs to be generalized to handle classes as well.
296  const RecordDecl *RD = RT->getDecl();
297  if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
298    return false;
299
300  uint64_t Size = 0;
301
302  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
303         i != e; ++i) {
304    const FieldDecl *FD = &*i;
305
306    if (!is32Or64BitBasicType(FD->getType(), Context))
307      return false;
308
309    // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
310    // how to expand them yet, and the predicate for telling if a bitfield still
311    // counts as "basic" is more complicated than what we were doing previously.
312    if (FD->isBitField())
313      return false;
314
315    Size += Context.getTypeSize(FD->getType());
316  }
317
318  // Make sure there are not any holes in the struct.
319  if (Size != Context.getTypeSize(Ty))
320    return false;
321
322  return true;
323}
324
325namespace {
326/// DefaultABIInfo - The default implementation for ABI specific
327/// details. This implementation provides information which results in
328/// self-consistent and sensible LLVM IR generation, but does not
329/// conform to any particular ABI.
330class DefaultABIInfo : public ABIInfo {
331public:
332  DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
333
334  ABIArgInfo classifyReturnType(QualType RetTy) const;
335  ABIArgInfo classifyArgumentType(QualType RetTy) const;
336
337  virtual void computeInfo(CGFunctionInfo &FI) const {
338    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
339    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
340         it != ie; ++it)
341      it->info = classifyArgumentType(it->type);
342  }
343
344  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
345                                 CodeGenFunction &CGF) const;
346};
347
348class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
349public:
350  DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
351    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
352};
353
354llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
355                                       CodeGenFunction &CGF) const {
356  return 0;
357}
358
359ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
360  if (isAggregateTypeForABI(Ty)) {
361    // Records with non trivial destructors/constructors should not be passed
362    // by value.
363    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
364      return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
365
366    return ABIArgInfo::getIndirect(0);
367  }
368
369  // Treat an enum type as its underlying type.
370  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
371    Ty = EnumTy->getDecl()->getIntegerType();
372
373  return (Ty->isPromotableIntegerType() ?
374          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
375}
376
377ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
378  if (RetTy->isVoidType())
379    return ABIArgInfo::getIgnore();
380
381  if (isAggregateTypeForABI(RetTy))
382    return ABIArgInfo::getIndirect(0);
383
384  // Treat an enum type as its underlying type.
385  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
386    RetTy = EnumTy->getDecl()->getIntegerType();
387
388  return (RetTy->isPromotableIntegerType() ?
389          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
390}
391
392/// UseX86_MMXType - Return true if this is an MMX type that should use the
393/// special x86_mmx type.
394bool UseX86_MMXType(llvm::Type *IRType) {
395  // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the
396  // special x86_mmx type.
397  return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
398    cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
399    IRType->getScalarSizeInBits() != 64;
400}
401
402static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
403                                          StringRef Constraint,
404                                          llvm::Type* Ty) {
405  if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy())
406    return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
407  return Ty;
408}
409
410//===----------------------------------------------------------------------===//
411// X86-32 ABI Implementation
412//===----------------------------------------------------------------------===//
413
414/// X86_32ABIInfo - The X86-32 ABI information.
415class X86_32ABIInfo : public ABIInfo {
416  static const unsigned MinABIStackAlignInBytes = 4;
417
418  bool IsDarwinVectorABI;
419  bool IsSmallStructInRegABI;
420  bool IsMMXDisabled;
421  bool IsWin32FloatStructABI;
422
423  static bool isRegisterSize(unsigned Size) {
424    return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
425  }
426
427  static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
428                                          unsigned callingConvention);
429
430  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
431  /// such that the argument will be passed in memory.
432  ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const;
433
434  /// \brief Return the alignment to use for the given type on the stack.
435  unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
436
437public:
438
439  ABIArgInfo classifyReturnType(QualType RetTy,
440                                unsigned callingConvention) const;
441  ABIArgInfo classifyArgumentType(QualType RetTy) const;
442
443  virtual void computeInfo(CGFunctionInfo &FI) const {
444    FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
445                                            FI.getCallingConvention());
446    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
447         it != ie; ++it)
448      it->info = classifyArgumentType(it->type);
449  }
450
451  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
452                                 CodeGenFunction &CGF) const;
453
454  X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m, bool w)
455    : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
456      IsMMXDisabled(m), IsWin32FloatStructABI(w) {}
457};
458
459class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
460public:
461  X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
462      bool d, bool p, bool m, bool w)
463    :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m, w)) {}
464
465  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
466                           CodeGen::CodeGenModule &CGM) const;
467
468  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
469    // Darwin uses different dwarf register numbers for EH.
470    if (CGM.isTargetDarwin()) return 5;
471
472    return 4;
473  }
474
475  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
476                               llvm::Value *Address) const;
477
478  llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
479                                  StringRef Constraint,
480                                  llvm::Type* Ty) const {
481    return X86AdjustInlineAsmType(CGF, Constraint, Ty);
482  }
483
484};
485
486}
487
488/// shouldReturnTypeInRegister - Determine if the given type should be
489/// passed in a register (for the Darwin ABI).
490bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
491                                               ASTContext &Context,
492                                               unsigned callingConvention) {
493  uint64_t Size = Context.getTypeSize(Ty);
494
495  // Type must be register sized.
496  if (!isRegisterSize(Size))
497    return false;
498
499  if (Ty->isVectorType()) {
500    // 64- and 128- bit vectors inside structures are not returned in
501    // registers.
502    if (Size == 64 || Size == 128)
503      return false;
504
505    return true;
506  }
507
508  // If this is a builtin, pointer, enum, complex type, member pointer, or
509  // member function pointer it is ok.
510  if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
511      Ty->isAnyComplexType() || Ty->isEnumeralType() ||
512      Ty->isBlockPointerType() || Ty->isMemberPointerType())
513    return true;
514
515  // Arrays are treated like records.
516  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
517    return shouldReturnTypeInRegister(AT->getElementType(), Context,
518                                      callingConvention);
519
520  // Otherwise, it must be a record type.
521  const RecordType *RT = Ty->getAs<RecordType>();
522  if (!RT) return false;
523
524  // FIXME: Traverse bases here too.
525
526  // For thiscall conventions, structures will never be returned in
527  // a register.  This is for compatibility with the MSVC ABI
528  if (callingConvention == llvm::CallingConv::X86_ThisCall &&
529      RT->isStructureType()) {
530    return false;
531  }
532
533  // Structure types are passed in register if all fields would be
534  // passed in a register.
535  for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
536         e = RT->getDecl()->field_end(); i != e; ++i) {
537    const FieldDecl *FD = &*i;
538
539    // Empty fields are ignored.
540    if (isEmptyField(Context, FD, true))
541      continue;
542
543    // Check fields recursively.
544    if (!shouldReturnTypeInRegister(FD->getType(), Context,
545                                    callingConvention))
546      return false;
547  }
548  return true;
549}
550
551ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
552                                            unsigned callingConvention) const {
553  if (RetTy->isVoidType())
554    return ABIArgInfo::getIgnore();
555
556  if (const VectorType *VT = RetTy->getAs<VectorType>()) {
557    // On Darwin, some vectors are returned in registers.
558    if (IsDarwinVectorABI) {
559      uint64_t Size = getContext().getTypeSize(RetTy);
560
561      // 128-bit vectors are a special case; they are returned in
562      // registers and we need to make sure to pick a type the LLVM
563      // backend will like.
564      if (Size == 128)
565        return ABIArgInfo::getDirect(llvm::VectorType::get(
566                  llvm::Type::getInt64Ty(getVMContext()), 2));
567
568      // Always return in register if it fits in a general purpose
569      // register, or if it is 64 bits and has a single element.
570      if ((Size == 8 || Size == 16 || Size == 32) ||
571          (Size == 64 && VT->getNumElements() == 1))
572        return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
573                                                            Size));
574
575      return ABIArgInfo::getIndirect(0);
576    }
577
578    return ABIArgInfo::getDirect();
579  }
580
581  if (isAggregateTypeForABI(RetTy)) {
582    if (const RecordType *RT = RetTy->getAs<RecordType>()) {
583      // Structures with either a non-trivial destructor or a non-trivial
584      // copy constructor are always indirect.
585      if (hasNonTrivialDestructorOrCopyConstructor(RT))
586        return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
587
588      // Structures with flexible arrays are always indirect.
589      if (RT->getDecl()->hasFlexibleArrayMember())
590        return ABIArgInfo::getIndirect(0);
591    }
592
593    // If specified, structs and unions are always indirect.
594    if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
595      return ABIArgInfo::getIndirect(0);
596
597    // Small structures which are register sized are generally returned
598    // in a register.
599    if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
600                                                  callingConvention)) {
601      uint64_t Size = getContext().getTypeSize(RetTy);
602
603      // As a special-case, if the struct is a "single-element" struct, and
604      // the field is of type "float" or "double", return it in a
605      // floating-point register. (MSVC does not apply this special case.)
606      // We apply a similar transformation for pointer types to improve the
607      // quality of the generated IR.
608      if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
609        if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType())
610            || SeltTy->hasPointerRepresentation())
611          return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
612
613      // FIXME: We should be able to narrow this integer in cases with dead
614      // padding.
615      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
616    }
617
618    return ABIArgInfo::getIndirect(0);
619  }
620
621  // Treat an enum type as its underlying type.
622  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
623    RetTy = EnumTy->getDecl()->getIntegerType();
624
625  return (RetTy->isPromotableIntegerType() ?
626          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
627}
628
629static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
630  const RecordType *RT = Ty->getAs<RecordType>();
631  if (!RT)
632    return 0;
633  const RecordDecl *RD = RT->getDecl();
634
635  // If this is a C++ record, check the bases first.
636  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
637    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
638           e = CXXRD->bases_end(); i != e; ++i)
639      if (!isRecordWithSSEVectorType(Context, i->getType()))
640        return false;
641
642  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
643       i != e; ++i) {
644    QualType FT = i->getType();
645
646    if (FT->getAs<VectorType>() && Context.getTypeSize(FT) == 128)
647      return true;
648
649    if (isRecordWithSSEVectorType(Context, FT))
650      return true;
651  }
652
653  return false;
654}
655
656unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
657                                                 unsigned Align) const {
658  // Otherwise, if the alignment is less than or equal to the minimum ABI
659  // alignment, just use the default; the backend will handle this.
660  if (Align <= MinABIStackAlignInBytes)
661    return 0; // Use default alignment.
662
663  // On non-Darwin, the stack type alignment is always 4.
664  if (!IsDarwinVectorABI) {
665    // Set explicit alignment, since we may need to realign the top.
666    return MinABIStackAlignInBytes;
667  }
668
669  // Otherwise, if the type contains an SSE vector type, the alignment is 16.
670  if (Align >= 16 && isRecordWithSSEVectorType(getContext(), Ty))
671    return 16;
672
673  return MinABIStackAlignInBytes;
674}
675
676ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const {
677  if (!ByVal)
678    return ABIArgInfo::getIndirect(0, false);
679
680  // Compute the byval alignment.
681  unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
682  unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
683  if (StackAlign == 0)
684    return ABIArgInfo::getIndirect(4);
685
686  // If the stack alignment is less than the type alignment, realign the
687  // argument.
688  if (StackAlign < TypeAlign)
689    return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
690                                   /*Realign=*/true);
691
692  return ABIArgInfo::getIndirect(StackAlign);
693}
694
695ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const {
696  // FIXME: Set alignment on indirect arguments.
697  if (isAggregateTypeForABI(Ty)) {
698    // Structures with flexible arrays are always indirect.
699    if (const RecordType *RT = Ty->getAs<RecordType>()) {
700      // Structures with either a non-trivial destructor or a non-trivial
701      // copy constructor are always indirect.
702      if (hasNonTrivialDestructorOrCopyConstructor(RT))
703        return getIndirectResult(Ty, /*ByVal=*/false);
704
705      if (RT->getDecl()->hasFlexibleArrayMember())
706        return getIndirectResult(Ty);
707    }
708
709    // Ignore empty structs/unions.
710    if (isEmptyRecord(getContext(), Ty, true))
711      return ABIArgInfo::getIgnore();
712
713    // Expand small (<= 128-bit) record types when we know that the stack layout
714    // of those arguments will match the struct. This is important because the
715    // LLVM backend isn't smart enough to remove byval, which inhibits many
716    // optimizations.
717    if (getContext().getTypeSize(Ty) <= 4*32 &&
718        canExpandIndirectArgument(Ty, getContext()))
719      return ABIArgInfo::getExpand();
720
721    return getIndirectResult(Ty);
722  }
723
724  if (const VectorType *VT = Ty->getAs<VectorType>()) {
725    // On Darwin, some vectors are passed in memory, we handle this by passing
726    // it as an i8/i16/i32/i64.
727    if (IsDarwinVectorABI) {
728      uint64_t Size = getContext().getTypeSize(Ty);
729      if ((Size == 8 || Size == 16 || Size == 32) ||
730          (Size == 64 && VT->getNumElements() == 1))
731        return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
732                                                            Size));
733    }
734
735    llvm::Type *IRType = CGT.ConvertType(Ty);
736    if (UseX86_MMXType(IRType)) {
737      if (IsMMXDisabled)
738        return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
739                                                            64));
740      ABIArgInfo AAI = ABIArgInfo::getDirect(IRType);
741      AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext()));
742      return AAI;
743    }
744
745    return ABIArgInfo::getDirect();
746  }
747
748
749  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
750    Ty = EnumTy->getDecl()->getIntegerType();
751
752  return (Ty->isPromotableIntegerType() ?
753          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
754}
755
756llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
757                                      CodeGenFunction &CGF) const {
758  llvm::Type *BPP = CGF.Int8PtrPtrTy;
759
760  CGBuilderTy &Builder = CGF.Builder;
761  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
762                                                       "ap");
763  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
764
765  // Compute if the address needs to be aligned
766  unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
767  Align = getTypeStackAlignInBytes(Ty, Align);
768  Align = std::max(Align, 4U);
769  if (Align > 4) {
770    // addr = (addr + align - 1) & -align;
771    llvm::Value *Offset =
772      llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
773    Addr = CGF.Builder.CreateGEP(Addr, Offset);
774    llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
775                                                    CGF.Int32Ty);
776    llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
777    Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
778                                      Addr->getType(),
779                                      "ap.cur.aligned");
780  }
781
782  llvm::Type *PTy =
783    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
784  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
785
786  uint64_t Offset =
787    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
788  llvm::Value *NextAddr =
789    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
790                      "ap.next");
791  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
792
793  return AddrTyped;
794}
795
796void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
797                                                  llvm::GlobalValue *GV,
798                                            CodeGen::CodeGenModule &CGM) const {
799  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
800    if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
801      // Get the LLVM function.
802      llvm::Function *Fn = cast<llvm::Function>(GV);
803
804      // Now add the 'alignstack' attribute with a value of 16.
805      Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16));
806    }
807  }
808}
809
810bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
811                                               CodeGen::CodeGenFunction &CGF,
812                                               llvm::Value *Address) const {
813  CodeGen::CGBuilderTy &Builder = CGF.Builder;
814
815  llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
816
817  // 0-7 are the eight integer registers;  the order is different
818  //   on Darwin (for EH), but the range is the same.
819  // 8 is %eip.
820  AssignToArrayRange(Builder, Address, Four8, 0, 8);
821
822  if (CGF.CGM.isTargetDarwin()) {
823    // 12-16 are st(0..4).  Not sure why we stop at 4.
824    // These have size 16, which is sizeof(long double) on
825    // platforms with 8-byte alignment for that type.
826    llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
827    AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
828
829  } else {
830    // 9 is %eflags, which doesn't get a size on Darwin for some
831    // reason.
832    Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
833
834    // 11-16 are st(0..5).  Not sure why we stop at 5.
835    // These have size 12, which is sizeof(long double) on
836    // platforms with 4-byte alignment for that type.
837    llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
838    AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
839  }
840
841  return false;
842}
843
844//===----------------------------------------------------------------------===//
845// X86-64 ABI Implementation
846//===----------------------------------------------------------------------===//
847
848
849namespace {
850/// X86_64ABIInfo - The X86_64 ABI information.
851class X86_64ABIInfo : public ABIInfo {
852  enum Class {
853    Integer = 0,
854    SSE,
855    SSEUp,
856    X87,
857    X87Up,
858    ComplexX87,
859    NoClass,
860    Memory
861  };
862
863  /// merge - Implement the X86_64 ABI merging algorithm.
864  ///
865  /// Merge an accumulating classification \arg Accum with a field
866  /// classification \arg Field.
867  ///
868  /// \param Accum - The accumulating classification. This should
869  /// always be either NoClass or the result of a previous merge
870  /// call. In addition, this should never be Memory (the caller
871  /// should just return Memory for the aggregate).
872  static Class merge(Class Accum, Class Field);
873
874  /// postMerge - Implement the X86_64 ABI post merging algorithm.
875  ///
876  /// Post merger cleanup, reduces a malformed Hi and Lo pair to
877  /// final MEMORY or SSE classes when necessary.
878  ///
879  /// \param AggregateSize - The size of the current aggregate in
880  /// the classification process.
881  ///
882  /// \param Lo - The classification for the parts of the type
883  /// residing in the low word of the containing object.
884  ///
885  /// \param Hi - The classification for the parts of the type
886  /// residing in the higher words of the containing object.
887  ///
888  void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
889
890  /// classify - Determine the x86_64 register classes in which the
891  /// given type T should be passed.
892  ///
893  /// \param Lo - The classification for the parts of the type
894  /// residing in the low word of the containing object.
895  ///
896  /// \param Hi - The classification for the parts of the type
897  /// residing in the high word of the containing object.
898  ///
899  /// \param OffsetBase - The bit offset of this type in the
900  /// containing object.  Some parameters are classified different
901  /// depending on whether they straddle an eightbyte boundary.
902  ///
903  /// If a word is unused its result will be NoClass; if a type should
904  /// be passed in Memory then at least the classification of \arg Lo
905  /// will be Memory.
906  ///
907  /// The \arg Lo class will be NoClass iff the argument is ignored.
908  ///
909  /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
910  /// also be ComplexX87.
911  void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
912
913  llvm::Type *GetByteVectorType(QualType Ty) const;
914  llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
915                                 unsigned IROffset, QualType SourceTy,
916                                 unsigned SourceOffset) const;
917  llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
918                                     unsigned IROffset, QualType SourceTy,
919                                     unsigned SourceOffset) const;
920
921  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
922  /// such that the argument will be returned in memory.
923  ABIArgInfo getIndirectReturnResult(QualType Ty) const;
924
925  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
926  /// such that the argument will be passed in memory.
927  ///
928  /// \param freeIntRegs - The number of free integer registers remaining
929  /// available.
930  ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
931
932  ABIArgInfo classifyReturnType(QualType RetTy) const;
933
934  ABIArgInfo classifyArgumentType(QualType Ty,
935                                  unsigned freeIntRegs,
936                                  unsigned &neededInt,
937                                  unsigned &neededSSE) const;
938
939  bool IsIllegalVectorType(QualType Ty) const;
940
941  /// The 0.98 ABI revision clarified a lot of ambiguities,
942  /// unfortunately in ways that were not always consistent with
943  /// certain previous compilers.  In particular, platforms which
944  /// required strict binary compatibility with older versions of GCC
945  /// may need to exempt themselves.
946  bool honorsRevision0_98() const {
947    return !getContext().getTargetInfo().getTriple().isOSDarwin();
948  }
949
950  bool HasAVX;
951
952public:
953  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
954      ABIInfo(CGT), HasAVX(hasavx) {}
955
956  bool isPassedUsingAVXType(QualType type) const {
957    unsigned neededInt, neededSSE;
958    // The freeIntRegs argument doesn't matter here.
959    ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE);
960    if (info.isDirect()) {
961      llvm::Type *ty = info.getCoerceToType();
962      if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
963        return (vectorTy->getBitWidth() > 128);
964    }
965    return false;
966  }
967
968  virtual void computeInfo(CGFunctionInfo &FI) const;
969
970  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
971                                 CodeGenFunction &CGF) const;
972};
973
974/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
975class WinX86_64ABIInfo : public ABIInfo {
976
977  ABIArgInfo classify(QualType Ty) const;
978
979public:
980  WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
981
982  virtual void computeInfo(CGFunctionInfo &FI) const;
983
984  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
985                                 CodeGenFunction &CGF) const;
986};
987
988class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
989public:
990  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
991    : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
992
993  const X86_64ABIInfo &getABIInfo() const {
994    return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
995  }
996
997  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
998    return 7;
999  }
1000
1001  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1002                               llvm::Value *Address) const {
1003    llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1004
1005    // 0-15 are the 16 integer registers.
1006    // 16 is %rip.
1007    AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1008    return false;
1009  }
1010
1011  llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1012                                  StringRef Constraint,
1013                                  llvm::Type* Ty) const {
1014    return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1015  }
1016
1017  bool isNoProtoCallVariadic(const CallArgList &args,
1018                             const FunctionNoProtoType *fnType) const {
1019    // The default CC on x86-64 sets %al to the number of SSA
1020    // registers used, and GCC sets this when calling an unprototyped
1021    // function, so we override the default behavior.  However, don't do
1022    // that when AVX types are involved: the ABI explicitly states it is
1023    // undefined, and it doesn't work in practice because of how the ABI
1024    // defines varargs anyway.
1025    if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) {
1026      bool HasAVXType = false;
1027      for (CallArgList::const_iterator
1028             it = args.begin(), ie = args.end(); it != ie; ++it) {
1029        if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1030          HasAVXType = true;
1031          break;
1032        }
1033      }
1034
1035      if (!HasAVXType)
1036        return true;
1037    }
1038
1039    return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1040  }
1041
1042};
1043
1044class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1045public:
1046  WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1047    : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1048
1049  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1050    return 7;
1051  }
1052
1053  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1054                               llvm::Value *Address) const {
1055    llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1056
1057    // 0-15 are the 16 integer registers.
1058    // 16 is %rip.
1059    AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1060    return false;
1061  }
1062};
1063
1064}
1065
1066void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1067                              Class &Hi) const {
1068  // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1069  //
1070  // (a) If one of the classes is Memory, the whole argument is passed in
1071  //     memory.
1072  //
1073  // (b) If X87UP is not preceded by X87, the whole argument is passed in
1074  //     memory.
1075  //
1076  // (c) If the size of the aggregate exceeds two eightbytes and the first
1077  //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1078  //     argument is passed in memory. NOTE: This is necessary to keep the
1079  //     ABI working for processors that don't support the __m256 type.
1080  //
1081  // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1082  //
1083  // Some of these are enforced by the merging logic.  Others can arise
1084  // only with unions; for example:
1085  //   union { _Complex double; unsigned; }
1086  //
1087  // Note that clauses (b) and (c) were added in 0.98.
1088  //
1089  if (Hi == Memory)
1090    Lo = Memory;
1091  if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1092    Lo = Memory;
1093  if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1094    Lo = Memory;
1095  if (Hi == SSEUp && Lo != SSE)
1096    Hi = SSE;
1097}
1098
1099X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1100  // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1101  // classified recursively so that always two fields are
1102  // considered. The resulting class is calculated according to
1103  // the classes of the fields in the eightbyte:
1104  //
1105  // (a) If both classes are equal, this is the resulting class.
1106  //
1107  // (b) If one of the classes is NO_CLASS, the resulting class is
1108  // the other class.
1109  //
1110  // (c) If one of the classes is MEMORY, the result is the MEMORY
1111  // class.
1112  //
1113  // (d) If one of the classes is INTEGER, the result is the
1114  // INTEGER.
1115  //
1116  // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1117  // MEMORY is used as class.
1118  //
1119  // (f) Otherwise class SSE is used.
1120
1121  // Accum should never be memory (we should have returned) or
1122  // ComplexX87 (because this cannot be passed in a structure).
1123  assert((Accum != Memory && Accum != ComplexX87) &&
1124         "Invalid accumulated classification during merge.");
1125  if (Accum == Field || Field == NoClass)
1126    return Accum;
1127  if (Field == Memory)
1128    return Memory;
1129  if (Accum == NoClass)
1130    return Field;
1131  if (Accum == Integer || Field == Integer)
1132    return Integer;
1133  if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1134      Accum == X87 || Accum == X87Up)
1135    return Memory;
1136  return SSE;
1137}
1138
1139void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1140                             Class &Lo, Class &Hi) const {
1141  // FIXME: This code can be simplified by introducing a simple value class for
1142  // Class pairs with appropriate constructor methods for the various
1143  // situations.
1144
1145  // FIXME: Some of the split computations are wrong; unaligned vectors
1146  // shouldn't be passed in registers for example, so there is no chance they
1147  // can straddle an eightbyte. Verify & simplify.
1148
1149  Lo = Hi = NoClass;
1150
1151  Class &Current = OffsetBase < 64 ? Lo : Hi;
1152  Current = Memory;
1153
1154  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1155    BuiltinType::Kind k = BT->getKind();
1156
1157    if (k == BuiltinType::Void) {
1158      Current = NoClass;
1159    } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1160      Lo = Integer;
1161      Hi = Integer;
1162    } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1163      Current = Integer;
1164    } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
1165      Current = SSE;
1166    } else if (k == BuiltinType::LongDouble) {
1167      Lo = X87;
1168      Hi = X87Up;
1169    }
1170    // FIXME: _Decimal32 and _Decimal64 are SSE.
1171    // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1172    return;
1173  }
1174
1175  if (const EnumType *ET = Ty->getAs<EnumType>()) {
1176    // Classify the underlying integer type.
1177    classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
1178    return;
1179  }
1180
1181  if (Ty->hasPointerRepresentation()) {
1182    Current = Integer;
1183    return;
1184  }
1185
1186  if (Ty->isMemberPointerType()) {
1187    if (Ty->isMemberFunctionPointerType())
1188      Lo = Hi = Integer;
1189    else
1190      Current = Integer;
1191    return;
1192  }
1193
1194  if (const VectorType *VT = Ty->getAs<VectorType>()) {
1195    uint64_t Size = getContext().getTypeSize(VT);
1196    if (Size == 32) {
1197      // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1198      // float> as integer.
1199      Current = Integer;
1200
1201      // If this type crosses an eightbyte boundary, it should be
1202      // split.
1203      uint64_t EB_Real = (OffsetBase) / 64;
1204      uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1205      if (EB_Real != EB_Imag)
1206        Hi = Lo;
1207    } else if (Size == 64) {
1208      // gcc passes <1 x double> in memory. :(
1209      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1210        return;
1211
1212      // gcc passes <1 x long long> as INTEGER.
1213      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1214          VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1215          VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1216          VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1217        Current = Integer;
1218      else
1219        Current = SSE;
1220
1221      // If this type crosses an eightbyte boundary, it should be
1222      // split.
1223      if (OffsetBase && OffsetBase != 64)
1224        Hi = Lo;
1225    } else if (Size == 128 || (HasAVX && Size == 256)) {
1226      // Arguments of 256-bits are split into four eightbyte chunks. The
1227      // least significant one belongs to class SSE and all the others to class
1228      // SSEUP. The original Lo and Hi design considers that types can't be
1229      // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1230      // This design isn't correct for 256-bits, but since there're no cases
1231      // where the upper parts would need to be inspected, avoid adding
1232      // complexity and just consider Hi to match the 64-256 part.
1233      Lo = SSE;
1234      Hi = SSEUp;
1235    }
1236    return;
1237  }
1238
1239  if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1240    QualType ET = getContext().getCanonicalType(CT->getElementType());
1241
1242    uint64_t Size = getContext().getTypeSize(Ty);
1243    if (ET->isIntegralOrEnumerationType()) {
1244      if (Size <= 64)
1245        Current = Integer;
1246      else if (Size <= 128)
1247        Lo = Hi = Integer;
1248    } else if (ET == getContext().FloatTy)
1249      Current = SSE;
1250    else if (ET == getContext().DoubleTy)
1251      Lo = Hi = SSE;
1252    else if (ET == getContext().LongDoubleTy)
1253      Current = ComplexX87;
1254
1255    // If this complex type crosses an eightbyte boundary then it
1256    // should be split.
1257    uint64_t EB_Real = (OffsetBase) / 64;
1258    uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1259    if (Hi == NoClass && EB_Real != EB_Imag)
1260      Hi = Lo;
1261
1262    return;
1263  }
1264
1265  if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1266    // Arrays are treated like structures.
1267
1268    uint64_t Size = getContext().getTypeSize(Ty);
1269
1270    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1271    // than four eightbytes, ..., it has class MEMORY.
1272    if (Size > 256)
1273      return;
1274
1275    // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1276    // fields, it has class MEMORY.
1277    //
1278    // Only need to check alignment of array base.
1279    if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1280      return;
1281
1282    // Otherwise implement simplified merge. We could be smarter about
1283    // this, but it isn't worth it and would be harder to verify.
1284    Current = NoClass;
1285    uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1286    uint64_t ArraySize = AT->getSize().getZExtValue();
1287
1288    // The only case a 256-bit wide vector could be used is when the array
1289    // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1290    // to work for sizes wider than 128, early check and fallback to memory.
1291    if (Size > 128 && EltSize != 256)
1292      return;
1293
1294    for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1295      Class FieldLo, FieldHi;
1296      classify(AT->getElementType(), Offset, FieldLo, FieldHi);
1297      Lo = merge(Lo, FieldLo);
1298      Hi = merge(Hi, FieldHi);
1299      if (Lo == Memory || Hi == Memory)
1300        break;
1301    }
1302
1303    postMerge(Size, Lo, Hi);
1304    assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1305    return;
1306  }
1307
1308  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1309    uint64_t Size = getContext().getTypeSize(Ty);
1310
1311    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1312    // than four eightbytes, ..., it has class MEMORY.
1313    if (Size > 256)
1314      return;
1315
1316    // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1317    // copy constructor or a non-trivial destructor, it is passed by invisible
1318    // reference.
1319    if (hasNonTrivialDestructorOrCopyConstructor(RT))
1320      return;
1321
1322    const RecordDecl *RD = RT->getDecl();
1323
1324    // Assume variable sized types are passed in memory.
1325    if (RD->hasFlexibleArrayMember())
1326      return;
1327
1328    const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1329
1330    // Reset Lo class, this will be recomputed.
1331    Current = NoClass;
1332
1333    // If this is a C++ record, classify the bases first.
1334    if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1335      for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1336             e = CXXRD->bases_end(); i != e; ++i) {
1337        assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1338               "Unexpected base class!");
1339        const CXXRecordDecl *Base =
1340          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1341
1342        // Classify this field.
1343        //
1344        // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1345        // single eightbyte, each is classified separately. Each eightbyte gets
1346        // initialized to class NO_CLASS.
1347        Class FieldLo, FieldHi;
1348        uint64_t Offset = OffsetBase + Layout.getBaseClassOffsetInBits(Base);
1349        classify(i->getType(), Offset, FieldLo, FieldHi);
1350        Lo = merge(Lo, FieldLo);
1351        Hi = merge(Hi, FieldHi);
1352        if (Lo == Memory || Hi == Memory)
1353          break;
1354      }
1355    }
1356
1357    // Classify the fields one at a time, merging the results.
1358    unsigned idx = 0;
1359    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1360           i != e; ++i, ++idx) {
1361      uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1362      bool BitField = i->isBitField();
1363
1364      // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1365      // four eightbytes, or it contains unaligned fields, it has class MEMORY.
1366      //
1367      // The only case a 256-bit wide vector could be used is when the struct
1368      // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1369      // to work for sizes wider than 128, early check and fallback to memory.
1370      //
1371      if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1372        Lo = Memory;
1373        return;
1374      }
1375      // Note, skip this test for bit-fields, see below.
1376      if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1377        Lo = Memory;
1378        return;
1379      }
1380
1381      // Classify this field.
1382      //
1383      // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1384      // exceeds a single eightbyte, each is classified
1385      // separately. Each eightbyte gets initialized to class
1386      // NO_CLASS.
1387      Class FieldLo, FieldHi;
1388
1389      // Bit-fields require special handling, they do not force the
1390      // structure to be passed in memory even if unaligned, and
1391      // therefore they can straddle an eightbyte.
1392      if (BitField) {
1393        // Ignore padding bit-fields.
1394        if (i->isUnnamedBitfield())
1395          continue;
1396
1397        uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1398        uint64_t Size = i->getBitWidthValue(getContext());
1399
1400        uint64_t EB_Lo = Offset / 64;
1401        uint64_t EB_Hi = (Offset + Size - 1) / 64;
1402        FieldLo = FieldHi = NoClass;
1403        if (EB_Lo) {
1404          assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1405          FieldLo = NoClass;
1406          FieldHi = Integer;
1407        } else {
1408          FieldLo = Integer;
1409          FieldHi = EB_Hi ? Integer : NoClass;
1410        }
1411      } else
1412        classify(i->getType(), Offset, FieldLo, FieldHi);
1413      Lo = merge(Lo, FieldLo);
1414      Hi = merge(Hi, FieldHi);
1415      if (Lo == Memory || Hi == Memory)
1416        break;
1417    }
1418
1419    postMerge(Size, Lo, Hi);
1420  }
1421}
1422
1423ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1424  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1425  // place naturally.
1426  if (!isAggregateTypeForABI(Ty)) {
1427    // Treat an enum type as its underlying type.
1428    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1429      Ty = EnumTy->getDecl()->getIntegerType();
1430
1431    return (Ty->isPromotableIntegerType() ?
1432            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1433  }
1434
1435  return ABIArgInfo::getIndirect(0);
1436}
1437
1438bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1439  if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1440    uint64_t Size = getContext().getTypeSize(VecTy);
1441    unsigned LargestVector = HasAVX ? 256 : 128;
1442    if (Size <= 64 || Size > LargestVector)
1443      return true;
1444  }
1445
1446  return false;
1447}
1448
1449ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1450                                            unsigned freeIntRegs) const {
1451  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1452  // place naturally.
1453  //
1454  // This assumption is optimistic, as there could be free registers available
1455  // when we need to pass this argument in memory, and LLVM could try to pass
1456  // the argument in the free register. This does not seem to happen currently,
1457  // but this code would be much safer if we could mark the argument with
1458  // 'onstack'. See PR12193.
1459  if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
1460    // Treat an enum type as its underlying type.
1461    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1462      Ty = EnumTy->getDecl()->getIntegerType();
1463
1464    return (Ty->isPromotableIntegerType() ?
1465            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1466  }
1467
1468  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1469    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1470
1471  // Compute the byval alignment. We specify the alignment of the byval in all
1472  // cases so that the mid-level optimizer knows the alignment of the byval.
1473  unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1474
1475  // Attempt to avoid passing indirect results using byval when possible. This
1476  // is important for good codegen.
1477  //
1478  // We do this by coercing the value into a scalar type which the backend can
1479  // handle naturally (i.e., without using byval).
1480  //
1481  // For simplicity, we currently only do this when we have exhausted all of the
1482  // free integer registers. Doing this when there are free integer registers
1483  // would require more care, as we would have to ensure that the coerced value
1484  // did not claim the unused register. That would require either reording the
1485  // arguments to the function (so that any subsequent inreg values came first),
1486  // or only doing this optimization when there were no following arguments that
1487  // might be inreg.
1488  //
1489  // We currently expect it to be rare (particularly in well written code) for
1490  // arguments to be passed on the stack when there are still free integer
1491  // registers available (this would typically imply large structs being passed
1492  // by value), so this seems like a fair tradeoff for now.
1493  //
1494  // We can revisit this if the backend grows support for 'onstack' parameter
1495  // attributes. See PR12193.
1496  if (freeIntRegs == 0) {
1497    uint64_t Size = getContext().getTypeSize(Ty);
1498
1499    // If this type fits in an eightbyte, coerce it into the matching integral
1500    // type, which will end up on the stack (with alignment 8).
1501    if (Align == 8 && Size <= 64)
1502      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1503                                                          Size));
1504  }
1505
1506  return ABIArgInfo::getIndirect(Align);
1507}
1508
1509/// GetByteVectorType - The ABI specifies that a value should be passed in an
1510/// full vector XMM/YMM register.  Pick an LLVM IR type that will be passed as a
1511/// vector register.
1512llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
1513  llvm::Type *IRType = CGT.ConvertType(Ty);
1514
1515  // Wrapper structs that just contain vectors are passed just like vectors,
1516  // strip them off if present.
1517  llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1518  while (STy && STy->getNumElements() == 1) {
1519    IRType = STy->getElementType(0);
1520    STy = dyn_cast<llvm::StructType>(IRType);
1521  }
1522
1523  // If the preferred type is a 16-byte vector, prefer to pass it.
1524  if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1525    llvm::Type *EltTy = VT->getElementType();
1526    unsigned BitWidth = VT->getBitWidth();
1527    if ((BitWidth >= 128 && BitWidth <= 256) &&
1528        (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1529         EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1530         EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1531         EltTy->isIntegerTy(128)))
1532      return VT;
1533  }
1534
1535  return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1536}
1537
1538/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1539/// is known to either be off the end of the specified type or being in
1540/// alignment padding.  The user type specified is known to be at most 128 bits
1541/// in size, and have passed through X86_64ABIInfo::classify with a successful
1542/// classification that put one of the two halves in the INTEGER class.
1543///
1544/// It is conservatively correct to return false.
1545static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1546                                  unsigned EndBit, ASTContext &Context) {
1547  // If the bytes being queried are off the end of the type, there is no user
1548  // data hiding here.  This handles analysis of builtins, vectors and other
1549  // types that don't contain interesting padding.
1550  unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1551  if (TySize <= StartBit)
1552    return true;
1553
1554  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1555    unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1556    unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1557
1558    // Check each element to see if the element overlaps with the queried range.
1559    for (unsigned i = 0; i != NumElts; ++i) {
1560      // If the element is after the span we care about, then we're done..
1561      unsigned EltOffset = i*EltSize;
1562      if (EltOffset >= EndBit) break;
1563
1564      unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1565      if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1566                                 EndBit-EltOffset, Context))
1567        return false;
1568    }
1569    // If it overlaps no elements, then it is safe to process as padding.
1570    return true;
1571  }
1572
1573  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1574    const RecordDecl *RD = RT->getDecl();
1575    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1576
1577    // If this is a C++ record, check the bases first.
1578    if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1579      for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1580           e = CXXRD->bases_end(); i != e; ++i) {
1581        assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1582               "Unexpected base class!");
1583        const CXXRecordDecl *Base =
1584          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1585
1586        // If the base is after the span we care about, ignore it.
1587        unsigned BaseOffset = (unsigned)Layout.getBaseClassOffsetInBits(Base);
1588        if (BaseOffset >= EndBit) continue;
1589
1590        unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1591        if (!BitsContainNoUserData(i->getType(), BaseStart,
1592                                   EndBit-BaseOffset, Context))
1593          return false;
1594      }
1595    }
1596
1597    // Verify that no field has data that overlaps the region of interest.  Yes
1598    // this could be sped up a lot by being smarter about queried fields,
1599    // however we're only looking at structs up to 16 bytes, so we don't care
1600    // much.
1601    unsigned idx = 0;
1602    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1603         i != e; ++i, ++idx) {
1604      unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1605
1606      // If we found a field after the region we care about, then we're done.
1607      if (FieldOffset >= EndBit) break;
1608
1609      unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1610      if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1611                                 Context))
1612        return false;
1613    }
1614
1615    // If nothing in this record overlapped the area of interest, then we're
1616    // clean.
1617    return true;
1618  }
1619
1620  return false;
1621}
1622
1623/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1624/// float member at the specified offset.  For example, {int,{float}} has a
1625/// float at offset 4.  It is conservatively correct for this routine to return
1626/// false.
1627static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
1628                                  const llvm::TargetData &TD) {
1629  // Base case if we find a float.
1630  if (IROffset == 0 && IRType->isFloatTy())
1631    return true;
1632
1633  // If this is a struct, recurse into the field at the specified offset.
1634  if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1635    const llvm::StructLayout *SL = TD.getStructLayout(STy);
1636    unsigned Elt = SL->getElementContainingOffset(IROffset);
1637    IROffset -= SL->getElementOffset(Elt);
1638    return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1639  }
1640
1641  // If this is an array, recurse into the field at the specified offset.
1642  if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1643    llvm::Type *EltTy = ATy->getElementType();
1644    unsigned EltSize = TD.getTypeAllocSize(EltTy);
1645    IROffset -= IROffset/EltSize*EltSize;
1646    return ContainsFloatAtOffset(EltTy, IROffset, TD);
1647  }
1648
1649  return false;
1650}
1651
1652
1653/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1654/// low 8 bytes of an XMM register, corresponding to the SSE class.
1655llvm::Type *X86_64ABIInfo::
1656GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1657                   QualType SourceTy, unsigned SourceOffset) const {
1658  // The only three choices we have are either double, <2 x float>, or float. We
1659  // pass as float if the last 4 bytes is just padding.  This happens for
1660  // structs that contain 3 floats.
1661  if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1662                            SourceOffset*8+64, getContext()))
1663    return llvm::Type::getFloatTy(getVMContext());
1664
1665  // We want to pass as <2 x float> if the LLVM IR type contains a float at
1666  // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
1667  // case.
1668  if (ContainsFloatAtOffset(IRType, IROffset, getTargetData()) &&
1669      ContainsFloatAtOffset(IRType, IROffset+4, getTargetData()))
1670    return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1671
1672  return llvm::Type::getDoubleTy(getVMContext());
1673}
1674
1675
1676/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1677/// an 8-byte GPR.  This means that we either have a scalar or we are talking
1678/// about the high or low part of an up-to-16-byte struct.  This routine picks
1679/// the best LLVM IR type to represent this, which may be i64 or may be anything
1680/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1681/// etc).
1682///
1683/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1684/// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1685/// the 8-byte value references.  PrefType may be null.
1686///
1687/// SourceTy is the source level type for the entire argument.  SourceOffset is
1688/// an offset into this that we're processing (which is always either 0 or 8).
1689///
1690llvm::Type *X86_64ABIInfo::
1691GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1692                       QualType SourceTy, unsigned SourceOffset) const {
1693  // If we're dealing with an un-offset LLVM IR type, then it means that we're
1694  // returning an 8-byte unit starting with it.  See if we can safely use it.
1695  if (IROffset == 0) {
1696    // Pointers and int64's always fill the 8-byte unit.
1697    if (isa<llvm::PointerType>(IRType) || IRType->isIntegerTy(64))
1698      return IRType;
1699
1700    // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1701    // goodness in the source type is just tail padding.  This is allowed to
1702    // kick in for struct {double,int} on the int, but not on
1703    // struct{double,int,int} because we wouldn't return the second int.  We
1704    // have to do this analysis on the source type because we can't depend on
1705    // unions being lowered a specific way etc.
1706    if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
1707        IRType->isIntegerTy(32)) {
1708      unsigned BitWidth = cast<llvm::IntegerType>(IRType)->getBitWidth();
1709
1710      if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1711                                SourceOffset*8+64, getContext()))
1712        return IRType;
1713    }
1714  }
1715
1716  if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1717    // If this is a struct, recurse into the field at the specified offset.
1718    const llvm::StructLayout *SL = getTargetData().getStructLayout(STy);
1719    if (IROffset < SL->getSizeInBytes()) {
1720      unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1721      IROffset -= SL->getElementOffset(FieldIdx);
1722
1723      return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1724                                    SourceTy, SourceOffset);
1725    }
1726  }
1727
1728  if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1729    llvm::Type *EltTy = ATy->getElementType();
1730    unsigned EltSize = getTargetData().getTypeAllocSize(EltTy);
1731    unsigned EltOffset = IROffset/EltSize*EltSize;
1732    return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1733                                  SourceOffset);
1734  }
1735
1736  // Okay, we don't have any better idea of what to pass, so we pass this in an
1737  // integer register that isn't too big to fit the rest of the struct.
1738  unsigned TySizeInBytes =
1739    (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
1740
1741  assert(TySizeInBytes != SourceOffset && "Empty field?");
1742
1743  // It is always safe to classify this as an integer type up to i64 that
1744  // isn't larger than the structure.
1745  return llvm::IntegerType::get(getVMContext(),
1746                                std::min(TySizeInBytes-SourceOffset, 8U)*8);
1747}
1748
1749
1750/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
1751/// be used as elements of a two register pair to pass or return, return a
1752/// first class aggregate to represent them.  For example, if the low part of
1753/// a by-value argument should be passed as i32* and the high part as float,
1754/// return {i32*, float}.
1755static llvm::Type *
1756GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
1757                           const llvm::TargetData &TD) {
1758  // In order to correctly satisfy the ABI, we need to the high part to start
1759  // at offset 8.  If the high and low parts we inferred are both 4-byte types
1760  // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
1761  // the second element at offset 8.  Check for this:
1762  unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
1763  unsigned HiAlign = TD.getABITypeAlignment(Hi);
1764  unsigned HiStart = llvm::TargetData::RoundUpAlignment(LoSize, HiAlign);
1765  assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
1766
1767  // To handle this, we have to increase the size of the low part so that the
1768  // second element will start at an 8 byte offset.  We can't increase the size
1769  // of the second element because it might make us access off the end of the
1770  // struct.
1771  if (HiStart != 8) {
1772    // There are only two sorts of types the ABI generation code can produce for
1773    // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
1774    // Promote these to a larger type.
1775    if (Lo->isFloatTy())
1776      Lo = llvm::Type::getDoubleTy(Lo->getContext());
1777    else {
1778      assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
1779      Lo = llvm::Type::getInt64Ty(Lo->getContext());
1780    }
1781  }
1782
1783  llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
1784
1785
1786  // Verify that the second element is at an 8-byte offset.
1787  assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
1788         "Invalid x86-64 argument pair!");
1789  return Result;
1790}
1791
1792ABIArgInfo X86_64ABIInfo::
1793classifyReturnType(QualType RetTy) const {
1794  // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1795  // classification algorithm.
1796  X86_64ABIInfo::Class Lo, Hi;
1797  classify(RetTy, 0, Lo, Hi);
1798
1799  // Check some invariants.
1800  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1801  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1802
1803  llvm::Type *ResType = 0;
1804  switch (Lo) {
1805  case NoClass:
1806    if (Hi == NoClass)
1807      return ABIArgInfo::getIgnore();
1808    // If the low part is just padding, it takes no register, leave ResType
1809    // null.
1810    assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1811           "Unknown missing lo part");
1812    break;
1813
1814  case SSEUp:
1815  case X87Up:
1816    llvm_unreachable("Invalid classification for lo word.");
1817
1818    // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1819    // hidden argument.
1820  case Memory:
1821    return getIndirectReturnResult(RetTy);
1822
1823    // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1824    // available register of the sequence %rax, %rdx is used.
1825  case Integer:
1826    ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
1827
1828    // If we have a sign or zero extended integer, make sure to return Extend
1829    // so that the parameter gets the right LLVM IR attributes.
1830    if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1831      // Treat an enum type as its underlying type.
1832      if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1833        RetTy = EnumTy->getDecl()->getIntegerType();
1834
1835      if (RetTy->isIntegralOrEnumerationType() &&
1836          RetTy->isPromotableIntegerType())
1837        return ABIArgInfo::getExtend();
1838    }
1839    break;
1840
1841    // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1842    // available SSE register of the sequence %xmm0, %xmm1 is used.
1843  case SSE:
1844    ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
1845    break;
1846
1847    // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1848    // returned on the X87 stack in %st0 as 80-bit x87 number.
1849  case X87:
1850    ResType = llvm::Type::getX86_FP80Ty(getVMContext());
1851    break;
1852
1853    // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1854    // part of the value is returned in %st0 and the imaginary part in
1855    // %st1.
1856  case ComplexX87:
1857    assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1858    ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
1859                                    llvm::Type::getX86_FP80Ty(getVMContext()),
1860                                    NULL);
1861    break;
1862  }
1863
1864  llvm::Type *HighPart = 0;
1865  switch (Hi) {
1866    // Memory was handled previously and X87 should
1867    // never occur as a hi class.
1868  case Memory:
1869  case X87:
1870    llvm_unreachable("Invalid classification for hi word.");
1871
1872  case ComplexX87: // Previously handled.
1873  case NoClass:
1874    break;
1875
1876  case Integer:
1877    HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1878    if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1879      return ABIArgInfo::getDirect(HighPart, 8);
1880    break;
1881  case SSE:
1882    HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1883    if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1884      return ABIArgInfo::getDirect(HighPart, 8);
1885    break;
1886
1887    // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1888    // is passed in the next available eightbyte chunk if the last used
1889    // vector register.
1890    //
1891    // SSEUP should always be preceded by SSE, just widen.
1892  case SSEUp:
1893    assert(Lo == SSE && "Unexpected SSEUp classification.");
1894    ResType = GetByteVectorType(RetTy);
1895    break;
1896
1897    // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1898    // returned together with the previous X87 value in %st0.
1899  case X87Up:
1900    // If X87Up is preceded by X87, we don't need to do
1901    // anything. However, in some cases with unions it may not be
1902    // preceded by X87. In such situations we follow gcc and pass the
1903    // extra bits in an SSE reg.
1904    if (Lo != X87) {
1905      HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1906      if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1907        return ABIArgInfo::getDirect(HighPart, 8);
1908    }
1909    break;
1910  }
1911
1912  // If a high part was specified, merge it together with the low part.  It is
1913  // known to pass in the high eightbyte of the result.  We do this by forming a
1914  // first class struct aggregate with the high and low part: {low, high}
1915  if (HighPart)
1916    ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1917
1918  return ABIArgInfo::getDirect(ResType);
1919}
1920
1921ABIArgInfo X86_64ABIInfo::classifyArgumentType(
1922  QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE)
1923  const
1924{
1925  X86_64ABIInfo::Class Lo, Hi;
1926  classify(Ty, 0, Lo, Hi);
1927
1928  // Check some invariants.
1929  // FIXME: Enforce these by construction.
1930  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1931  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1932
1933  neededInt = 0;
1934  neededSSE = 0;
1935  llvm::Type *ResType = 0;
1936  switch (Lo) {
1937  case NoClass:
1938    if (Hi == NoClass)
1939      return ABIArgInfo::getIgnore();
1940    // If the low part is just padding, it takes no register, leave ResType
1941    // null.
1942    assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1943           "Unknown missing lo part");
1944    break;
1945
1946    // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1947    // on the stack.
1948  case Memory:
1949
1950    // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1951    // COMPLEX_X87, it is passed in memory.
1952  case X87:
1953  case ComplexX87:
1954    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1955      ++neededInt;
1956    return getIndirectResult(Ty, freeIntRegs);
1957
1958  case SSEUp:
1959  case X87Up:
1960    llvm_unreachable("Invalid classification for lo word.");
1961
1962    // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1963    // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1964    // and %r9 is used.
1965  case Integer:
1966    ++neededInt;
1967
1968    // Pick an 8-byte type based on the preferred type.
1969    ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
1970
1971    // If we have a sign or zero extended integer, make sure to return Extend
1972    // so that the parameter gets the right LLVM IR attributes.
1973    if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1974      // Treat an enum type as its underlying type.
1975      if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1976        Ty = EnumTy->getDecl()->getIntegerType();
1977
1978      if (Ty->isIntegralOrEnumerationType() &&
1979          Ty->isPromotableIntegerType())
1980        return ABIArgInfo::getExtend();
1981    }
1982
1983    break;
1984
1985    // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1986    // available SSE register is used, the registers are taken in the
1987    // order from %xmm0 to %xmm7.
1988  case SSE: {
1989    llvm::Type *IRType = CGT.ConvertType(Ty);
1990    ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
1991    ++neededSSE;
1992    break;
1993  }
1994  }
1995
1996  llvm::Type *HighPart = 0;
1997  switch (Hi) {
1998    // Memory was handled previously, ComplexX87 and X87 should
1999    // never occur as hi classes, and X87Up must be preceded by X87,
2000    // which is passed in memory.
2001  case Memory:
2002  case X87:
2003  case ComplexX87:
2004    llvm_unreachable("Invalid classification for hi word.");
2005
2006  case NoClass: break;
2007
2008  case Integer:
2009    ++neededInt;
2010    // Pick an 8-byte type based on the preferred type.
2011    HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2012
2013    if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2014      return ABIArgInfo::getDirect(HighPart, 8);
2015    break;
2016
2017    // X87Up generally doesn't occur here (long double is passed in
2018    // memory), except in situations involving unions.
2019  case X87Up:
2020  case SSE:
2021    HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2022
2023    if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2024      return ABIArgInfo::getDirect(HighPart, 8);
2025
2026    ++neededSSE;
2027    break;
2028
2029    // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2030    // eightbyte is passed in the upper half of the last used SSE
2031    // register.  This only happens when 128-bit vectors are passed.
2032  case SSEUp:
2033    assert(Lo == SSE && "Unexpected SSEUp classification");
2034    ResType = GetByteVectorType(Ty);
2035    break;
2036  }
2037
2038  // If a high part was specified, merge it together with the low part.  It is
2039  // known to pass in the high eightbyte of the result.  We do this by forming a
2040  // first class struct aggregate with the high and low part: {low, high}
2041  if (HighPart)
2042    ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
2043
2044  return ABIArgInfo::getDirect(ResType);
2045}
2046
2047void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2048
2049  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2050
2051  // Keep track of the number of assigned registers.
2052  unsigned freeIntRegs = 6, freeSSERegs = 8;
2053
2054  // If the return value is indirect, then the hidden argument is consuming one
2055  // integer register.
2056  if (FI.getReturnInfo().isIndirect())
2057    --freeIntRegs;
2058
2059  // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2060  // get assigned (in left-to-right order) for passing as follows...
2061  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2062       it != ie; ++it) {
2063    unsigned neededInt, neededSSE;
2064    it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2065                                    neededSSE);
2066
2067    // AMD64-ABI 3.2.3p3: If there are no registers available for any
2068    // eightbyte of an argument, the whole argument is passed on the
2069    // stack. If registers have already been assigned for some
2070    // eightbytes of such an argument, the assignments get reverted.
2071    if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
2072      freeIntRegs -= neededInt;
2073      freeSSERegs -= neededSSE;
2074    } else {
2075      it->info = getIndirectResult(it->type, freeIntRegs);
2076    }
2077  }
2078}
2079
2080static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2081                                        QualType Ty,
2082                                        CodeGenFunction &CGF) {
2083  llvm::Value *overflow_arg_area_p =
2084    CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2085  llvm::Value *overflow_arg_area =
2086    CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2087
2088  // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2089  // byte boundary if alignment needed by type exceeds 8 byte boundary.
2090  // It isn't stated explicitly in the standard, but in practice we use
2091  // alignment greater than 16 where necessary.
2092  uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2093  if (Align > 8) {
2094    // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
2095    llvm::Value *Offset =
2096      llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
2097    overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2098    llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
2099                                                    CGF.Int64Ty);
2100    llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
2101    overflow_arg_area =
2102      CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2103                                 overflow_arg_area->getType(),
2104                                 "overflow_arg_area.align");
2105  }
2106
2107  // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2108  llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2109  llvm::Value *Res =
2110    CGF.Builder.CreateBitCast(overflow_arg_area,
2111                              llvm::PointerType::getUnqual(LTy));
2112
2113  // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2114  // l->overflow_arg_area + sizeof(type).
2115  // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2116  // an 8 byte boundary.
2117
2118  uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2119  llvm::Value *Offset =
2120      llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
2121  overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2122                                            "overflow_arg_area.next");
2123  CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2124
2125  // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2126  return Res;
2127}
2128
2129llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2130                                      CodeGenFunction &CGF) const {
2131  // Assume that va_list type is correct; should be pointer to LLVM type:
2132  // struct {
2133  //   i32 gp_offset;
2134  //   i32 fp_offset;
2135  //   i8* overflow_arg_area;
2136  //   i8* reg_save_area;
2137  // };
2138  unsigned neededInt, neededSSE;
2139
2140  Ty = CGF.getContext().getCanonicalType(Ty);
2141  ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE);
2142
2143  // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2144  // in the registers. If not go to step 7.
2145  if (!neededInt && !neededSSE)
2146    return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2147
2148  // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2149  // general purpose registers needed to pass type and num_fp to hold
2150  // the number of floating point registers needed.
2151
2152  // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2153  // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2154  // l->fp_offset > 304 - num_fp * 16 go to step 7.
2155  //
2156  // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2157  // register save space).
2158
2159  llvm::Value *InRegs = 0;
2160  llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2161  llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2162  if (neededInt) {
2163    gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2164    gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2165    InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2166    InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2167  }
2168
2169  if (neededSSE) {
2170    fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2171    fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2172    llvm::Value *FitsInFP =
2173      llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2174    FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2175    InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2176  }
2177
2178  llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2179  llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2180  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2181  CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2182
2183  // Emit code to load the value if it was passed in registers.
2184
2185  CGF.EmitBlock(InRegBlock);
2186
2187  // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2188  // an offset of l->gp_offset and/or l->fp_offset. This may require
2189  // copying to a temporary location in case the parameter is passed
2190  // in different register classes or requires an alignment greater
2191  // than 8 for general purpose registers and 16 for XMM registers.
2192  //
2193  // FIXME: This really results in shameful code when we end up needing to
2194  // collect arguments from different places; often what should result in a
2195  // simple assembling of a structure from scattered addresses has many more
2196  // loads than necessary. Can we clean this up?
2197  llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2198  llvm::Value *RegAddr =
2199    CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2200                           "reg_save_area");
2201  if (neededInt && neededSSE) {
2202    // FIXME: Cleanup.
2203    assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2204    llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2205    llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
2206    assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2207    llvm::Type *TyLo = ST->getElementType(0);
2208    llvm::Type *TyHi = ST->getElementType(1);
2209    assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2210           "Unexpected ABI info for mixed regs");
2211    llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2212    llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2213    llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2214    llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2215    llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2216    llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
2217    llvm::Value *V =
2218      CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2219    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2220    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2221    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2222
2223    RegAddr = CGF.Builder.CreateBitCast(Tmp,
2224                                        llvm::PointerType::getUnqual(LTy));
2225  } else if (neededInt) {
2226    RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2227    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2228                                        llvm::PointerType::getUnqual(LTy));
2229  } else if (neededSSE == 1) {
2230    RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2231    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2232                                        llvm::PointerType::getUnqual(LTy));
2233  } else {
2234    assert(neededSSE == 2 && "Invalid number of needed registers!");
2235    // SSE registers are spaced 16 bytes apart in the register save
2236    // area, we need to collect the two eightbytes together.
2237    llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2238    llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2239    llvm::Type *DoubleTy = CGF.DoubleTy;
2240    llvm::Type *DblPtrTy =
2241      llvm::PointerType::getUnqual(DoubleTy);
2242    llvm::StructType *ST = llvm::StructType::get(DoubleTy,
2243                                                       DoubleTy, NULL);
2244    llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
2245    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2246                                                         DblPtrTy));
2247    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2248    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2249                                                         DblPtrTy));
2250    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2251    RegAddr = CGF.Builder.CreateBitCast(Tmp,
2252                                        llvm::PointerType::getUnqual(LTy));
2253  }
2254
2255  // AMD64-ABI 3.5.7p5: Step 5. Set:
2256  // l->gp_offset = l->gp_offset + num_gp * 8
2257  // l->fp_offset = l->fp_offset + num_fp * 16.
2258  if (neededInt) {
2259    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2260    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2261                            gp_offset_p);
2262  }
2263  if (neededSSE) {
2264    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2265    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2266                            fp_offset_p);
2267  }
2268  CGF.EmitBranch(ContBlock);
2269
2270  // Emit code to load the value if it was passed in memory.
2271
2272  CGF.EmitBlock(InMemBlock);
2273  llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2274
2275  // Return the appropriate result.
2276
2277  CGF.EmitBlock(ContBlock);
2278  llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2279                                                 "vaarg.addr");
2280  ResAddr->addIncoming(RegAddr, InRegBlock);
2281  ResAddr->addIncoming(MemAddr, InMemBlock);
2282  return ResAddr;
2283}
2284
2285ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
2286
2287  if (Ty->isVoidType())
2288    return ABIArgInfo::getIgnore();
2289
2290  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2291    Ty = EnumTy->getDecl()->getIntegerType();
2292
2293  uint64_t Size = getContext().getTypeSize(Ty);
2294
2295  if (const RecordType *RT = Ty->getAs<RecordType>()) {
2296    if (hasNonTrivialDestructorOrCopyConstructor(RT) ||
2297        RT->getDecl()->hasFlexibleArrayMember())
2298      return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2299
2300    // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2301    if (Size == 128 &&
2302        getContext().getTargetInfo().getTriple().getOS()
2303          == llvm::Triple::MinGW32)
2304      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2305                                                          Size));
2306
2307    // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2308    // not 1, 2, 4, or 8 bytes, must be passed by reference."
2309    if (Size <= 64 &&
2310        (Size & (Size - 1)) == 0)
2311      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2312                                                          Size));
2313
2314    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2315  }
2316
2317  if (Ty->isPromotableIntegerType())
2318    return ABIArgInfo::getExtend();
2319
2320  return ABIArgInfo::getDirect();
2321}
2322
2323void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2324
2325  QualType RetTy = FI.getReturnType();
2326  FI.getReturnInfo() = classify(RetTy);
2327
2328  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2329       it != ie; ++it)
2330    it->info = classify(it->type);
2331}
2332
2333llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2334                                      CodeGenFunction &CGF) const {
2335  llvm::Type *BPP = CGF.Int8PtrPtrTy;
2336
2337  CGBuilderTy &Builder = CGF.Builder;
2338  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2339                                                       "ap");
2340  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2341  llvm::Type *PTy =
2342    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2343  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2344
2345  uint64_t Offset =
2346    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2347  llvm::Value *NextAddr =
2348    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2349                      "ap.next");
2350  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2351
2352  return AddrTyped;
2353}
2354
2355// PowerPC-32
2356
2357namespace {
2358class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2359public:
2360  PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2361
2362  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2363    // This is recovered from gcc output.
2364    return 1; // r1 is the dedicated stack pointer
2365  }
2366
2367  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2368                               llvm::Value *Address) const;
2369};
2370
2371}
2372
2373bool
2374PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2375                                                llvm::Value *Address) const {
2376  // This is calculated from the LLVM and GCC tables and verified
2377  // against gcc output.  AFAIK all ABIs use the same encoding.
2378
2379  CodeGen::CGBuilderTy &Builder = CGF.Builder;
2380
2381  llvm::IntegerType *i8 = CGF.Int8Ty;
2382  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2383  llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2384  llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2385
2386  // 0-31: r0-31, the 4-byte general-purpose registers
2387  AssignToArrayRange(Builder, Address, Four8, 0, 31);
2388
2389  // 32-63: fp0-31, the 8-byte floating-point registers
2390  AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2391
2392  // 64-76 are various 4-byte special-purpose registers:
2393  // 64: mq
2394  // 65: lr
2395  // 66: ctr
2396  // 67: ap
2397  // 68-75 cr0-7
2398  // 76: xer
2399  AssignToArrayRange(Builder, Address, Four8, 64, 76);
2400
2401  // 77-108: v0-31, the 16-byte vector registers
2402  AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2403
2404  // 109: vrsave
2405  // 110: vscr
2406  // 111: spe_acc
2407  // 112: spefscr
2408  // 113: sfp
2409  AssignToArrayRange(Builder, Address, Four8, 109, 113);
2410
2411  return false;
2412}
2413
2414// PowerPC-64
2415
2416namespace {
2417class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2418public:
2419  PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2420
2421  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2422    // This is recovered from gcc output.
2423    return 1; // r1 is the dedicated stack pointer
2424  }
2425
2426  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2427                               llvm::Value *Address) const;
2428};
2429
2430}
2431
2432bool
2433PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2434                                                llvm::Value *Address) const {
2435  // This is calculated from the LLVM and GCC tables and verified
2436  // against gcc output.  AFAIK all ABIs use the same encoding.
2437
2438  CodeGen::CGBuilderTy &Builder = CGF.Builder;
2439
2440  llvm::IntegerType *i8 = CGF.Int8Ty;
2441  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2442  llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2443  llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2444
2445  // 0-31: r0-31, the 8-byte general-purpose registers
2446  AssignToArrayRange(Builder, Address, Eight8, 0, 31);
2447
2448  // 32-63: fp0-31, the 8-byte floating-point registers
2449  AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2450
2451  // 64-76 are various 4-byte special-purpose registers:
2452  // 64: mq
2453  // 65: lr
2454  // 66: ctr
2455  // 67: ap
2456  // 68-75 cr0-7
2457  // 76: xer
2458  AssignToArrayRange(Builder, Address, Four8, 64, 76);
2459
2460  // 77-108: v0-31, the 16-byte vector registers
2461  AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2462
2463  // 109: vrsave
2464  // 110: vscr
2465  // 111: spe_acc
2466  // 112: spefscr
2467  // 113: sfp
2468  AssignToArrayRange(Builder, Address, Four8, 109, 113);
2469
2470  return false;
2471}
2472
2473//===----------------------------------------------------------------------===//
2474// ARM ABI Implementation
2475//===----------------------------------------------------------------------===//
2476
2477namespace {
2478
2479class ARMABIInfo : public ABIInfo {
2480public:
2481  enum ABIKind {
2482    APCS = 0,
2483    AAPCS = 1,
2484    AAPCS_VFP
2485  };
2486
2487private:
2488  ABIKind Kind;
2489
2490public:
2491  ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
2492
2493  bool isEABI() const {
2494    StringRef Env =
2495      getContext().getTargetInfo().getTriple().getEnvironmentName();
2496    return (Env == "gnueabi" || Env == "eabi" || Env == "androideabi");
2497  }
2498
2499private:
2500  ABIKind getABIKind() const { return Kind; }
2501
2502  ABIArgInfo classifyReturnType(QualType RetTy) const;
2503  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2504
2505  virtual void computeInfo(CGFunctionInfo &FI) const;
2506
2507  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2508                                 CodeGenFunction &CGF) const;
2509};
2510
2511class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
2512public:
2513  ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
2514    :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
2515
2516  const ARMABIInfo &getABIInfo() const {
2517    return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
2518  }
2519
2520  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2521    return 13;
2522  }
2523
2524  StringRef getARCRetainAutoreleasedReturnValueMarker() const {
2525    return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
2526  }
2527
2528  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2529                               llvm::Value *Address) const {
2530    llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2531
2532    // 0-15 are the 16 integer registers.
2533    AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
2534    return false;
2535  }
2536
2537  unsigned getSizeOfUnwindException() const {
2538    if (getABIInfo().isEABI()) return 88;
2539    return TargetCodeGenInfo::getSizeOfUnwindException();
2540  }
2541};
2542
2543}
2544
2545void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
2546  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2547  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2548       it != ie; ++it)
2549    it->info = classifyArgumentType(it->type);
2550
2551  // Always honor user-specified calling convention.
2552  if (FI.getCallingConvention() != llvm::CallingConv::C)
2553    return;
2554
2555  // Calling convention as default by an ABI.
2556  llvm::CallingConv::ID DefaultCC;
2557  if (isEABI())
2558    DefaultCC = llvm::CallingConv::ARM_AAPCS;
2559  else
2560    DefaultCC = llvm::CallingConv::ARM_APCS;
2561
2562  // If user did not ask for specific calling convention explicitly (e.g. via
2563  // pcs attribute), set effective calling convention if it's different than ABI
2564  // default.
2565  switch (getABIKind()) {
2566  case APCS:
2567    if (DefaultCC != llvm::CallingConv::ARM_APCS)
2568      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
2569    break;
2570  case AAPCS:
2571    if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
2572      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
2573    break;
2574  case AAPCS_VFP:
2575    if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP)
2576      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
2577    break;
2578  }
2579}
2580
2581/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
2582/// aggregate.  If HAMembers is non-null, the number of base elements
2583/// contained in the type is returned through it; this is used for the
2584/// recursive calls that check aggregate component types.
2585static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
2586                                   ASTContext &Context,
2587                                   uint64_t *HAMembers = 0) {
2588  uint64_t Members = 0;
2589  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2590    if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
2591      return false;
2592    Members *= AT->getSize().getZExtValue();
2593  } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
2594    const RecordDecl *RD = RT->getDecl();
2595    if (RD->hasFlexibleArrayMember())
2596      return false;
2597
2598    Members = 0;
2599    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2600         i != e; ++i) {
2601      const FieldDecl *FD = &*i;
2602      uint64_t FldMembers;
2603      if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
2604        return false;
2605
2606      Members = (RD->isUnion() ?
2607                 std::max(Members, FldMembers) : Members + FldMembers);
2608    }
2609  } else {
2610    Members = 1;
2611    if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2612      Members = 2;
2613      Ty = CT->getElementType();
2614    }
2615
2616    // Homogeneous aggregates for AAPCS-VFP must have base types of float,
2617    // double, or 64-bit or 128-bit vectors.
2618    if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2619      if (BT->getKind() != BuiltinType::Float &&
2620          BT->getKind() != BuiltinType::Double)
2621        return false;
2622    } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
2623      unsigned VecSize = Context.getTypeSize(VT);
2624      if (VecSize != 64 && VecSize != 128)
2625        return false;
2626    } else {
2627      return false;
2628    }
2629
2630    // The base type must be the same for all members.  Vector types of the
2631    // same total size are treated as being equivalent here.
2632    const Type *TyPtr = Ty.getTypePtr();
2633    if (!Base)
2634      Base = TyPtr;
2635    if (Base != TyPtr &&
2636        (!Base->isVectorType() || !TyPtr->isVectorType() ||
2637         Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
2638      return false;
2639  }
2640
2641  // Homogeneous Aggregates can have at most 4 members of the base type.
2642  if (HAMembers)
2643    *HAMembers = Members;
2644
2645  return (Members > 0 && Members <= 4);
2646}
2647
2648ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
2649  if (!isAggregateTypeForABI(Ty)) {
2650    // Treat an enum type as its underlying type.
2651    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2652      Ty = EnumTy->getDecl()->getIntegerType();
2653
2654    return (Ty->isPromotableIntegerType() ?
2655            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2656  }
2657
2658  // Ignore empty records.
2659  if (isEmptyRecord(getContext(), Ty, true))
2660    return ABIArgInfo::getIgnore();
2661
2662  // Structures with either a non-trivial destructor or a non-trivial
2663  // copy constructor are always indirect.
2664  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2665    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2666
2667  if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
2668    // Homogeneous Aggregates need to be expanded.
2669    const Type *Base = 0;
2670    if (isHomogeneousAggregate(Ty, Base, getContext())) {
2671      assert(Base && "Base class should be set for homogeneous aggregate");
2672      return ABIArgInfo::getExpand();
2673    }
2674  }
2675
2676  // Otherwise, pass by coercing to a structure of the appropriate size.
2677  //
2678  // FIXME: This is kind of nasty... but there isn't much choice because the ARM
2679  // backend doesn't support byval.
2680  // FIXME: This doesn't handle alignment > 64 bits.
2681  llvm::Type* ElemTy;
2682  unsigned SizeRegs;
2683  if (getContext().getTypeAlign(Ty) > 32) {
2684    ElemTy = llvm::Type::getInt64Ty(getVMContext());
2685    SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
2686  } else {
2687    ElemTy = llvm::Type::getInt32Ty(getVMContext());
2688    SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
2689  }
2690
2691  llvm::Type *STy =
2692    llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
2693  return ABIArgInfo::getDirect(STy);
2694}
2695
2696static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
2697                              llvm::LLVMContext &VMContext) {
2698  // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
2699  // is called integer-like if its size is less than or equal to one word, and
2700  // the offset of each of its addressable sub-fields is zero.
2701
2702  uint64_t Size = Context.getTypeSize(Ty);
2703
2704  // Check that the type fits in a word.
2705  if (Size > 32)
2706    return false;
2707
2708  // FIXME: Handle vector types!
2709  if (Ty->isVectorType())
2710    return false;
2711
2712  // Float types are never treated as "integer like".
2713  if (Ty->isRealFloatingType())
2714    return false;
2715
2716  // If this is a builtin or pointer type then it is ok.
2717  if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
2718    return true;
2719
2720  // Small complex integer types are "integer like".
2721  if (const ComplexType *CT = Ty->getAs<ComplexType>())
2722    return isIntegerLikeType(CT->getElementType(), Context, VMContext);
2723
2724  // Single element and zero sized arrays should be allowed, by the definition
2725  // above, but they are not.
2726
2727  // Otherwise, it must be a record type.
2728  const RecordType *RT = Ty->getAs<RecordType>();
2729  if (!RT) return false;
2730
2731  // Ignore records with flexible arrays.
2732  const RecordDecl *RD = RT->getDecl();
2733  if (RD->hasFlexibleArrayMember())
2734    return false;
2735
2736  // Check that all sub-fields are at offset 0, and are themselves "integer
2737  // like".
2738  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2739
2740  bool HadField = false;
2741  unsigned idx = 0;
2742  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2743       i != e; ++i, ++idx) {
2744    const FieldDecl *FD = &*i;
2745
2746    // Bit-fields are not addressable, we only need to verify they are "integer
2747    // like". We still have to disallow a subsequent non-bitfield, for example:
2748    //   struct { int : 0; int x }
2749    // is non-integer like according to gcc.
2750    if (FD->isBitField()) {
2751      if (!RD->isUnion())
2752        HadField = true;
2753
2754      if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2755        return false;
2756
2757      continue;
2758    }
2759
2760    // Check if this field is at offset 0.
2761    if (Layout.getFieldOffset(idx) != 0)
2762      return false;
2763
2764    if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2765      return false;
2766
2767    // Only allow at most one field in a structure. This doesn't match the
2768    // wording above, but follows gcc in situations with a field following an
2769    // empty structure.
2770    if (!RD->isUnion()) {
2771      if (HadField)
2772        return false;
2773
2774      HadField = true;
2775    }
2776  }
2777
2778  return true;
2779}
2780
2781ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
2782  if (RetTy->isVoidType())
2783    return ABIArgInfo::getIgnore();
2784
2785  // Large vector types should be returned via memory.
2786  if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
2787    return ABIArgInfo::getIndirect(0);
2788
2789  if (!isAggregateTypeForABI(RetTy)) {
2790    // Treat an enum type as its underlying type.
2791    if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2792      RetTy = EnumTy->getDecl()->getIntegerType();
2793
2794    return (RetTy->isPromotableIntegerType() ?
2795            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2796  }
2797
2798  // Structures with either a non-trivial destructor or a non-trivial
2799  // copy constructor are always indirect.
2800  if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
2801    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2802
2803  // Are we following APCS?
2804  if (getABIKind() == APCS) {
2805    if (isEmptyRecord(getContext(), RetTy, false))
2806      return ABIArgInfo::getIgnore();
2807
2808    // Complex types are all returned as packed integers.
2809    //
2810    // FIXME: Consider using 2 x vector types if the back end handles them
2811    // correctly.
2812    if (RetTy->isAnyComplexType())
2813      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2814                                              getContext().getTypeSize(RetTy)));
2815
2816    // Integer like structures are returned in r0.
2817    if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
2818      // Return in the smallest viable integer type.
2819      uint64_t Size = getContext().getTypeSize(RetTy);
2820      if (Size <= 8)
2821        return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2822      if (Size <= 16)
2823        return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2824      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2825    }
2826
2827    // Otherwise return in memory.
2828    return ABIArgInfo::getIndirect(0);
2829  }
2830
2831  // Otherwise this is an AAPCS variant.
2832
2833  if (isEmptyRecord(getContext(), RetTy, true))
2834    return ABIArgInfo::getIgnore();
2835
2836  // Check for homogeneous aggregates with AAPCS-VFP.
2837  if (getABIKind() == AAPCS_VFP) {
2838    const Type *Base = 0;
2839    if (isHomogeneousAggregate(RetTy, Base, getContext())) {
2840      assert(Base && "Base class should be set for homogeneous aggregate");
2841      // Homogeneous Aggregates are returned directly.
2842      return ABIArgInfo::getDirect();
2843    }
2844  }
2845
2846  // Aggregates <= 4 bytes are returned in r0; other aggregates
2847  // are returned indirectly.
2848  uint64_t Size = getContext().getTypeSize(RetTy);
2849  if (Size <= 32) {
2850    // Return in the smallest viable integer type.
2851    if (Size <= 8)
2852      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2853    if (Size <= 16)
2854      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2855    return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2856  }
2857
2858  return ABIArgInfo::getIndirect(0);
2859}
2860
2861llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2862                                   CodeGenFunction &CGF) const {
2863  llvm::Type *BP = CGF.Int8PtrTy;
2864  llvm::Type *BPP = CGF.Int8PtrPtrTy;
2865
2866  CGBuilderTy &Builder = CGF.Builder;
2867  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2868  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2869  // Handle address alignment for type alignment > 32 bits
2870  uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
2871  if (TyAlign > 4) {
2872    assert((TyAlign & (TyAlign - 1)) == 0 &&
2873           "Alignment is not power of 2!");
2874    llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
2875    AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
2876    AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
2877    Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2878  }
2879  llvm::Type *PTy =
2880    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2881  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2882
2883  uint64_t Offset =
2884    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
2885  llvm::Value *NextAddr =
2886    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2887                      "ap.next");
2888  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2889
2890  return AddrTyped;
2891}
2892
2893//===----------------------------------------------------------------------===//
2894// NVPTX ABI Implementation
2895//===----------------------------------------------------------------------===//
2896
2897namespace {
2898
2899class NVPTXABIInfo : public ABIInfo {
2900public:
2901  NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2902
2903  ABIArgInfo classifyReturnType(QualType RetTy) const;
2904  ABIArgInfo classifyArgumentType(QualType Ty) const;
2905
2906  virtual void computeInfo(CGFunctionInfo &FI) const;
2907  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2908                                 CodeGenFunction &CFG) const;
2909};
2910
2911class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
2912public:
2913  NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
2914    : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
2915
2916  virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2917                                   CodeGen::CodeGenModule &M) const;
2918};
2919
2920ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
2921  if (RetTy->isVoidType())
2922    return ABIArgInfo::getIgnore();
2923  if (isAggregateTypeForABI(RetTy))
2924    return ABIArgInfo::getIndirect(0);
2925  return ABIArgInfo::getDirect();
2926}
2927
2928ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
2929  if (isAggregateTypeForABI(Ty))
2930    return ABIArgInfo::getIndirect(0);
2931
2932  return ABIArgInfo::getDirect();
2933}
2934
2935void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
2936  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2937  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2938       it != ie; ++it)
2939    it->info = classifyArgumentType(it->type);
2940
2941  // Always honor user-specified calling convention.
2942  if (FI.getCallingConvention() != llvm::CallingConv::C)
2943    return;
2944
2945  // Calling convention as default by an ABI.
2946  // We're still using the PTX_Kernel/PTX_Device calling conventions here,
2947  // but we should switch to NVVM metadata later on.
2948  llvm::CallingConv::ID DefaultCC;
2949  const LangOptions &LangOpts = getContext().getLangOpts();
2950  if (LangOpts.OpenCL || LangOpts.CUDA) {
2951    // If we are in OpenCL or CUDA mode, then default to device functions
2952    DefaultCC = llvm::CallingConv::PTX_Device;
2953  } else {
2954    // If we are in standard C/C++ mode, use the triple to decide on the default
2955    StringRef Env =
2956      getContext().getTargetInfo().getTriple().getEnvironmentName();
2957    if (Env == "device")
2958      DefaultCC = llvm::CallingConv::PTX_Device;
2959    else
2960      DefaultCC = llvm::CallingConv::PTX_Kernel;
2961  }
2962  FI.setEffectiveCallingConvention(DefaultCC);
2963
2964}
2965
2966llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2967                                     CodeGenFunction &CFG) const {
2968  llvm_unreachable("NVPTX does not support varargs");
2969}
2970
2971void NVPTXTargetCodeGenInfo::
2972SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2973                    CodeGen::CodeGenModule &M) const{
2974  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2975  if (!FD) return;
2976
2977  llvm::Function *F = cast<llvm::Function>(GV);
2978
2979  // Perform special handling in OpenCL mode
2980  if (M.getLangOpts().OpenCL) {
2981    // Use OpenCL function attributes to set proper calling conventions
2982    // By default, all functions are device functions
2983    if (FD->hasAttr<OpenCLKernelAttr>()) {
2984      // OpenCL __kernel functions get a kernel calling convention
2985      F->setCallingConv(llvm::CallingConv::PTX_Kernel);
2986      // And kernel functions are not subject to inlining
2987      F->addFnAttr(llvm::Attribute::NoInline);
2988    }
2989  }
2990
2991  // Perform special handling in CUDA mode.
2992  if (M.getLangOpts().CUDA) {
2993    // CUDA __global__ functions get a kernel calling convention.  Since
2994    // __global__ functions cannot be called from the device, we do not
2995    // need to set the noinline attribute.
2996    if (FD->getAttr<CUDAGlobalAttr>())
2997      F->setCallingConv(llvm::CallingConv::PTX_Kernel);
2998  }
2999}
3000
3001}
3002
3003//===----------------------------------------------------------------------===//
3004// MBlaze ABI Implementation
3005//===----------------------------------------------------------------------===//
3006
3007namespace {
3008
3009class MBlazeABIInfo : public ABIInfo {
3010public:
3011  MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3012
3013  bool isPromotableIntegerType(QualType Ty) const;
3014
3015  ABIArgInfo classifyReturnType(QualType RetTy) const;
3016  ABIArgInfo classifyArgumentType(QualType RetTy) const;
3017
3018  virtual void computeInfo(CGFunctionInfo &FI) const {
3019    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3020    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3021         it != ie; ++it)
3022      it->info = classifyArgumentType(it->type);
3023  }
3024
3025  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3026                                 CodeGenFunction &CGF) const;
3027};
3028
3029class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
3030public:
3031  MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
3032    : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
3033  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3034                           CodeGen::CodeGenModule &M) const;
3035};
3036
3037}
3038
3039bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
3040  // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
3041  if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3042    switch (BT->getKind()) {
3043    case BuiltinType::Bool:
3044    case BuiltinType::Char_S:
3045    case BuiltinType::Char_U:
3046    case BuiltinType::SChar:
3047    case BuiltinType::UChar:
3048    case BuiltinType::Short:
3049    case BuiltinType::UShort:
3050      return true;
3051    default:
3052      return false;
3053    }
3054  return false;
3055}
3056
3057llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3058                                      CodeGenFunction &CGF) const {
3059  // FIXME: Implement
3060  return 0;
3061}
3062
3063
3064ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
3065  if (RetTy->isVoidType())
3066    return ABIArgInfo::getIgnore();
3067  if (isAggregateTypeForABI(RetTy))
3068    return ABIArgInfo::getIndirect(0);
3069
3070  return (isPromotableIntegerType(RetTy) ?
3071          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3072}
3073
3074ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
3075  if (isAggregateTypeForABI(Ty))
3076    return ABIArgInfo::getIndirect(0);
3077
3078  return (isPromotableIntegerType(Ty) ?
3079          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3080}
3081
3082void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3083                                                  llvm::GlobalValue *GV,
3084                                                  CodeGen::CodeGenModule &M)
3085                                                  const {
3086  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3087  if (!FD) return;
3088
3089  llvm::CallingConv::ID CC = llvm::CallingConv::C;
3090  if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
3091    CC = llvm::CallingConv::MBLAZE_INTR;
3092  else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
3093    CC = llvm::CallingConv::MBLAZE_SVOL;
3094
3095  if (CC != llvm::CallingConv::C) {
3096      // Handle 'interrupt_handler' attribute:
3097      llvm::Function *F = cast<llvm::Function>(GV);
3098
3099      // Step 1: Set ISR calling convention.
3100      F->setCallingConv(CC);
3101
3102      // Step 2: Add attributes goodness.
3103      F->addFnAttr(llvm::Attribute::NoInline);
3104  }
3105
3106  // Step 3: Emit _interrupt_handler alias.
3107  if (CC == llvm::CallingConv::MBLAZE_INTR)
3108    new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3109                          "_interrupt_handler", GV, &M.getModule());
3110}
3111
3112
3113//===----------------------------------------------------------------------===//
3114// MSP430 ABI Implementation
3115//===----------------------------------------------------------------------===//
3116
3117namespace {
3118
3119class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
3120public:
3121  MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
3122    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
3123  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3124                           CodeGen::CodeGenModule &M) const;
3125};
3126
3127}
3128
3129void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3130                                                  llvm::GlobalValue *GV,
3131                                             CodeGen::CodeGenModule &M) const {
3132  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3133    if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
3134      // Handle 'interrupt' attribute:
3135      llvm::Function *F = cast<llvm::Function>(GV);
3136
3137      // Step 1: Set ISR calling convention.
3138      F->setCallingConv(llvm::CallingConv::MSP430_INTR);
3139
3140      // Step 2: Add attributes goodness.
3141      F->addFnAttr(llvm::Attribute::NoInline);
3142
3143      // Step 3: Emit ISR vector alias.
3144      unsigned Num = attr->getNumber() + 0xffe0;
3145      new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3146                            "vector_" + Twine::utohexstr(Num),
3147                            GV, &M.getModule());
3148    }
3149  }
3150}
3151
3152//===----------------------------------------------------------------------===//
3153// MIPS ABI Implementation.  This works for both little-endian and
3154// big-endian variants.
3155//===----------------------------------------------------------------------===//
3156
3157namespace {
3158class MipsABIInfo : public ABIInfo {
3159  bool IsO32;
3160  unsigned MinABIStackAlignInBytes;
3161  llvm::Type* CoerceToIntArgs(uint64_t TySize) const;
3162  llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
3163  llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
3164  llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
3165public:
3166  MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
3167    ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8) {}
3168
3169  ABIArgInfo classifyReturnType(QualType RetTy) const;
3170  ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
3171  virtual void computeInfo(CGFunctionInfo &FI) const;
3172  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3173                                 CodeGenFunction &CGF) const;
3174};
3175
3176class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
3177  unsigned SizeOfUnwindException;
3178public:
3179  MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
3180    : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
3181      SizeOfUnwindException(IsO32 ? 24 : 32) {}
3182
3183  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
3184    return 29;
3185  }
3186
3187  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3188                               llvm::Value *Address) const;
3189
3190  unsigned getSizeOfUnwindException() const {
3191    return SizeOfUnwindException;
3192  }
3193};
3194}
3195
3196llvm::Type* MipsABIInfo::CoerceToIntArgs(uint64_t TySize) const {
3197  SmallVector<llvm::Type*, 8> ArgList;
3198  llvm::IntegerType *IntTy = llvm::IntegerType::get(getVMContext(),
3199                                                    MinABIStackAlignInBytes * 8);
3200
3201  // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
3202  for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
3203    ArgList.push_back(IntTy);
3204
3205  // If necessary, add one more integer type to ArgList.
3206  unsigned R = TySize % (MinABIStackAlignInBytes * 8);
3207
3208  if (R)
3209    ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
3210
3211  return llvm::StructType::get(getVMContext(), ArgList);
3212}
3213
3214// In N32/64, an aligned double precision floating point field is passed in
3215// a register.
3216llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
3217  if (IsO32)
3218    return CoerceToIntArgs(TySize);
3219
3220  if (Ty->isComplexType())
3221    return CGT.ConvertType(Ty);
3222
3223  const RecordType *RT = Ty->getAs<RecordType>();
3224
3225  // Unions are passed in integer registers.
3226  if (!RT || !RT->isStructureOrClassType())
3227    return CoerceToIntArgs(TySize);
3228
3229  const RecordDecl *RD = RT->getDecl();
3230  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3231  assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
3232
3233  uint64_t LastOffset = 0;
3234  unsigned idx = 0;
3235  llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
3236  SmallVector<llvm::Type*, 8> ArgList;
3237
3238  // Iterate over fields in the struct/class and check if there are any aligned
3239  // double fields.
3240  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3241       i != e; ++i, ++idx) {
3242    const QualType Ty = i->getType();
3243    const BuiltinType *BT = Ty->getAs<BuiltinType>();
3244
3245    if (!BT || BT->getKind() != BuiltinType::Double)
3246      continue;
3247
3248    uint64_t Offset = Layout.getFieldOffset(idx);
3249    if (Offset % 64) // Ignore doubles that are not aligned.
3250      continue;
3251
3252    // Add ((Offset - LastOffset) / 64) args of type i64.
3253    for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
3254      ArgList.push_back(I64);
3255
3256    // Add double type.
3257    ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
3258    LastOffset = Offset + 64;
3259  }
3260
3261  // Add ((TySize - LastOffset) / 64) args of type i64.
3262  for (unsigned N = (TySize - LastOffset) / 64; N; --N)
3263    ArgList.push_back(I64);
3264
3265  // If the size of the remainder is not zero, add one more integer type to
3266  // ArgList.
3267  unsigned R = (TySize - LastOffset) % 64;
3268  if (R)
3269    ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
3270
3271  return llvm::StructType::get(getVMContext(), ArgList);
3272}
3273
3274llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const {
3275  assert((Offset % MinABIStackAlignInBytes) == 0);
3276
3277  if ((Align - 1) & Offset)
3278    return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
3279
3280  return 0;
3281}
3282
3283ABIArgInfo
3284MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
3285  uint64_t OrigOffset = Offset;
3286  uint64_t TySize = getContext().getTypeSize(Ty);
3287  uint64_t Align = getContext().getTypeAlign(Ty) / 8;
3288
3289  Align = std::max(Align, (uint64_t)MinABIStackAlignInBytes);
3290  Offset = llvm::RoundUpToAlignment(Offset, Align);
3291  Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
3292
3293  if (isAggregateTypeForABI(Ty)) {
3294    // Ignore empty aggregates.
3295    if (TySize == 0)
3296      return ABIArgInfo::getIgnore();
3297
3298    // Records with non trivial destructors/constructors should not be passed
3299    // by value.
3300    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) {
3301      Offset = OrigOffset + MinABIStackAlignInBytes;
3302      return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3303    }
3304
3305    // If we have reached here, aggregates are passed directly by coercing to
3306    // another structure type. Padding is inserted if the offset of the
3307    // aggregate is unaligned.
3308    return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
3309                                 getPaddingType(Align, OrigOffset));
3310  }
3311
3312  // Treat an enum type as its underlying type.
3313  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3314    Ty = EnumTy->getDecl()->getIntegerType();
3315
3316  if (Ty->isPromotableIntegerType())
3317    return ABIArgInfo::getExtend();
3318
3319  return ABIArgInfo::getDirect(0, 0, getPaddingType(Align, OrigOffset));
3320}
3321
3322llvm::Type*
3323MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
3324  const RecordType *RT = RetTy->getAs<RecordType>();
3325  SmallVector<llvm::Type*, 2> RTList;
3326
3327  if (RT && RT->isStructureOrClassType()) {
3328    const RecordDecl *RD = RT->getDecl();
3329    const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3330    unsigned FieldCnt = Layout.getFieldCount();
3331
3332    // N32/64 returns struct/classes in floating point registers if the
3333    // following conditions are met:
3334    // 1. The size of the struct/class is no larger than 128-bit.
3335    // 2. The struct/class has one or two fields all of which are floating
3336    //    point types.
3337    // 3. The offset of the first field is zero (this follows what gcc does).
3338    //
3339    // Any other composite results are returned in integer registers.
3340    //
3341    if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
3342      RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
3343      for (; b != e; ++b) {
3344        const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
3345
3346        if (!BT || !BT->isFloatingPoint())
3347          break;
3348
3349        RTList.push_back(CGT.ConvertType(b->getType()));
3350      }
3351
3352      if (b == e)
3353        return llvm::StructType::get(getVMContext(), RTList,
3354                                     RD->hasAttr<PackedAttr>());
3355
3356      RTList.clear();
3357    }
3358  }
3359
3360  RTList.push_back(llvm::IntegerType::get(getVMContext(),
3361                                          std::min(Size, (uint64_t)64)));
3362  if (Size > 64)
3363    RTList.push_back(llvm::IntegerType::get(getVMContext(), Size - 64));
3364
3365  return llvm::StructType::get(getVMContext(), RTList);
3366}
3367
3368ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
3369  uint64_t Size = getContext().getTypeSize(RetTy);
3370
3371  if (RetTy->isVoidType() || Size == 0)
3372    return ABIArgInfo::getIgnore();
3373
3374  if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
3375    if (Size <= 128) {
3376      if (RetTy->isAnyComplexType())
3377        return ABIArgInfo::getDirect();
3378
3379      if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
3380        return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
3381    }
3382
3383    return ABIArgInfo::getIndirect(0);
3384  }
3385
3386  // Treat an enum type as its underlying type.
3387  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3388    RetTy = EnumTy->getDecl()->getIntegerType();
3389
3390  return (RetTy->isPromotableIntegerType() ?
3391          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3392}
3393
3394void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
3395  ABIArgInfo &RetInfo = FI.getReturnInfo();
3396  RetInfo = classifyReturnType(FI.getReturnType());
3397
3398  // Check if a pointer to an aggregate is passed as a hidden argument.
3399  uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
3400
3401  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3402       it != ie; ++it)
3403    it->info = classifyArgumentType(it->type, Offset);
3404}
3405
3406llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3407                                    CodeGenFunction &CGF) const {
3408  llvm::Type *BP = CGF.Int8PtrTy;
3409  llvm::Type *BPP = CGF.Int8PtrPtrTy;
3410
3411  CGBuilderTy &Builder = CGF.Builder;
3412  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3413  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3414  int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
3415  llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3416  llvm::Value *AddrTyped;
3417  unsigned PtrWidth = getContext().getTargetInfo().getPointerWidth(0);
3418  llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
3419
3420  if (TypeAlign > MinABIStackAlignInBytes) {
3421    llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
3422    llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
3423    llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
3424    llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
3425    llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
3426    AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
3427  }
3428  else
3429    AddrTyped = Builder.CreateBitCast(Addr, PTy);
3430
3431  llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
3432  TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
3433  uint64_t Offset =
3434    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
3435  llvm::Value *NextAddr =
3436    Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
3437                      "ap.next");
3438  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3439
3440  return AddrTyped;
3441}
3442
3443bool
3444MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3445                                               llvm::Value *Address) const {
3446  // This information comes from gcc's implementation, which seems to
3447  // as canonical as it gets.
3448
3449  // Everything on MIPS is 4 bytes.  Double-precision FP registers
3450  // are aliased to pairs of single-precision FP registers.
3451  llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
3452
3453  // 0-31 are the general purpose registers, $0 - $31.
3454  // 32-63 are the floating-point registers, $f0 - $f31.
3455  // 64 and 65 are the multiply/divide registers, $hi and $lo.
3456  // 66 is the (notional, I think) register for signal-handler return.
3457  AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
3458
3459  // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
3460  // They are one bit wide and ignored here.
3461
3462  // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
3463  // (coprocessor 1 is the FP unit)
3464  // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
3465  // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
3466  // 176-181 are the DSP accumulator registers.
3467  AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
3468  return false;
3469}
3470
3471//===----------------------------------------------------------------------===//
3472// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
3473// Currently subclassed only to implement custom OpenCL C function attribute
3474// handling.
3475//===----------------------------------------------------------------------===//
3476
3477namespace {
3478
3479class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3480public:
3481  TCETargetCodeGenInfo(CodeGenTypes &CGT)
3482    : DefaultTargetCodeGenInfo(CGT) {}
3483
3484  virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3485                                   CodeGen::CodeGenModule &M) const;
3486};
3487
3488void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3489                                               llvm::GlobalValue *GV,
3490                                               CodeGen::CodeGenModule &M) const {
3491  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3492  if (!FD) return;
3493
3494  llvm::Function *F = cast<llvm::Function>(GV);
3495
3496  if (M.getLangOpts().OpenCL) {
3497    if (FD->hasAttr<OpenCLKernelAttr>()) {
3498      // OpenCL C Kernel functions are not subject to inlining
3499      F->addFnAttr(llvm::Attribute::NoInline);
3500
3501      if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
3502
3503        // Convert the reqd_work_group_size() attributes to metadata.
3504        llvm::LLVMContext &Context = F->getContext();
3505        llvm::NamedMDNode *OpenCLMetadata =
3506            M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
3507
3508        SmallVector<llvm::Value*, 5> Operands;
3509        Operands.push_back(F);
3510
3511        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3512                             llvm::APInt(32,
3513                             FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
3514        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3515                             llvm::APInt(32,
3516                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
3517        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3518                             llvm::APInt(32,
3519                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
3520
3521        // Add a boolean constant operand for "required" (true) or "hint" (false)
3522        // for implementing the work_group_size_hint attr later. Currently
3523        // always true as the hint is not yet implemented.
3524        Operands.push_back(llvm::ConstantInt::getTrue(Context));
3525        OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
3526      }
3527    }
3528  }
3529}
3530
3531}
3532
3533//===----------------------------------------------------------------------===//
3534// Hexagon ABI Implementation
3535//===----------------------------------------------------------------------===//
3536
3537namespace {
3538
3539class HexagonABIInfo : public ABIInfo {
3540
3541
3542public:
3543  HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3544
3545private:
3546
3547  ABIArgInfo classifyReturnType(QualType RetTy) const;
3548  ABIArgInfo classifyArgumentType(QualType RetTy) const;
3549
3550  virtual void computeInfo(CGFunctionInfo &FI) const;
3551
3552  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3553                                 CodeGenFunction &CGF) const;
3554};
3555
3556class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
3557public:
3558  HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
3559    :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
3560
3561  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3562    return 29;
3563  }
3564};
3565
3566}
3567
3568void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
3569  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3570  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3571       it != ie; ++it)
3572    it->info = classifyArgumentType(it->type);
3573}
3574
3575ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
3576  if (!isAggregateTypeForABI(Ty)) {
3577    // Treat an enum type as its underlying type.
3578    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3579      Ty = EnumTy->getDecl()->getIntegerType();
3580
3581    return (Ty->isPromotableIntegerType() ?
3582            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3583  }
3584
3585  // Ignore empty records.
3586  if (isEmptyRecord(getContext(), Ty, true))
3587    return ABIArgInfo::getIgnore();
3588
3589  // Structures with either a non-trivial destructor or a non-trivial
3590  // copy constructor are always indirect.
3591  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
3592    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3593
3594  uint64_t Size = getContext().getTypeSize(Ty);
3595  if (Size > 64)
3596    return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
3597    // Pass in the smallest viable integer type.
3598  else if (Size > 32)
3599      return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
3600  else if (Size > 16)
3601      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3602  else if (Size > 8)
3603      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3604  else
3605      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3606}
3607
3608ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
3609  if (RetTy->isVoidType())
3610    return ABIArgInfo::getIgnore();
3611
3612  // Large vector types should be returned via memory.
3613  if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
3614    return ABIArgInfo::getIndirect(0);
3615
3616  if (!isAggregateTypeForABI(RetTy)) {
3617    // Treat an enum type as its underlying type.
3618    if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3619      RetTy = EnumTy->getDecl()->getIntegerType();
3620
3621    return (RetTy->isPromotableIntegerType() ?
3622            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3623  }
3624
3625  // Structures with either a non-trivial destructor or a non-trivial
3626  // copy constructor are always indirect.
3627  if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
3628    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3629
3630  if (isEmptyRecord(getContext(), RetTy, true))
3631    return ABIArgInfo::getIgnore();
3632
3633  // Aggregates <= 8 bytes are returned in r0; other aggregates
3634  // are returned indirectly.
3635  uint64_t Size = getContext().getTypeSize(RetTy);
3636  if (Size <= 64) {
3637    // Return in the smallest viable integer type.
3638    if (Size <= 8)
3639      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3640    if (Size <= 16)
3641      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3642    if (Size <= 32)
3643      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3644    return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
3645  }
3646
3647  return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
3648}
3649
3650llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3651                                       CodeGenFunction &CGF) const {
3652  // FIXME: Need to handle alignment
3653  llvm::Type *BPP = CGF.Int8PtrPtrTy;
3654
3655  CGBuilderTy &Builder = CGF.Builder;
3656  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3657                                                       "ap");
3658  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3659  llvm::Type *PTy =
3660    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3661  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3662
3663  uint64_t Offset =
3664    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
3665  llvm::Value *NextAddr =
3666    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3667                      "ap.next");
3668  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3669
3670  return AddrTyped;
3671}
3672
3673
3674const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
3675  if (TheTargetCodeGenInfo)
3676    return *TheTargetCodeGenInfo;
3677
3678  const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
3679  switch (Triple.getArch()) {
3680  default:
3681    return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
3682
3683  case llvm::Triple::mips:
3684  case llvm::Triple::mipsel:
3685    return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
3686
3687  case llvm::Triple::mips64:
3688  case llvm::Triple::mips64el:
3689    return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
3690
3691  case llvm::Triple::arm:
3692  case llvm::Triple::thumb:
3693    {
3694      ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
3695
3696      if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0)
3697        Kind = ARMABIInfo::APCS;
3698      else if (CodeGenOpts.FloatABI == "hard")
3699        Kind = ARMABIInfo::AAPCS_VFP;
3700
3701      return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
3702    }
3703
3704  case llvm::Triple::ppc:
3705    return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
3706  case llvm::Triple::ppc64:
3707    return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
3708
3709  case llvm::Triple::nvptx:
3710  case llvm::Triple::nvptx64:
3711    return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
3712
3713  case llvm::Triple::mblaze:
3714    return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
3715
3716  case llvm::Triple::msp430:
3717    return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
3718
3719  case llvm::Triple::tce:
3720    return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
3721
3722  case llvm::Triple::x86: {
3723    bool DisableMMX = strcmp(getContext().getTargetInfo().getABI(), "no-mmx") == 0;
3724
3725    if (Triple.isOSDarwin())
3726      return *(TheTargetCodeGenInfo =
3727               new X86_32TargetCodeGenInfo(
3728                 Types, true, true, DisableMMX, false));
3729
3730    switch (Triple.getOS()) {
3731    case llvm::Triple::Cygwin:
3732    case llvm::Triple::MinGW32:
3733    case llvm::Triple::AuroraUX:
3734    case llvm::Triple::DragonFly:
3735    case llvm::Triple::FreeBSD:
3736    case llvm::Triple::OpenBSD:
3737      return *(TheTargetCodeGenInfo =
3738               new X86_32TargetCodeGenInfo(
3739                 Types, false, true, DisableMMX, false));
3740
3741    case llvm::Triple::Win32:
3742      return *(TheTargetCodeGenInfo =
3743               new X86_32TargetCodeGenInfo(
3744                 Types, false, true, DisableMMX, true));
3745
3746    default:
3747      return *(TheTargetCodeGenInfo =
3748               new X86_32TargetCodeGenInfo(
3749                 Types, false, false, DisableMMX, false));
3750    }
3751  }
3752
3753  case llvm::Triple::x86_64: {
3754    bool HasAVX = strcmp(getContext().getTargetInfo().getABI(), "avx") == 0;
3755
3756    switch (Triple.getOS()) {
3757    case llvm::Triple::Win32:
3758    case llvm::Triple::MinGW32:
3759    case llvm::Triple::Cygwin:
3760      return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
3761    default:
3762      return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
3763                                                                  HasAVX));
3764    }
3765  }
3766  case llvm::Triple::hexagon:
3767    return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
3768  }
3769}
3770