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