TargetInfo.cpp revision 4857947d18a7d0d0c250892fc5597ec0aecc9823
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  llvm::raw_ostream &OS = llvm::errs();
61  OS << "(ABIArgInfo Kind=";
62  switch (TheKind) {
63  case Direct:
64    OS << "Direct Type=";
65    if (const 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       << " Byal=" << 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
90static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
91
92/// isEmptyField - Return true iff a the field is "empty", that is it
93/// is an unnamed bit-field or an (array of) empty record(s).
94static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
95                         bool AllowArrays) {
96  if (FD->isUnnamedBitfield())
97    return true;
98
99  QualType FT = FD->getType();
100
101    // Constant arrays of empty records count as empty, strip them off.
102  if (AllowArrays)
103    while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
104      FT = AT->getElementType();
105
106  const RecordType *RT = FT->getAs<RecordType>();
107  if (!RT)
108    return false;
109
110  // C++ record fields are never empty, at least in the Itanium ABI.
111  //
112  // FIXME: We should use a predicate for whether this behavior is true in the
113  // current ABI.
114  if (isa<CXXRecordDecl>(RT->getDecl()))
115    return false;
116
117  return isEmptyRecord(Context, FT, AllowArrays);
118}
119
120/// isEmptyRecord - Return true iff a structure contains only empty
121/// fields. Note that a structure with a flexible array member is not
122/// considered empty.
123static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
124  const RecordType *RT = T->getAs<RecordType>();
125  if (!RT)
126    return 0;
127  const RecordDecl *RD = RT->getDecl();
128  if (RD->hasFlexibleArrayMember())
129    return false;
130
131  // If this is a C++ record, check the bases first.
132  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
133    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
134           e = CXXRD->bases_end(); i != e; ++i)
135      if (!isEmptyRecord(Context, i->getType(), true))
136        return false;
137
138  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
139         i != e; ++i)
140    if (!isEmptyField(Context, *i, AllowArrays))
141      return false;
142  return true;
143}
144
145/// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
146/// a non-trivial destructor or a non-trivial copy constructor.
147static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
148  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
149  if (!RD)
150    return false;
151
152  return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
153}
154
155/// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
156/// a record type with either a non-trivial destructor or a non-trivial copy
157/// constructor.
158static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
159  const RecordType *RT = T->getAs<RecordType>();
160  if (!RT)
161    return false;
162
163  return hasNonTrivialDestructorOrCopyConstructor(RT);
164}
165
166/// isSingleElementStruct - Determine if a structure is a "single
167/// element struct", i.e. it has exactly one non-empty field or
168/// exactly one field which is itself a single element
169/// struct. Structures with flexible array members are never
170/// considered single element structs.
171///
172/// \return The field declaration for the single non-empty field, if
173/// it exists.
174static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
175  const RecordType *RT = T->getAsStructureType();
176  if (!RT)
177    return 0;
178
179  const RecordDecl *RD = RT->getDecl();
180  if (RD->hasFlexibleArrayMember())
181    return 0;
182
183  const Type *Found = 0;
184
185  // If this is a C++ record, check the bases first.
186  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
187    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
188           e = CXXRD->bases_end(); i != e; ++i) {
189      // Ignore empty records.
190      if (isEmptyRecord(Context, i->getType(), true))
191        continue;
192
193      // If we already found an element then this isn't a single-element struct.
194      if (Found)
195        return 0;
196
197      // If this is non-empty and not a single element struct, the composite
198      // cannot be a single element struct.
199      Found = isSingleElementStruct(i->getType(), Context);
200      if (!Found)
201        return 0;
202    }
203  }
204
205  // Check for single element.
206  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
207         i != e; ++i) {
208    const FieldDecl *FD = *i;
209    QualType FT = FD->getType();
210
211    // Ignore empty fields.
212    if (isEmptyField(Context, FD, true))
213      continue;
214
215    // If we already found an element then this isn't a single-element
216    // struct.
217    if (Found)
218      return 0;
219
220    // Treat single element arrays as the element.
221    while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
222      if (AT->getSize().getZExtValue() != 1)
223        break;
224      FT = AT->getElementType();
225    }
226
227    if (!isAggregateTypeForABI(FT)) {
228      Found = FT.getTypePtr();
229    } else {
230      Found = isSingleElementStruct(FT, Context);
231      if (!Found)
232        return 0;
233    }
234  }
235
236  return Found;
237}
238
239static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
240  if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
241      !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
242      !Ty->isBlockPointerType())
243    return false;
244
245  uint64_t Size = Context.getTypeSize(Ty);
246  return Size == 32 || Size == 64;
247}
248
249/// canExpandIndirectArgument - Test whether an argument type which is to be
250/// passed indirectly (on the stack) would have the equivalent layout if it was
251/// expanded into separate arguments. If so, we prefer to do the latter to avoid
252/// inhibiting optimizations.
253///
254// FIXME: This predicate is missing many cases, currently it just follows
255// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
256// should probably make this smarter, or better yet make the LLVM backend
257// capable of handling it.
258static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
259  // We can only expand structure types.
260  const RecordType *RT = Ty->getAs<RecordType>();
261  if (!RT)
262    return false;
263
264  // We can only expand (C) structures.
265  //
266  // FIXME: This needs to be generalized to handle classes as well.
267  const RecordDecl *RD = RT->getDecl();
268  if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
269    return false;
270
271  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
272         i != e; ++i) {
273    const FieldDecl *FD = *i;
274
275    if (!is32Or64BitBasicType(FD->getType(), Context))
276      return false;
277
278    // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
279    // how to expand them yet, and the predicate for telling if a bitfield still
280    // counts as "basic" is more complicated than what we were doing previously.
281    if (FD->isBitField())
282      return false;
283  }
284
285  return true;
286}
287
288namespace {
289/// DefaultABIInfo - The default implementation for ABI specific
290/// details. This implementation provides information which results in
291/// self-consistent and sensible LLVM IR generation, but does not
292/// conform to any particular ABI.
293class DefaultABIInfo : public ABIInfo {
294public:
295  DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
296
297  ABIArgInfo classifyReturnType(QualType RetTy) const;
298  ABIArgInfo classifyArgumentType(QualType RetTy) const;
299
300  virtual void computeInfo(CGFunctionInfo &FI) const {
301    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
302    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
303         it != ie; ++it)
304      it->info = classifyArgumentType(it->type);
305  }
306
307  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
308                                 CodeGenFunction &CGF) const;
309};
310
311class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
312public:
313  DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
314    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
315};
316
317llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
318                                       CodeGenFunction &CGF) const {
319  return 0;
320}
321
322ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
323  if (isAggregateTypeForABI(Ty))
324    return ABIArgInfo::getIndirect(0);
325
326  // Treat an enum type as its underlying type.
327  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
328    Ty = EnumTy->getDecl()->getIntegerType();
329
330  return (Ty->isPromotableIntegerType() ?
331          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
332}
333
334ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
335  if (RetTy->isVoidType())
336    return ABIArgInfo::getIgnore();
337
338  if (isAggregateTypeForABI(RetTy))
339    return ABIArgInfo::getIndirect(0);
340
341  // Treat an enum type as its underlying type.
342  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
343    RetTy = EnumTy->getDecl()->getIntegerType();
344
345  return (RetTy->isPromotableIntegerType() ?
346          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
347}
348
349/// UseX86_MMXType - Return true if this is an MMX type that should use the special
350/// x86_mmx type.
351bool UseX86_MMXType(const llvm::Type *IRType) {
352  // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the
353  // special x86_mmx type.
354  return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
355    cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
356    IRType->getScalarSizeInBits() != 64;
357}
358
359static const llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
360                                                llvm::StringRef Constraint,
361                                                const llvm::Type* Ty) {
362  if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy())
363    return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
364  return Ty;
365}
366
367//===----------------------------------------------------------------------===//
368// X86-32 ABI Implementation
369//===----------------------------------------------------------------------===//
370
371/// X86_32ABIInfo - The X86-32 ABI information.
372class X86_32ABIInfo : public ABIInfo {
373  static const unsigned MinABIStackAlignInBytes = 4;
374
375  bool IsDarwinVectorABI;
376  bool IsSmallStructInRegABI;
377
378  static bool isRegisterSize(unsigned Size) {
379    return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
380  }
381
382  static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
383
384  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
385  /// such that the argument will be passed in memory.
386  ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const;
387
388  /// \brief Return the alignment to use for the given type on the stack.
389  unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
390
391public:
392
393  ABIArgInfo classifyReturnType(QualType RetTy) const;
394  ABIArgInfo classifyArgumentType(QualType RetTy) const;
395
396  virtual void computeInfo(CGFunctionInfo &FI) const {
397    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
398    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
399         it != ie; ++it)
400      it->info = classifyArgumentType(it->type);
401  }
402
403  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
404                                 CodeGenFunction &CGF) const;
405
406  X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p)
407    : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p) {}
408};
409
410class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
411public:
412  X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p)
413    :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p)) {}
414
415  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
416                           CodeGen::CodeGenModule &CGM) const;
417
418  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
419    // Darwin uses different dwarf register numbers for EH.
420    if (CGM.isTargetDarwin()) return 5;
421
422    return 4;
423  }
424
425  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
426                               llvm::Value *Address) const;
427
428  const llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
429                                        llvm::StringRef Constraint,
430                                        const llvm::Type* Ty) const {
431    return X86AdjustInlineAsmType(CGF, Constraint, Ty);
432  }
433
434};
435
436}
437
438/// shouldReturnTypeInRegister - Determine if the given type should be
439/// passed in a register (for the Darwin ABI).
440bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
441                                               ASTContext &Context) {
442  uint64_t Size = Context.getTypeSize(Ty);
443
444  // Type must be register sized.
445  if (!isRegisterSize(Size))
446    return false;
447
448  if (Ty->isVectorType()) {
449    // 64- and 128- bit vectors inside structures are not returned in
450    // registers.
451    if (Size == 64 || Size == 128)
452      return false;
453
454    return true;
455  }
456
457  // If this is a builtin, pointer, enum, complex type, member pointer, or
458  // member function pointer it is ok.
459  if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
460      Ty->isAnyComplexType() || Ty->isEnumeralType() ||
461      Ty->isBlockPointerType() || Ty->isMemberPointerType())
462    return true;
463
464  // Arrays are treated like records.
465  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
466    return shouldReturnTypeInRegister(AT->getElementType(), Context);
467
468  // Otherwise, it must be a record type.
469  const RecordType *RT = Ty->getAs<RecordType>();
470  if (!RT) return false;
471
472  // FIXME: Traverse bases here too.
473
474  // Structure types are passed in register if all fields would be
475  // passed in a register.
476  for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
477         e = RT->getDecl()->field_end(); i != e; ++i) {
478    const FieldDecl *FD = *i;
479
480    // Empty fields are ignored.
481    if (isEmptyField(Context, FD, true))
482      continue;
483
484    // Check fields recursively.
485    if (!shouldReturnTypeInRegister(FD->getType(), Context))
486      return false;
487  }
488
489  return true;
490}
491
492ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy) const {
493  if (RetTy->isVoidType())
494    return ABIArgInfo::getIgnore();
495
496  if (const VectorType *VT = RetTy->getAs<VectorType>()) {
497    // On Darwin, some vectors are returned in registers.
498    if (IsDarwinVectorABI) {
499      uint64_t Size = getContext().getTypeSize(RetTy);
500
501      // 128-bit vectors are a special case; they are returned in
502      // registers and we need to make sure to pick a type the LLVM
503      // backend will like.
504      if (Size == 128)
505        return ABIArgInfo::getDirect(llvm::VectorType::get(
506                  llvm::Type::getInt64Ty(getVMContext()), 2));
507
508      // Always return in register if it fits in a general purpose
509      // register, or if it is 64 bits and has a single element.
510      if ((Size == 8 || Size == 16 || Size == 32) ||
511          (Size == 64 && VT->getNumElements() == 1))
512        return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
513                                                            Size));
514
515      return ABIArgInfo::getIndirect(0);
516    }
517
518    return ABIArgInfo::getDirect();
519  }
520
521  if (isAggregateTypeForABI(RetTy)) {
522    if (const RecordType *RT = RetTy->getAs<RecordType>()) {
523      // Structures with either a non-trivial destructor or a non-trivial
524      // copy constructor are always indirect.
525      if (hasNonTrivialDestructorOrCopyConstructor(RT))
526        return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
527
528      // Structures with flexible arrays are always indirect.
529      if (RT->getDecl()->hasFlexibleArrayMember())
530        return ABIArgInfo::getIndirect(0);
531    }
532
533    // If specified, structs and unions are always indirect.
534    if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
535      return ABIArgInfo::getIndirect(0);
536
537    // Classify "single element" structs as their element type.
538    if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) {
539      if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
540        if (BT->isIntegerType()) {
541          // We need to use the size of the structure, padding
542          // bit-fields can adjust that to be larger than the single
543          // element type.
544          uint64_t Size = getContext().getTypeSize(RetTy);
545          return ABIArgInfo::getDirect(
546            llvm::IntegerType::get(getVMContext(), (unsigned)Size));
547        }
548
549        if (BT->getKind() == BuiltinType::Float) {
550          assert(getContext().getTypeSize(RetTy) ==
551                 getContext().getTypeSize(SeltTy) &&
552                 "Unexpect single element structure size!");
553          return ABIArgInfo::getDirect(llvm::Type::getFloatTy(getVMContext()));
554        }
555
556        if (BT->getKind() == BuiltinType::Double) {
557          assert(getContext().getTypeSize(RetTy) ==
558                 getContext().getTypeSize(SeltTy) &&
559                 "Unexpect single element structure size!");
560          return ABIArgInfo::getDirect(llvm::Type::getDoubleTy(getVMContext()));
561        }
562      } else if (SeltTy->isPointerType()) {
563        // FIXME: It would be really nice if this could come out as the proper
564        // pointer type.
565        const llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(getVMContext());
566        return ABIArgInfo::getDirect(PtrTy);
567      } else if (SeltTy->isVectorType()) {
568        // 64- and 128-bit vectors are never returned in a
569        // register when inside a structure.
570        uint64_t Size = getContext().getTypeSize(RetTy);
571        if (Size == 64 || Size == 128)
572          return ABIArgInfo::getIndirect(0);
573
574        return classifyReturnType(QualType(SeltTy, 0));
575      }
576    }
577
578    // Small structures which are register sized are generally returned
579    // in a register.
580    if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext())) {
581      uint64_t Size = getContext().getTypeSize(RetTy);
582      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
583    }
584
585    return ABIArgInfo::getIndirect(0);
586  }
587
588  // Treat an enum type as its underlying type.
589  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
590    RetTy = EnumTy->getDecl()->getIntegerType();
591
592  return (RetTy->isPromotableIntegerType() ?
593          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
594}
595
596static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
597  const RecordType *RT = Ty->getAs<RecordType>();
598  if (!RT)
599    return 0;
600  const RecordDecl *RD = RT->getDecl();
601
602  // If this is a C++ record, check the bases first.
603  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
604    for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
605           e = CXXRD->bases_end(); i != e; ++i)
606      if (!isRecordWithSSEVectorType(Context, i->getType()))
607        return false;
608
609  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
610       i != e; ++i) {
611    QualType FT = i->getType();
612
613    if (FT->getAs<VectorType>() && Context.getTypeSize(Ty) == 128)
614      return true;
615
616    if (isRecordWithSSEVectorType(Context, FT))
617      return true;
618  }
619
620  return false;
621}
622
623unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
624                                                 unsigned Align) const {
625  // Otherwise, if the alignment is less than or equal to the minimum ABI
626  // alignment, just use the default; the backend will handle this.
627  if (Align <= MinABIStackAlignInBytes)
628    return 0; // Use default alignment.
629
630  // On non-Darwin, the stack type alignment is always 4.
631  if (!IsDarwinVectorABI) {
632    // Set explicit alignment, since we may need to realign the top.
633    return MinABIStackAlignInBytes;
634  }
635
636  // Otherwise, if the type contains an SSE vector type, the alignment is 16.
637  if (isRecordWithSSEVectorType(getContext(), Ty))
638    return 16;
639
640  return MinABIStackAlignInBytes;
641}
642
643ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const {
644  if (!ByVal)
645    return ABIArgInfo::getIndirect(0, false);
646
647  // Compute the byval alignment.
648  unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
649  unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
650  if (StackAlign == 0)
651    return ABIArgInfo::getIndirect(4);
652
653  // If the stack alignment is less than the type alignment, realign the
654  // argument.
655  if (StackAlign < TypeAlign)
656    return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
657                                   /*Realign=*/true);
658
659  return ABIArgInfo::getIndirect(StackAlign);
660}
661
662ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const {
663  // FIXME: Set alignment on indirect arguments.
664  if (isAggregateTypeForABI(Ty)) {
665    // Structures with flexible arrays are always indirect.
666    if (const RecordType *RT = Ty->getAs<RecordType>()) {
667      // Structures with either a non-trivial destructor or a non-trivial
668      // copy constructor are always indirect.
669      if (hasNonTrivialDestructorOrCopyConstructor(RT))
670        return getIndirectResult(Ty, /*ByVal=*/false);
671
672      if (RT->getDecl()->hasFlexibleArrayMember())
673        return getIndirectResult(Ty);
674    }
675
676    // Ignore empty structs.
677    if (Ty->isStructureType() && getContext().getTypeSize(Ty) == 0)
678      return ABIArgInfo::getIgnore();
679
680    // Expand small (<= 128-bit) record types when we know that the stack layout
681    // of those arguments will match the struct. This is important because the
682    // LLVM backend isn't smart enough to remove byval, which inhibits many
683    // optimizations.
684    if (getContext().getTypeSize(Ty) <= 4*32 &&
685        canExpandIndirectArgument(Ty, getContext()))
686      return ABIArgInfo::getExpand();
687
688    return getIndirectResult(Ty);
689  }
690
691  if (const VectorType *VT = Ty->getAs<VectorType>()) {
692    // On Darwin, some vectors are passed in memory, we handle this by passing
693    // it as an i8/i16/i32/i64.
694    if (IsDarwinVectorABI) {
695      uint64_t Size = getContext().getTypeSize(Ty);
696      if ((Size == 8 || Size == 16 || Size == 32) ||
697          (Size == 64 && VT->getNumElements() == 1))
698        return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
699                                                            Size));
700    }
701
702    const llvm::Type *IRType = CGT.ConvertTypeRecursive(Ty);
703    if (UseX86_MMXType(IRType)) {
704      ABIArgInfo AAI = ABIArgInfo::getDirect(IRType);
705      AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext()));
706      return AAI;
707    }
708
709    return ABIArgInfo::getDirect();
710  }
711
712
713  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
714    Ty = EnumTy->getDecl()->getIntegerType();
715
716  return (Ty->isPromotableIntegerType() ?
717          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
718}
719
720llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
721                                      CodeGenFunction &CGF) const {
722  const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
723  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
724
725  CGBuilderTy &Builder = CGF.Builder;
726  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
727                                                       "ap");
728  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
729  llvm::Type *PTy =
730    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
731  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
732
733  uint64_t Offset =
734    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
735  llvm::Value *NextAddr =
736    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
737                      "ap.next");
738  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
739
740  return AddrTyped;
741}
742
743void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
744                                                  llvm::GlobalValue *GV,
745                                            CodeGen::CodeGenModule &CGM) const {
746  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
747    if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
748      // Get the LLVM function.
749      llvm::Function *Fn = cast<llvm::Function>(GV);
750
751      // Now add the 'alignstack' attribute with a value of 16.
752      Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16));
753    }
754  }
755}
756
757bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
758                                               CodeGen::CodeGenFunction &CGF,
759                                               llvm::Value *Address) const {
760  CodeGen::CGBuilderTy &Builder = CGF.Builder;
761  llvm::LLVMContext &Context = CGF.getLLVMContext();
762
763  const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
764  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
765
766  // 0-7 are the eight integer registers;  the order is different
767  //   on Darwin (for EH), but the range is the same.
768  // 8 is %eip.
769  AssignToArrayRange(Builder, Address, Four8, 0, 8);
770
771  if (CGF.CGM.isTargetDarwin()) {
772    // 12-16 are st(0..4).  Not sure why we stop at 4.
773    // These have size 16, which is sizeof(long double) on
774    // platforms with 8-byte alignment for that type.
775    llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
776    AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
777
778  } else {
779    // 9 is %eflags, which doesn't get a size on Darwin for some
780    // reason.
781    Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
782
783    // 11-16 are st(0..5).  Not sure why we stop at 5.
784    // These have size 12, which is sizeof(long double) on
785    // platforms with 4-byte alignment for that type.
786    llvm::Value *Twelve8 = llvm::ConstantInt::get(i8, 12);
787    AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
788  }
789
790  return false;
791}
792
793//===----------------------------------------------------------------------===//
794// X86-64 ABI Implementation
795//===----------------------------------------------------------------------===//
796
797
798namespace {
799/// X86_64ABIInfo - The X86_64 ABI information.
800class X86_64ABIInfo : public ABIInfo {
801  enum Class {
802    Integer = 0,
803    SSE,
804    SSEUp,
805    X87,
806    X87Up,
807    ComplexX87,
808    NoClass,
809    Memory
810  };
811
812  /// merge - Implement the X86_64 ABI merging algorithm.
813  ///
814  /// Merge an accumulating classification \arg Accum with a field
815  /// classification \arg Field.
816  ///
817  /// \param Accum - The accumulating classification. This should
818  /// always be either NoClass or the result of a previous merge
819  /// call. In addition, this should never be Memory (the caller
820  /// should just return Memory for the aggregate).
821  static Class merge(Class Accum, Class Field);
822
823  /// classify - Determine the x86_64 register classes in which the
824  /// given type T should be passed.
825  ///
826  /// \param Lo - The classification for the parts of the type
827  /// residing in the low word of the containing object.
828  ///
829  /// \param Hi - The classification for the parts of the type
830  /// residing in the high word of the containing object.
831  ///
832  /// \param OffsetBase - The bit offset of this type in the
833  /// containing object.  Some parameters are classified different
834  /// depending on whether they straddle an eightbyte boundary.
835  ///
836  /// If a word is unused its result will be NoClass; if a type should
837  /// be passed in Memory then at least the classification of \arg Lo
838  /// will be Memory.
839  ///
840  /// The \arg Lo class will be NoClass iff the argument is ignored.
841  ///
842  /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
843  /// also be ComplexX87.
844  void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
845
846  const llvm::Type *Get16ByteVectorType(QualType Ty) const;
847  const llvm::Type *GetSSETypeAtOffset(const llvm::Type *IRType,
848                                       unsigned IROffset, QualType SourceTy,
849                                       unsigned SourceOffset) const;
850  const llvm::Type *GetINTEGERTypeAtOffset(const llvm::Type *IRType,
851                                           unsigned IROffset, QualType SourceTy,
852                                           unsigned SourceOffset) const;
853
854  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
855  /// such that the argument will be returned in memory.
856  ABIArgInfo getIndirectReturnResult(QualType Ty) const;
857
858  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
859  /// such that the argument will be passed in memory.
860  ABIArgInfo getIndirectResult(QualType Ty) const;
861
862  ABIArgInfo classifyReturnType(QualType RetTy) const;
863
864  ABIArgInfo classifyArgumentType(QualType Ty,
865                                  unsigned &neededInt,
866                                  unsigned &neededSSE) const;
867
868  /// The 0.98 ABI revision clarified a lot of ambiguities,
869  /// unfortunately in ways that were not always consistent with
870  /// certain previous compilers.  In particular, platforms which
871  /// required strict binary compatibility with older versions of GCC
872  /// may need to exempt themselves.
873  bool honorsRevision0_98() const {
874    return !getContext().Target.getTriple().isOSDarwin();
875  }
876
877public:
878  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
879
880  virtual void computeInfo(CGFunctionInfo &FI) const;
881
882  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
883                                 CodeGenFunction &CGF) const;
884};
885
886/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
887class WinX86_64ABIInfo : public ABIInfo {
888
889  ABIArgInfo classify(QualType Ty) const;
890
891public:
892  WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
893
894  virtual void computeInfo(CGFunctionInfo &FI) const;
895
896  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
897                                 CodeGenFunction &CGF) const;
898};
899
900class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
901public:
902  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
903    : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
904
905  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
906    return 7;
907  }
908
909  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
910                               llvm::Value *Address) const {
911    CodeGen::CGBuilderTy &Builder = CGF.Builder;
912    llvm::LLVMContext &Context = CGF.getLLVMContext();
913
914    const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
915    llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
916
917    // 0-15 are the 16 integer registers.
918    // 16 is %rip.
919    AssignToArrayRange(Builder, Address, Eight8, 0, 16);
920
921    return false;
922  }
923
924  const llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
925                                        llvm::StringRef Constraint,
926                                        const llvm::Type* Ty) const {
927    return X86AdjustInlineAsmType(CGF, Constraint, Ty);
928  }
929
930};
931
932class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
933public:
934  WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
935    : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
936
937  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
938    return 7;
939  }
940
941  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
942                               llvm::Value *Address) const {
943    CodeGen::CGBuilderTy &Builder = CGF.Builder;
944    llvm::LLVMContext &Context = CGF.getLLVMContext();
945
946    const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
947    llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
948
949    // 0-15 are the 16 integer registers.
950    // 16 is %rip.
951    AssignToArrayRange(Builder, Address, Eight8, 0, 16);
952
953    return false;
954  }
955};
956
957}
958
959X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
960  // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
961  // classified recursively so that always two fields are
962  // considered. The resulting class is calculated according to
963  // the classes of the fields in the eightbyte:
964  //
965  // (a) If both classes are equal, this is the resulting class.
966  //
967  // (b) If one of the classes is NO_CLASS, the resulting class is
968  // the other class.
969  //
970  // (c) If one of the classes is MEMORY, the result is the MEMORY
971  // class.
972  //
973  // (d) If one of the classes is INTEGER, the result is the
974  // INTEGER.
975  //
976  // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
977  // MEMORY is used as class.
978  //
979  // (f) Otherwise class SSE is used.
980
981  // Accum should never be memory (we should have returned) or
982  // ComplexX87 (because this cannot be passed in a structure).
983  assert((Accum != Memory && Accum != ComplexX87) &&
984         "Invalid accumulated classification during merge.");
985  if (Accum == Field || Field == NoClass)
986    return Accum;
987  if (Field == Memory)
988    return Memory;
989  if (Accum == NoClass)
990    return Field;
991  if (Accum == Integer || Field == Integer)
992    return Integer;
993  if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
994      Accum == X87 || Accum == X87Up)
995    return Memory;
996  return SSE;
997}
998
999void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1000                             Class &Lo, Class &Hi) const {
1001  // FIXME: This code can be simplified by introducing a simple value class for
1002  // Class pairs with appropriate constructor methods for the various
1003  // situations.
1004
1005  // FIXME: Some of the split computations are wrong; unaligned vectors
1006  // shouldn't be passed in registers for example, so there is no chance they
1007  // can straddle an eightbyte. Verify & simplify.
1008
1009  Lo = Hi = NoClass;
1010
1011  Class &Current = OffsetBase < 64 ? Lo : Hi;
1012  Current = Memory;
1013
1014  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1015    BuiltinType::Kind k = BT->getKind();
1016
1017    if (k == BuiltinType::Void) {
1018      Current = NoClass;
1019    } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1020      Lo = Integer;
1021      Hi = Integer;
1022    } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1023      Current = Integer;
1024    } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
1025      Current = SSE;
1026    } else if (k == BuiltinType::LongDouble) {
1027      Lo = X87;
1028      Hi = X87Up;
1029    }
1030    // FIXME: _Decimal32 and _Decimal64 are SSE.
1031    // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1032    return;
1033  }
1034
1035  if (const EnumType *ET = Ty->getAs<EnumType>()) {
1036    // Classify the underlying integer type.
1037    classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
1038    return;
1039  }
1040
1041  if (Ty->hasPointerRepresentation()) {
1042    Current = Integer;
1043    return;
1044  }
1045
1046  if (Ty->isMemberPointerType()) {
1047    if (Ty->isMemberFunctionPointerType())
1048      Lo = Hi = Integer;
1049    else
1050      Current = Integer;
1051    return;
1052  }
1053
1054  if (const VectorType *VT = Ty->getAs<VectorType>()) {
1055    uint64_t Size = getContext().getTypeSize(VT);
1056    if (Size == 32) {
1057      // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1058      // float> as integer.
1059      Current = Integer;
1060
1061      // If this type crosses an eightbyte boundary, it should be
1062      // split.
1063      uint64_t EB_Real = (OffsetBase) / 64;
1064      uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1065      if (EB_Real != EB_Imag)
1066        Hi = Lo;
1067    } else if (Size == 64) {
1068      // gcc passes <1 x double> in memory. :(
1069      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1070        return;
1071
1072      // gcc passes <1 x long long> as INTEGER.
1073      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1074          VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1075          VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1076          VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1077        Current = Integer;
1078      else
1079        Current = SSE;
1080
1081      // If this type crosses an eightbyte boundary, it should be
1082      // split.
1083      if (OffsetBase && OffsetBase != 64)
1084        Hi = Lo;
1085    } else if (Size == 128) {
1086      Lo = SSE;
1087      Hi = SSEUp;
1088    }
1089    return;
1090  }
1091
1092  if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1093    QualType ET = getContext().getCanonicalType(CT->getElementType());
1094
1095    uint64_t Size = getContext().getTypeSize(Ty);
1096    if (ET->isIntegralOrEnumerationType()) {
1097      if (Size <= 64)
1098        Current = Integer;
1099      else if (Size <= 128)
1100        Lo = Hi = Integer;
1101    } else if (ET == getContext().FloatTy)
1102      Current = SSE;
1103    else if (ET == getContext().DoubleTy)
1104      Lo = Hi = SSE;
1105    else if (ET == getContext().LongDoubleTy)
1106      Current = ComplexX87;
1107
1108    // If this complex type crosses an eightbyte boundary then it
1109    // should be split.
1110    uint64_t EB_Real = (OffsetBase) / 64;
1111    uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1112    if (Hi == NoClass && EB_Real != EB_Imag)
1113      Hi = Lo;
1114
1115    return;
1116  }
1117
1118  if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1119    // Arrays are treated like structures.
1120
1121    uint64_t Size = getContext().getTypeSize(Ty);
1122
1123    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1124    // than two eightbytes, ..., it has class MEMORY.
1125    if (Size > 128)
1126      return;
1127
1128    // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1129    // fields, it has class MEMORY.
1130    //
1131    // Only need to check alignment of array base.
1132    if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1133      return;
1134
1135    // Otherwise implement simplified merge. We could be smarter about
1136    // this, but it isn't worth it and would be harder to verify.
1137    Current = NoClass;
1138    uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1139    uint64_t ArraySize = AT->getSize().getZExtValue();
1140    for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1141      Class FieldLo, FieldHi;
1142      classify(AT->getElementType(), Offset, FieldLo, FieldHi);
1143      Lo = merge(Lo, FieldLo);
1144      Hi = merge(Hi, FieldHi);
1145      if (Lo == Memory || Hi == Memory)
1146        break;
1147    }
1148
1149    // Do post merger cleanup (see below). Only case we worry about is Memory.
1150    if (Hi == Memory)
1151      Lo = Memory;
1152    assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1153    return;
1154  }
1155
1156  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1157    uint64_t Size = getContext().getTypeSize(Ty);
1158
1159    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1160    // than two eightbytes, ..., it has class MEMORY.
1161    if (Size > 128)
1162      return;
1163
1164    // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1165    // copy constructor or a non-trivial destructor, it is passed by invisible
1166    // reference.
1167    if (hasNonTrivialDestructorOrCopyConstructor(RT))
1168      return;
1169
1170    const RecordDecl *RD = RT->getDecl();
1171
1172    // Assume variable sized types are passed in memory.
1173    if (RD->hasFlexibleArrayMember())
1174      return;
1175
1176    const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1177
1178    // Reset Lo class, this will be recomputed.
1179    Current = NoClass;
1180
1181    // If this is a C++ record, classify the bases first.
1182    if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1183      for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1184             e = CXXRD->bases_end(); i != e; ++i) {
1185        assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1186               "Unexpected base class!");
1187        const CXXRecordDecl *Base =
1188          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1189
1190        // Classify this field.
1191        //
1192        // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1193        // single eightbyte, each is classified separately. Each eightbyte gets
1194        // initialized to class NO_CLASS.
1195        Class FieldLo, FieldHi;
1196        uint64_t Offset = OffsetBase + Layout.getBaseClassOffsetInBits(Base);
1197        classify(i->getType(), Offset, FieldLo, FieldHi);
1198        Lo = merge(Lo, FieldLo);
1199        Hi = merge(Hi, FieldHi);
1200        if (Lo == Memory || Hi == Memory)
1201          break;
1202      }
1203    }
1204
1205    // Classify the fields one at a time, merging the results.
1206    unsigned idx = 0;
1207    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1208           i != e; ++i, ++idx) {
1209      uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1210      bool BitField = i->isBitField();
1211
1212      // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1213      // fields, it has class MEMORY.
1214      //
1215      // Note, skip this test for bit-fields, see below.
1216      if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1217        Lo = Memory;
1218        return;
1219      }
1220
1221      // Classify this field.
1222      //
1223      // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1224      // exceeds a single eightbyte, each is classified
1225      // separately. Each eightbyte gets initialized to class
1226      // NO_CLASS.
1227      Class FieldLo, FieldHi;
1228
1229      // Bit-fields require special handling, they do not force the
1230      // structure to be passed in memory even if unaligned, and
1231      // therefore they can straddle an eightbyte.
1232      if (BitField) {
1233        // Ignore padding bit-fields.
1234        if (i->isUnnamedBitfield())
1235          continue;
1236
1237        uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1238        uint64_t Size =
1239          i->getBitWidth()->EvaluateAsInt(getContext()).getZExtValue();
1240
1241        uint64_t EB_Lo = Offset / 64;
1242        uint64_t EB_Hi = (Offset + Size - 1) / 64;
1243        FieldLo = FieldHi = NoClass;
1244        if (EB_Lo) {
1245          assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1246          FieldLo = NoClass;
1247          FieldHi = Integer;
1248        } else {
1249          FieldLo = Integer;
1250          FieldHi = EB_Hi ? Integer : NoClass;
1251        }
1252      } else
1253        classify(i->getType(), Offset, FieldLo, FieldHi);
1254      Lo = merge(Lo, FieldLo);
1255      Hi = merge(Hi, FieldHi);
1256      if (Lo == Memory || Hi == Memory)
1257        break;
1258    }
1259
1260    // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1261    //
1262    // (a) If one of the classes is MEMORY, the whole argument is
1263    // passed in memory.
1264    //
1265    // (b) If X87UP is not preceded by X87, the whole argument is
1266    // passed in memory.
1267    //
1268    // (c) If the size of the aggregate exceeds two eightbytes and the first
1269    // eight-byte isn't SSE or any other eightbyte isn't SSEUP, the whole
1270    // argument is passed in memory.
1271    //
1272    // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1273    //
1274    // Some of these are enforced by the merging logic.  Others can arise
1275    // only with unions; for example:
1276    //   union { _Complex double; unsigned; }
1277    //
1278    // Note that clauses (b) and (c) were added in 0.98.
1279    if (Hi == Memory)
1280      Lo = Memory;
1281    if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1282      Lo = Memory;
1283    if (Hi == SSEUp && Lo != SSE)
1284      Hi = SSE;
1285  }
1286}
1287
1288ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1289  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1290  // place naturally.
1291  if (!isAggregateTypeForABI(Ty)) {
1292    // Treat an enum type as its underlying type.
1293    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1294      Ty = EnumTy->getDecl()->getIntegerType();
1295
1296    return (Ty->isPromotableIntegerType() ?
1297            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1298  }
1299
1300  return ABIArgInfo::getIndirect(0);
1301}
1302
1303ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const {
1304  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1305  // place naturally.
1306  if (!isAggregateTypeForABI(Ty)) {
1307    // Treat an enum type as its underlying type.
1308    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1309      Ty = EnumTy->getDecl()->getIntegerType();
1310
1311    return (Ty->isPromotableIntegerType() ?
1312            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1313  }
1314
1315  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1316    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1317
1318  // Compute the byval alignment. We specify the alignment of the byval in all
1319  // cases so that the mid-level optimizer knows the alignment of the byval.
1320  unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1321  return ABIArgInfo::getIndirect(Align);
1322}
1323
1324/// Get16ByteVectorType - The ABI specifies that a value should be passed in an
1325/// full vector XMM register.  Pick an LLVM IR type that will be passed as a
1326/// vector register.
1327const llvm::Type *X86_64ABIInfo::Get16ByteVectorType(QualType Ty) const {
1328  const llvm::Type *IRType = CGT.ConvertTypeRecursive(Ty);
1329
1330  // Wrapper structs that just contain vectors are passed just like vectors,
1331  // strip them off if present.
1332  const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1333  while (STy && STy->getNumElements() == 1) {
1334    IRType = STy->getElementType(0);
1335    STy = dyn_cast<llvm::StructType>(IRType);
1336  }
1337
1338  // If the preferred type is a 16-byte vector, prefer to pass it.
1339  if (const llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1340    const llvm::Type *EltTy = VT->getElementType();
1341    if (VT->getBitWidth() == 128 &&
1342        (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1343         EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1344         EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1345         EltTy->isIntegerTy(128)))
1346      return VT;
1347  }
1348
1349  return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1350}
1351
1352/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1353/// is known to either be off the end of the specified type or being in
1354/// alignment padding.  The user type specified is known to be at most 128 bits
1355/// in size, and have passed through X86_64ABIInfo::classify with a successful
1356/// classification that put one of the two halves in the INTEGER class.
1357///
1358/// It is conservatively correct to return false.
1359static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1360                                  unsigned EndBit, ASTContext &Context) {
1361  // If the bytes being queried are off the end of the type, there is no user
1362  // data hiding here.  This handles analysis of builtins, vectors and other
1363  // types that don't contain interesting padding.
1364  unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1365  if (TySize <= StartBit)
1366    return true;
1367
1368  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1369    unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1370    unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1371
1372    // Check each element to see if the element overlaps with the queried range.
1373    for (unsigned i = 0; i != NumElts; ++i) {
1374      // If the element is after the span we care about, then we're done..
1375      unsigned EltOffset = i*EltSize;
1376      if (EltOffset >= EndBit) break;
1377
1378      unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1379      if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1380                                 EndBit-EltOffset, Context))
1381        return false;
1382    }
1383    // If it overlaps no elements, then it is safe to process as padding.
1384    return true;
1385  }
1386
1387  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1388    const RecordDecl *RD = RT->getDecl();
1389    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1390
1391    // If this is a C++ record, check the bases first.
1392    if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1393      for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1394           e = CXXRD->bases_end(); i != e; ++i) {
1395        assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1396               "Unexpected base class!");
1397        const CXXRecordDecl *Base =
1398          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1399
1400        // If the base is after the span we care about, ignore it.
1401        unsigned BaseOffset = (unsigned)Layout.getBaseClassOffsetInBits(Base);
1402        if (BaseOffset >= EndBit) continue;
1403
1404        unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1405        if (!BitsContainNoUserData(i->getType(), BaseStart,
1406                                   EndBit-BaseOffset, Context))
1407          return false;
1408      }
1409    }
1410
1411    // Verify that no field has data that overlaps the region of interest.  Yes
1412    // this could be sped up a lot by being smarter about queried fields,
1413    // however we're only looking at structs up to 16 bytes, so we don't care
1414    // much.
1415    unsigned idx = 0;
1416    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1417         i != e; ++i, ++idx) {
1418      unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1419
1420      // If we found a field after the region we care about, then we're done.
1421      if (FieldOffset >= EndBit) break;
1422
1423      unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1424      if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1425                                 Context))
1426        return false;
1427    }
1428
1429    // If nothing in this record overlapped the area of interest, then we're
1430    // clean.
1431    return true;
1432  }
1433
1434  return false;
1435}
1436
1437/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1438/// float member at the specified offset.  For example, {int,{float}} has a
1439/// float at offset 4.  It is conservatively correct for this routine to return
1440/// false.
1441static bool ContainsFloatAtOffset(const llvm::Type *IRType, unsigned IROffset,
1442                                  const llvm::TargetData &TD) {
1443  // Base case if we find a float.
1444  if (IROffset == 0 && IRType->isFloatTy())
1445    return true;
1446
1447  // If this is a struct, recurse into the field at the specified offset.
1448  if (const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1449    const llvm::StructLayout *SL = TD.getStructLayout(STy);
1450    unsigned Elt = SL->getElementContainingOffset(IROffset);
1451    IROffset -= SL->getElementOffset(Elt);
1452    return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1453  }
1454
1455  // If this is an array, recurse into the field at the specified offset.
1456  if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1457    const llvm::Type *EltTy = ATy->getElementType();
1458    unsigned EltSize = TD.getTypeAllocSize(EltTy);
1459    IROffset -= IROffset/EltSize*EltSize;
1460    return ContainsFloatAtOffset(EltTy, IROffset, TD);
1461  }
1462
1463  return false;
1464}
1465
1466
1467/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1468/// low 8 bytes of an XMM register, corresponding to the SSE class.
1469const llvm::Type *X86_64ABIInfo::
1470GetSSETypeAtOffset(const llvm::Type *IRType, unsigned IROffset,
1471                   QualType SourceTy, unsigned SourceOffset) const {
1472  // The only three choices we have are either double, <2 x float>, or float. We
1473  // pass as float if the last 4 bytes is just padding.  This happens for
1474  // structs that contain 3 floats.
1475  if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1476                            SourceOffset*8+64, getContext()))
1477    return llvm::Type::getFloatTy(getVMContext());
1478
1479  // We want to pass as <2 x float> if the LLVM IR type contains a float at
1480  // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
1481  // case.
1482  if (ContainsFloatAtOffset(IRType, IROffset, getTargetData()) &&
1483      ContainsFloatAtOffset(IRType, IROffset+4, getTargetData()))
1484    return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1485
1486  return llvm::Type::getDoubleTy(getVMContext());
1487}
1488
1489
1490/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1491/// an 8-byte GPR.  This means that we either have a scalar or we are talking
1492/// about the high or low part of an up-to-16-byte struct.  This routine picks
1493/// the best LLVM IR type to represent this, which may be i64 or may be anything
1494/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1495/// etc).
1496///
1497/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1498/// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1499/// the 8-byte value references.  PrefType may be null.
1500///
1501/// SourceTy is the source level type for the entire argument.  SourceOffset is
1502/// an offset into this that we're processing (which is always either 0 or 8).
1503///
1504const llvm::Type *X86_64ABIInfo::
1505GetINTEGERTypeAtOffset(const llvm::Type *IRType, unsigned IROffset,
1506                       QualType SourceTy, unsigned SourceOffset) const {
1507  // If we're dealing with an un-offset LLVM IR type, then it means that we're
1508  // returning an 8-byte unit starting with it.  See if we can safely use it.
1509  if (IROffset == 0) {
1510    // Pointers and int64's always fill the 8-byte unit.
1511    if (isa<llvm::PointerType>(IRType) || IRType->isIntegerTy(64))
1512      return IRType;
1513
1514    // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1515    // goodness in the source type is just tail padding.  This is allowed to
1516    // kick in for struct {double,int} on the int, but not on
1517    // struct{double,int,int} because we wouldn't return the second int.  We
1518    // have to do this analysis on the source type because we can't depend on
1519    // unions being lowered a specific way etc.
1520    if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
1521        IRType->isIntegerTy(32)) {
1522      unsigned BitWidth = cast<llvm::IntegerType>(IRType)->getBitWidth();
1523
1524      if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1525                                SourceOffset*8+64, getContext()))
1526        return IRType;
1527    }
1528  }
1529
1530  if (const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1531    // If this is a struct, recurse into the field at the specified offset.
1532    const llvm::StructLayout *SL = getTargetData().getStructLayout(STy);
1533    if (IROffset < SL->getSizeInBytes()) {
1534      unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1535      IROffset -= SL->getElementOffset(FieldIdx);
1536
1537      return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1538                                    SourceTy, SourceOffset);
1539    }
1540  }
1541
1542  if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1543    const llvm::Type *EltTy = ATy->getElementType();
1544    unsigned EltSize = getTargetData().getTypeAllocSize(EltTy);
1545    unsigned EltOffset = IROffset/EltSize*EltSize;
1546    return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1547                                  SourceOffset);
1548  }
1549
1550  // Okay, we don't have any better idea of what to pass, so we pass this in an
1551  // integer register that isn't too big to fit the rest of the struct.
1552  unsigned TySizeInBytes =
1553    (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
1554
1555  assert(TySizeInBytes != SourceOffset && "Empty field?");
1556
1557  // It is always safe to classify this as an integer type up to i64 that
1558  // isn't larger than the structure.
1559  return llvm::IntegerType::get(getVMContext(),
1560                                std::min(TySizeInBytes-SourceOffset, 8U)*8);
1561}
1562
1563
1564/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
1565/// be used as elements of a two register pair to pass or return, return a
1566/// first class aggregate to represent them.  For example, if the low part of
1567/// a by-value argument should be passed as i32* and the high part as float,
1568/// return {i32*, float}.
1569static const llvm::Type *
1570GetX86_64ByValArgumentPair(const llvm::Type *Lo, const llvm::Type *Hi,
1571                           const llvm::TargetData &TD) {
1572  // In order to correctly satisfy the ABI, we need to the high part to start
1573  // at offset 8.  If the high and low parts we inferred are both 4-byte types
1574  // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
1575  // the second element at offset 8.  Check for this:
1576  unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
1577  unsigned HiAlign = TD.getABITypeAlignment(Hi);
1578  unsigned HiStart = llvm::TargetData::RoundUpAlignment(LoSize, HiAlign);
1579  assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
1580
1581  // To handle this, we have to increase the size of the low part so that the
1582  // second element will start at an 8 byte offset.  We can't increase the size
1583  // of the second element because it might make us access off the end of the
1584  // struct.
1585  if (HiStart != 8) {
1586    // There are only two sorts of types the ABI generation code can produce for
1587    // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
1588    // Promote these to a larger type.
1589    if (Lo->isFloatTy())
1590      Lo = llvm::Type::getDoubleTy(Lo->getContext());
1591    else {
1592      assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
1593      Lo = llvm::Type::getInt64Ty(Lo->getContext());
1594    }
1595  }
1596
1597  const llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
1598
1599
1600  // Verify that the second element is at an 8-byte offset.
1601  assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
1602         "Invalid x86-64 argument pair!");
1603  return Result;
1604}
1605
1606ABIArgInfo X86_64ABIInfo::
1607classifyReturnType(QualType RetTy) const {
1608  // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1609  // classification algorithm.
1610  X86_64ABIInfo::Class Lo, Hi;
1611  classify(RetTy, 0, Lo, Hi);
1612
1613  // Check some invariants.
1614  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1615  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1616
1617  const llvm::Type *ResType = 0;
1618  switch (Lo) {
1619  case NoClass:
1620    if (Hi == NoClass)
1621      return ABIArgInfo::getIgnore();
1622    // If the low part is just padding, it takes no register, leave ResType
1623    // null.
1624    assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1625           "Unknown missing lo part");
1626    break;
1627
1628  case SSEUp:
1629  case X87Up:
1630    assert(0 && "Invalid classification for lo word.");
1631
1632    // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1633    // hidden argument.
1634  case Memory:
1635    return getIndirectReturnResult(RetTy);
1636
1637    // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1638    // available register of the sequence %rax, %rdx is used.
1639  case Integer:
1640    ResType = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 0,
1641                                     RetTy, 0);
1642
1643    // If we have a sign or zero extended integer, make sure to return Extend
1644    // so that the parameter gets the right LLVM IR attributes.
1645    if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1646      // Treat an enum type as its underlying type.
1647      if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1648        RetTy = EnumTy->getDecl()->getIntegerType();
1649
1650      if (RetTy->isIntegralOrEnumerationType() &&
1651          RetTy->isPromotableIntegerType())
1652        return ABIArgInfo::getExtend();
1653    }
1654    break;
1655
1656    // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1657    // available SSE register of the sequence %xmm0, %xmm1 is used.
1658  case SSE:
1659    ResType = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 0, RetTy, 0);
1660    break;
1661
1662    // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1663    // returned on the X87 stack in %st0 as 80-bit x87 number.
1664  case X87:
1665    ResType = llvm::Type::getX86_FP80Ty(getVMContext());
1666    break;
1667
1668    // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1669    // part of the value is returned in %st0 and the imaginary part in
1670    // %st1.
1671  case ComplexX87:
1672    assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1673    ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
1674                                    llvm::Type::getX86_FP80Ty(getVMContext()),
1675                                    NULL);
1676    break;
1677  }
1678
1679  const llvm::Type *HighPart = 0;
1680  switch (Hi) {
1681    // Memory was handled previously and X87 should
1682    // never occur as a hi class.
1683  case Memory:
1684  case X87:
1685    assert(0 && "Invalid classification for hi word.");
1686
1687  case ComplexX87: // Previously handled.
1688  case NoClass:
1689    break;
1690
1691  case Integer:
1692    HighPart = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(RetTy),
1693                                      8, RetTy, 8);
1694    if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1695      return ABIArgInfo::getDirect(HighPart, 8);
1696    break;
1697  case SSE:
1698    HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 8, RetTy, 8);
1699    if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1700      return ABIArgInfo::getDirect(HighPart, 8);
1701    break;
1702
1703    // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1704    // is passed in the upper half of the last used SSE register.
1705    //
1706    // SSEUP should always be preceded by SSE, just widen.
1707  case SSEUp:
1708    assert(Lo == SSE && "Unexpected SSEUp classification.");
1709    ResType = Get16ByteVectorType(RetTy);
1710    break;
1711
1712    // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1713    // returned together with the previous X87 value in %st0.
1714  case X87Up:
1715    // If X87Up is preceded by X87, we don't need to do
1716    // anything. However, in some cases with unions it may not be
1717    // preceded by X87. In such situations we follow gcc and pass the
1718    // extra bits in an SSE reg.
1719    if (Lo != X87) {
1720      HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy),
1721                                    8, RetTy, 8);
1722      if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1723        return ABIArgInfo::getDirect(HighPart, 8);
1724    }
1725    break;
1726  }
1727
1728  // If a high part was specified, merge it together with the low part.  It is
1729  // known to pass in the high eightbyte of the result.  We do this by forming a
1730  // first class struct aggregate with the high and low part: {low, high}
1731  if (HighPart)
1732    ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1733
1734  return ABIArgInfo::getDirect(ResType);
1735}
1736
1737ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &neededInt,
1738                                               unsigned &neededSSE) const {
1739  X86_64ABIInfo::Class Lo, Hi;
1740  classify(Ty, 0, Lo, Hi);
1741
1742  // Check some invariants.
1743  // FIXME: Enforce these by construction.
1744  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1745  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1746
1747  neededInt = 0;
1748  neededSSE = 0;
1749  const llvm::Type *ResType = 0;
1750  switch (Lo) {
1751  case NoClass:
1752    if (Hi == NoClass)
1753      return ABIArgInfo::getIgnore();
1754    // If the low part is just padding, it takes no register, leave ResType
1755    // null.
1756    assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1757           "Unknown missing lo part");
1758    break;
1759
1760    // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1761    // on the stack.
1762  case Memory:
1763
1764    // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1765    // COMPLEX_X87, it is passed in memory.
1766  case X87:
1767  case ComplexX87:
1768    return getIndirectResult(Ty);
1769
1770  case SSEUp:
1771  case X87Up:
1772    assert(0 && "Invalid classification for lo word.");
1773
1774    // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1775    // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1776    // and %r9 is used.
1777  case Integer:
1778    ++neededInt;
1779
1780    // Pick an 8-byte type based on the preferred type.
1781    ResType = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(Ty), 0, Ty, 0);
1782
1783    // If we have a sign or zero extended integer, make sure to return Extend
1784    // so that the parameter gets the right LLVM IR attributes.
1785    if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1786      // Treat an enum type as its underlying type.
1787      if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1788        Ty = EnumTy->getDecl()->getIntegerType();
1789
1790      if (Ty->isIntegralOrEnumerationType() &&
1791          Ty->isPromotableIntegerType())
1792        return ABIArgInfo::getExtend();
1793    }
1794
1795    break;
1796
1797    // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1798    // available SSE register is used, the registers are taken in the
1799    // order from %xmm0 to %xmm7.
1800  case SSE: {
1801    const llvm::Type *IRType = CGT.ConvertTypeRecursive(Ty);
1802    if (Hi != NoClass || !UseX86_MMXType(IRType))
1803      ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
1804    else
1805      // This is an MMX type. Treat it as such.
1806      ResType = llvm::Type::getX86_MMXTy(getVMContext());
1807
1808    ++neededSSE;
1809    break;
1810  }
1811  }
1812
1813  const llvm::Type *HighPart = 0;
1814  switch (Hi) {
1815    // Memory was handled previously, ComplexX87 and X87 should
1816    // never occur as hi classes, and X87Up must be preceded by X87,
1817    // which is passed in memory.
1818  case Memory:
1819  case X87:
1820  case ComplexX87:
1821    assert(0 && "Invalid classification for hi word.");
1822    break;
1823
1824  case NoClass: break;
1825
1826  case Integer:
1827    ++neededInt;
1828    // Pick an 8-byte type based on the preferred type.
1829    HighPart = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(Ty), 8, Ty, 8);
1830
1831    if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
1832      return ABIArgInfo::getDirect(HighPart, 8);
1833    break;
1834
1835    // X87Up generally doesn't occur here (long double is passed in
1836    // memory), except in situations involving unions.
1837  case X87Up:
1838  case SSE:
1839    HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(Ty), 8, Ty, 8);
1840
1841    if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
1842      return ABIArgInfo::getDirect(HighPart, 8);
1843
1844    ++neededSSE;
1845    break;
1846
1847    // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1848    // eightbyte is passed in the upper half of the last used SSE
1849    // register.  This only happens when 128-bit vectors are passed.
1850  case SSEUp:
1851    assert(Lo == SSE && "Unexpected SSEUp classification");
1852    ResType = Get16ByteVectorType(Ty);
1853    break;
1854  }
1855
1856  // If a high part was specified, merge it together with the low part.  It is
1857  // known to pass in the high eightbyte of the result.  We do this by forming a
1858  // first class struct aggregate with the high and low part: {low, high}
1859  if (HighPart)
1860    ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1861
1862  return ABIArgInfo::getDirect(ResType);
1863}
1864
1865void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1866
1867  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1868
1869  // Keep track of the number of assigned registers.
1870  unsigned freeIntRegs = 6, freeSSERegs = 8;
1871
1872  // If the return value is indirect, then the hidden argument is consuming one
1873  // integer register.
1874  if (FI.getReturnInfo().isIndirect())
1875    --freeIntRegs;
1876
1877  // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1878  // get assigned (in left-to-right order) for passing as follows...
1879  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1880       it != ie; ++it) {
1881    unsigned neededInt, neededSSE;
1882    it->info = classifyArgumentType(it->type, neededInt, neededSSE);
1883
1884    // AMD64-ABI 3.2.3p3: If there are no registers available for any
1885    // eightbyte of an argument, the whole argument is passed on the
1886    // stack. If registers have already been assigned for some
1887    // eightbytes of such an argument, the assignments get reverted.
1888    if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1889      freeIntRegs -= neededInt;
1890      freeSSERegs -= neededSSE;
1891    } else {
1892      it->info = getIndirectResult(it->type);
1893    }
1894  }
1895}
1896
1897static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1898                                        QualType Ty,
1899                                        CodeGenFunction &CGF) {
1900  llvm::Value *overflow_arg_area_p =
1901    CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1902  llvm::Value *overflow_arg_area =
1903    CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1904
1905  // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1906  // byte boundary if alignment needed by type exceeds 8 byte boundary.
1907  uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1908  if (Align > 8) {
1909    // Note that we follow the ABI & gcc here, even though the type
1910    // could in theory have an alignment greater than 16. This case
1911    // shouldn't ever matter in practice.
1912
1913    // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1914    llvm::Value *Offset =
1915      llvm::ConstantInt::get(CGF.Int32Ty, 15);
1916    overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1917    llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1918                                                    CGF.Int64Ty);
1919    llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~15LL);
1920    overflow_arg_area =
1921      CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1922                                 overflow_arg_area->getType(),
1923                                 "overflow_arg_area.align");
1924  }
1925
1926  // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1927  const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1928  llvm::Value *Res =
1929    CGF.Builder.CreateBitCast(overflow_arg_area,
1930                              llvm::PointerType::getUnqual(LTy));
1931
1932  // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1933  // l->overflow_arg_area + sizeof(type).
1934  // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1935  // an 8 byte boundary.
1936
1937  uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1938  llvm::Value *Offset =
1939      llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
1940  overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1941                                            "overflow_arg_area.next");
1942  CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1943
1944  // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1945  return Res;
1946}
1947
1948llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1949                                      CodeGenFunction &CGF) const {
1950  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1951
1952  // Assume that va_list type is correct; should be pointer to LLVM type:
1953  // struct {
1954  //   i32 gp_offset;
1955  //   i32 fp_offset;
1956  //   i8* overflow_arg_area;
1957  //   i8* reg_save_area;
1958  // };
1959  unsigned neededInt, neededSSE;
1960
1961  Ty = CGF.getContext().getCanonicalType(Ty);
1962  ABIArgInfo AI = classifyArgumentType(Ty, neededInt, neededSSE);
1963
1964  // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1965  // in the registers. If not go to step 7.
1966  if (!neededInt && !neededSSE)
1967    return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1968
1969  // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1970  // general purpose registers needed to pass type and num_fp to hold
1971  // the number of floating point registers needed.
1972
1973  // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1974  // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1975  // l->fp_offset > 304 - num_fp * 16 go to step 7.
1976  //
1977  // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1978  // register save space).
1979
1980  llvm::Value *InRegs = 0;
1981  llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1982  llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1983  if (neededInt) {
1984    gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1985    gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1986    InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
1987    InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
1988  }
1989
1990  if (neededSSE) {
1991    fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1992    fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1993    llvm::Value *FitsInFP =
1994      llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
1995    FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
1996    InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1997  }
1998
1999  llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2000  llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2001  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2002  CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2003
2004  // Emit code to load the value if it was passed in registers.
2005
2006  CGF.EmitBlock(InRegBlock);
2007
2008  // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2009  // an offset of l->gp_offset and/or l->fp_offset. This may require
2010  // copying to a temporary location in case the parameter is passed
2011  // in different register classes or requires an alignment greater
2012  // than 8 for general purpose registers and 16 for XMM registers.
2013  //
2014  // FIXME: This really results in shameful code when we end up needing to
2015  // collect arguments from different places; often what should result in a
2016  // simple assembling of a structure from scattered addresses has many more
2017  // loads than necessary. Can we clean this up?
2018  const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2019  llvm::Value *RegAddr =
2020    CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2021                           "reg_save_area");
2022  if (neededInt && neededSSE) {
2023    // FIXME: Cleanup.
2024    assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2025    const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2026    llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
2027    assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2028    const llvm::Type *TyLo = ST->getElementType(0);
2029    const llvm::Type *TyHi = ST->getElementType(1);
2030    assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2031           "Unexpected ABI info for mixed regs");
2032    const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2033    const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2034    llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2035    llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2036    llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2037    llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
2038    llvm::Value *V =
2039      CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2040    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2041    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2042    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2043
2044    RegAddr = CGF.Builder.CreateBitCast(Tmp,
2045                                        llvm::PointerType::getUnqual(LTy));
2046  } else if (neededInt) {
2047    RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2048    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2049                                        llvm::PointerType::getUnqual(LTy));
2050  } else if (neededSSE == 1) {
2051    RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2052    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2053                                        llvm::PointerType::getUnqual(LTy));
2054  } else {
2055    assert(neededSSE == 2 && "Invalid number of needed registers!");
2056    // SSE registers are spaced 16 bytes apart in the register save
2057    // area, we need to collect the two eightbytes together.
2058    llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2059    llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2060    const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
2061    const llvm::Type *DblPtrTy =
2062      llvm::PointerType::getUnqual(DoubleTy);
2063    const llvm::StructType *ST = llvm::StructType::get(DoubleTy,
2064                                                       DoubleTy, NULL);
2065    llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
2066    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2067                                                         DblPtrTy));
2068    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2069    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2070                                                         DblPtrTy));
2071    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2072    RegAddr = CGF.Builder.CreateBitCast(Tmp,
2073                                        llvm::PointerType::getUnqual(LTy));
2074  }
2075
2076  // AMD64-ABI 3.5.7p5: Step 5. Set:
2077  // l->gp_offset = l->gp_offset + num_gp * 8
2078  // l->fp_offset = l->fp_offset + num_fp * 16.
2079  if (neededInt) {
2080    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2081    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2082                            gp_offset_p);
2083  }
2084  if (neededSSE) {
2085    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2086    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2087                            fp_offset_p);
2088  }
2089  CGF.EmitBranch(ContBlock);
2090
2091  // Emit code to load the value if it was passed in memory.
2092
2093  CGF.EmitBlock(InMemBlock);
2094  llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2095
2096  // Return the appropriate result.
2097
2098  CGF.EmitBlock(ContBlock);
2099  llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2100                                                 "vaarg.addr");
2101  ResAddr->addIncoming(RegAddr, InRegBlock);
2102  ResAddr->addIncoming(MemAddr, InMemBlock);
2103  return ResAddr;
2104}
2105
2106ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
2107
2108  if (Ty->isVoidType())
2109    return ABIArgInfo::getIgnore();
2110
2111  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2112    Ty = EnumTy->getDecl()->getIntegerType();
2113
2114  uint64_t Size = getContext().getTypeSize(Ty);
2115
2116  if (const RecordType *RT = Ty->getAs<RecordType>()) {
2117    if (hasNonTrivialDestructorOrCopyConstructor(RT) ||
2118        RT->getDecl()->hasFlexibleArrayMember())
2119      return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2120
2121    // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2122    if (Size == 128 &&
2123        getContext().Target.getTriple().getOS() == llvm::Triple::MinGW32)
2124      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2125                                                          Size));
2126
2127    // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2128    // not 1, 2, 4, or 8 bytes, must be passed by reference."
2129    if (Size <= 64 &&
2130        (Size & (Size - 1)) == 0)
2131      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2132                                                          Size));
2133
2134    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2135  }
2136
2137  if (Ty->isPromotableIntegerType())
2138    return ABIArgInfo::getExtend();
2139
2140  return ABIArgInfo::getDirect();
2141}
2142
2143void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2144
2145  QualType RetTy = FI.getReturnType();
2146  FI.getReturnInfo() = classify(RetTy);
2147
2148  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2149       it != ie; ++it)
2150    it->info = classify(it->type);
2151}
2152
2153llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2154                                      CodeGenFunction &CGF) const {
2155  const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2156  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2157
2158  CGBuilderTy &Builder = CGF.Builder;
2159  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2160                                                       "ap");
2161  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2162  llvm::Type *PTy =
2163    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2164  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2165
2166  uint64_t Offset =
2167    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2168  llvm::Value *NextAddr =
2169    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2170                      "ap.next");
2171  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2172
2173  return AddrTyped;
2174}
2175
2176// PowerPC-32
2177
2178namespace {
2179class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2180public:
2181  PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2182
2183  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2184    // This is recovered from gcc output.
2185    return 1; // r1 is the dedicated stack pointer
2186  }
2187
2188  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2189                               llvm::Value *Address) const;
2190};
2191
2192}
2193
2194bool
2195PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2196                                                llvm::Value *Address) const {
2197  // This is calculated from the LLVM and GCC tables and verified
2198  // against gcc output.  AFAIK all ABIs use the same encoding.
2199
2200  CodeGen::CGBuilderTy &Builder = CGF.Builder;
2201  llvm::LLVMContext &Context = CGF.getLLVMContext();
2202
2203  const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2204  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2205  llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2206  llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2207
2208  // 0-31: r0-31, the 4-byte general-purpose registers
2209  AssignToArrayRange(Builder, Address, Four8, 0, 31);
2210
2211  // 32-63: fp0-31, the 8-byte floating-point registers
2212  AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2213
2214  // 64-76 are various 4-byte special-purpose registers:
2215  // 64: mq
2216  // 65: lr
2217  // 66: ctr
2218  // 67: ap
2219  // 68-75 cr0-7
2220  // 76: xer
2221  AssignToArrayRange(Builder, Address, Four8, 64, 76);
2222
2223  // 77-108: v0-31, the 16-byte vector registers
2224  AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2225
2226  // 109: vrsave
2227  // 110: vscr
2228  // 111: spe_acc
2229  // 112: spefscr
2230  // 113: sfp
2231  AssignToArrayRange(Builder, Address, Four8, 109, 113);
2232
2233  return false;
2234}
2235
2236
2237//===----------------------------------------------------------------------===//
2238// ARM ABI Implementation
2239//===----------------------------------------------------------------------===//
2240
2241namespace {
2242
2243class ARMABIInfo : public ABIInfo {
2244public:
2245  enum ABIKind {
2246    APCS = 0,
2247    AAPCS = 1,
2248    AAPCS_VFP
2249  };
2250
2251private:
2252  ABIKind Kind;
2253
2254public:
2255  ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
2256
2257private:
2258  ABIKind getABIKind() const { return Kind; }
2259
2260  ABIArgInfo classifyReturnType(QualType RetTy) const;
2261  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2262
2263  virtual void computeInfo(CGFunctionInfo &FI) const;
2264
2265  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2266                                 CodeGenFunction &CGF) const;
2267};
2268
2269class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
2270public:
2271  ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
2272    :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
2273
2274  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2275    return 13;
2276  }
2277
2278  llvm::StringRef getARCRetainAutoreleasedReturnValueMarker() const {
2279    return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
2280  }
2281
2282  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2283                               llvm::Value *Address) const {
2284    CodeGen::CGBuilderTy &Builder = CGF.Builder;
2285    llvm::LLVMContext &Context = CGF.getLLVMContext();
2286
2287    const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2288    llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2289
2290    // 0-15 are the 16 integer registers.
2291    AssignToArrayRange(Builder, Address, Four8, 0, 15);
2292
2293    return false;
2294  }
2295};
2296
2297}
2298
2299void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
2300  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2301  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2302       it != ie; ++it)
2303    it->info = classifyArgumentType(it->type);
2304
2305  // Always honor user-specified calling convention.
2306  if (FI.getCallingConvention() != llvm::CallingConv::C)
2307    return;
2308
2309  // Calling convention as default by an ABI.
2310  llvm::CallingConv::ID DefaultCC;
2311  llvm::StringRef Env = getContext().Target.getTriple().getEnvironmentName();
2312  if (Env == "gnueabi" || Env == "eabi")
2313    DefaultCC = llvm::CallingConv::ARM_AAPCS;
2314  else
2315    DefaultCC = llvm::CallingConv::ARM_APCS;
2316
2317  // If user did not ask for specific calling convention explicitly (e.g. via
2318  // pcs attribute), set effective calling convention if it's different than ABI
2319  // default.
2320  switch (getABIKind()) {
2321  case APCS:
2322    if (DefaultCC != llvm::CallingConv::ARM_APCS)
2323      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
2324    break;
2325  case AAPCS:
2326    if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
2327      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
2328    break;
2329  case AAPCS_VFP:
2330    if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP)
2331      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
2332    break;
2333  }
2334}
2335
2336ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
2337  if (!isAggregateTypeForABI(Ty)) {
2338    // Treat an enum type as its underlying type.
2339    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2340      Ty = EnumTy->getDecl()->getIntegerType();
2341
2342    return (Ty->isPromotableIntegerType() ?
2343            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2344  }
2345
2346  // Ignore empty records.
2347  if (isEmptyRecord(getContext(), Ty, true))
2348    return ABIArgInfo::getIgnore();
2349
2350  // Structures with either a non-trivial destructor or a non-trivial
2351  // copy constructor are always indirect.
2352  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2353    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2354
2355  // Otherwise, pass by coercing to a structure of the appropriate size.
2356  //
2357  // FIXME: This doesn't handle alignment > 64 bits.
2358  const llvm::Type* ElemTy;
2359  unsigned SizeRegs;
2360  if (getContext().getTypeSizeInChars(Ty) <= CharUnits::fromQuantity(64)) {
2361    ElemTy = llvm::Type::getInt32Ty(getVMContext());
2362    SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
2363  } else if (getABIKind() == ARMABIInfo::APCS) {
2364    // Initial ARM ByVal support is APCS-only.
2365    return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
2366  } else {
2367    // FIXME: This is kind of nasty... but there isn't much choice
2368    // because most of the ARM calling conventions don't yet support
2369    // byval.
2370    ElemTy = llvm::Type::getInt64Ty(getVMContext());
2371    SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
2372  }
2373
2374  const llvm::Type *STy =
2375    llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
2376  return ABIArgInfo::getDirect(STy);
2377}
2378
2379static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
2380                              llvm::LLVMContext &VMContext) {
2381  // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
2382  // is called integer-like if its size is less than or equal to one word, and
2383  // the offset of each of its addressable sub-fields is zero.
2384
2385  uint64_t Size = Context.getTypeSize(Ty);
2386
2387  // Check that the type fits in a word.
2388  if (Size > 32)
2389    return false;
2390
2391  // FIXME: Handle vector types!
2392  if (Ty->isVectorType())
2393    return false;
2394
2395  // Float types are never treated as "integer like".
2396  if (Ty->isRealFloatingType())
2397    return false;
2398
2399  // If this is a builtin or pointer type then it is ok.
2400  if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
2401    return true;
2402
2403  // Small complex integer types are "integer like".
2404  if (const ComplexType *CT = Ty->getAs<ComplexType>())
2405    return isIntegerLikeType(CT->getElementType(), Context, VMContext);
2406
2407  // Single element and zero sized arrays should be allowed, by the definition
2408  // above, but they are not.
2409
2410  // Otherwise, it must be a record type.
2411  const RecordType *RT = Ty->getAs<RecordType>();
2412  if (!RT) return false;
2413
2414  // Ignore records with flexible arrays.
2415  const RecordDecl *RD = RT->getDecl();
2416  if (RD->hasFlexibleArrayMember())
2417    return false;
2418
2419  // Check that all sub-fields are at offset 0, and are themselves "integer
2420  // like".
2421  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2422
2423  bool HadField = false;
2424  unsigned idx = 0;
2425  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2426       i != e; ++i, ++idx) {
2427    const FieldDecl *FD = *i;
2428
2429    // Bit-fields are not addressable, we only need to verify they are "integer
2430    // like". We still have to disallow a subsequent non-bitfield, for example:
2431    //   struct { int : 0; int x }
2432    // is non-integer like according to gcc.
2433    if (FD->isBitField()) {
2434      if (!RD->isUnion())
2435        HadField = true;
2436
2437      if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2438        return false;
2439
2440      continue;
2441    }
2442
2443    // Check if this field is at offset 0.
2444    if (Layout.getFieldOffset(idx) != 0)
2445      return false;
2446
2447    if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2448      return false;
2449
2450    // Only allow at most one field in a structure. This doesn't match the
2451    // wording above, but follows gcc in situations with a field following an
2452    // empty structure.
2453    if (!RD->isUnion()) {
2454      if (HadField)
2455        return false;
2456
2457      HadField = true;
2458    }
2459  }
2460
2461  return true;
2462}
2463
2464ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
2465  if (RetTy->isVoidType())
2466    return ABIArgInfo::getIgnore();
2467
2468  // Large vector types should be returned via memory.
2469  if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
2470    return ABIArgInfo::getIndirect(0);
2471
2472  if (!isAggregateTypeForABI(RetTy)) {
2473    // Treat an enum type as its underlying type.
2474    if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2475      RetTy = EnumTy->getDecl()->getIntegerType();
2476
2477    return (RetTy->isPromotableIntegerType() ?
2478            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2479  }
2480
2481  // Structures with either a non-trivial destructor or a non-trivial
2482  // copy constructor are always indirect.
2483  if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
2484    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2485
2486  // Are we following APCS?
2487  if (getABIKind() == APCS) {
2488    if (isEmptyRecord(getContext(), RetTy, false))
2489      return ABIArgInfo::getIgnore();
2490
2491    // Complex types are all returned as packed integers.
2492    //
2493    // FIXME: Consider using 2 x vector types if the back end handles them
2494    // correctly.
2495    if (RetTy->isAnyComplexType())
2496      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2497                                              getContext().getTypeSize(RetTy)));
2498
2499    // Integer like structures are returned in r0.
2500    if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
2501      // Return in the smallest viable integer type.
2502      uint64_t Size = getContext().getTypeSize(RetTy);
2503      if (Size <= 8)
2504        return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2505      if (Size <= 16)
2506        return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2507      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2508    }
2509
2510    // Otherwise return in memory.
2511    return ABIArgInfo::getIndirect(0);
2512  }
2513
2514  // Otherwise this is an AAPCS variant.
2515
2516  if (isEmptyRecord(getContext(), RetTy, true))
2517    return ABIArgInfo::getIgnore();
2518
2519  // Aggregates <= 4 bytes are returned in r0; other aggregates
2520  // are returned indirectly.
2521  uint64_t Size = getContext().getTypeSize(RetTy);
2522  if (Size <= 32) {
2523    // Return in the smallest viable integer type.
2524    if (Size <= 8)
2525      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2526    if (Size <= 16)
2527      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2528    return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2529  }
2530
2531  return ABIArgInfo::getIndirect(0);
2532}
2533
2534llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2535                                   CodeGenFunction &CGF) const {
2536  // FIXME: Need to handle alignment
2537  const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2538  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2539
2540  CGBuilderTy &Builder = CGF.Builder;
2541  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2542                                                       "ap");
2543  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2544  llvm::Type *PTy =
2545    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2546  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2547
2548  uint64_t Offset =
2549    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
2550  llvm::Value *NextAddr =
2551    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2552                      "ap.next");
2553  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2554
2555  return AddrTyped;
2556}
2557
2558//===----------------------------------------------------------------------===//
2559// PTX ABI Implementation
2560//===----------------------------------------------------------------------===//
2561
2562namespace {
2563
2564class PTXABIInfo : public ABIInfo {
2565public:
2566  PTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2567
2568  ABIArgInfo classifyReturnType(QualType RetTy) const;
2569  ABIArgInfo classifyArgumentType(QualType Ty) const;
2570
2571  virtual void computeInfo(CGFunctionInfo &FI) const;
2572  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2573                                 CodeGenFunction &CFG) const;
2574};
2575
2576class PTXTargetCodeGenInfo : public TargetCodeGenInfo {
2577public:
2578  PTXTargetCodeGenInfo(CodeGenTypes &CGT)
2579    : TargetCodeGenInfo(new PTXABIInfo(CGT)) {}
2580};
2581
2582ABIArgInfo PTXABIInfo::classifyReturnType(QualType RetTy) const {
2583  if (RetTy->isVoidType())
2584    return ABIArgInfo::getIgnore();
2585  if (isAggregateTypeForABI(RetTy))
2586    return ABIArgInfo::getIndirect(0);
2587  return ABIArgInfo::getDirect();
2588}
2589
2590ABIArgInfo PTXABIInfo::classifyArgumentType(QualType Ty) const {
2591  if (isAggregateTypeForABI(Ty))
2592    return ABIArgInfo::getIndirect(0);
2593
2594  return ABIArgInfo::getDirect();
2595}
2596
2597void PTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
2598  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2599  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2600       it != ie; ++it)
2601    it->info = classifyArgumentType(it->type);
2602
2603  // Always honor user-specified calling convention.
2604  if (FI.getCallingConvention() != llvm::CallingConv::C)
2605    return;
2606
2607  // Calling convention as default by an ABI.
2608  llvm::CallingConv::ID DefaultCC;
2609  llvm::StringRef Env = getContext().Target.getTriple().getEnvironmentName();
2610  if (Env == "device")
2611    DefaultCC = llvm::CallingConv::PTX_Device;
2612  else
2613    DefaultCC = llvm::CallingConv::PTX_Kernel;
2614
2615  FI.setEffectiveCallingConvention(DefaultCC);
2616}
2617
2618llvm::Value *PTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2619                                   CodeGenFunction &CFG) const {
2620  llvm_unreachable("PTX does not support varargs");
2621  return 0;
2622}
2623
2624}
2625
2626//===----------------------------------------------------------------------===//
2627// SystemZ ABI Implementation
2628//===----------------------------------------------------------------------===//
2629
2630namespace {
2631
2632class SystemZABIInfo : public ABIInfo {
2633public:
2634  SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2635
2636  bool isPromotableIntegerType(QualType Ty) const;
2637
2638  ABIArgInfo classifyReturnType(QualType RetTy) const;
2639  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2640
2641  virtual void computeInfo(CGFunctionInfo &FI) const {
2642    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2643    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2644         it != ie; ++it)
2645      it->info = classifyArgumentType(it->type);
2646  }
2647
2648  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2649                                 CodeGenFunction &CGF) const;
2650};
2651
2652class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
2653public:
2654  SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
2655    : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
2656};
2657
2658}
2659
2660bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
2661  // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
2662  if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2663    switch (BT->getKind()) {
2664    case BuiltinType::Bool:
2665    case BuiltinType::Char_S:
2666    case BuiltinType::Char_U:
2667    case BuiltinType::SChar:
2668    case BuiltinType::UChar:
2669    case BuiltinType::Short:
2670    case BuiltinType::UShort:
2671    case BuiltinType::Int:
2672    case BuiltinType::UInt:
2673      return true;
2674    default:
2675      return false;
2676    }
2677  return false;
2678}
2679
2680llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2681                                       CodeGenFunction &CGF) const {
2682  // FIXME: Implement
2683  return 0;
2684}
2685
2686
2687ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
2688  if (RetTy->isVoidType())
2689    return ABIArgInfo::getIgnore();
2690  if (isAggregateTypeForABI(RetTy))
2691    return ABIArgInfo::getIndirect(0);
2692
2693  return (isPromotableIntegerType(RetTy) ?
2694          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2695}
2696
2697ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
2698  if (isAggregateTypeForABI(Ty))
2699    return ABIArgInfo::getIndirect(0);
2700
2701  return (isPromotableIntegerType(Ty) ?
2702          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2703}
2704
2705//===----------------------------------------------------------------------===//
2706// MBlaze ABI Implementation
2707//===----------------------------------------------------------------------===//
2708
2709namespace {
2710
2711class MBlazeABIInfo : public ABIInfo {
2712public:
2713  MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2714
2715  bool isPromotableIntegerType(QualType Ty) const;
2716
2717  ABIArgInfo classifyReturnType(QualType RetTy) const;
2718  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2719
2720  virtual void computeInfo(CGFunctionInfo &FI) const {
2721    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2722    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2723         it != ie; ++it)
2724      it->info = classifyArgumentType(it->type);
2725  }
2726
2727  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2728                                 CodeGenFunction &CGF) const;
2729};
2730
2731class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
2732public:
2733  MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
2734    : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
2735  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2736                           CodeGen::CodeGenModule &M) const;
2737};
2738
2739}
2740
2741bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
2742  // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
2743  if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2744    switch (BT->getKind()) {
2745    case BuiltinType::Bool:
2746    case BuiltinType::Char_S:
2747    case BuiltinType::Char_U:
2748    case BuiltinType::SChar:
2749    case BuiltinType::UChar:
2750    case BuiltinType::Short:
2751    case BuiltinType::UShort:
2752      return true;
2753    default:
2754      return false;
2755    }
2756  return false;
2757}
2758
2759llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2760                                      CodeGenFunction &CGF) const {
2761  // FIXME: Implement
2762  return 0;
2763}
2764
2765
2766ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
2767  if (RetTy->isVoidType())
2768    return ABIArgInfo::getIgnore();
2769  if (isAggregateTypeForABI(RetTy))
2770    return ABIArgInfo::getIndirect(0);
2771
2772  return (isPromotableIntegerType(RetTy) ?
2773          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2774}
2775
2776ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
2777  if (isAggregateTypeForABI(Ty))
2778    return ABIArgInfo::getIndirect(0);
2779
2780  return (isPromotableIntegerType(Ty) ?
2781          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2782}
2783
2784void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2785                                                  llvm::GlobalValue *GV,
2786                                                  CodeGen::CodeGenModule &M)
2787                                                  const {
2788  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2789  if (!FD) return;
2790
2791  llvm::CallingConv::ID CC = llvm::CallingConv::C;
2792  if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
2793    CC = llvm::CallingConv::MBLAZE_INTR;
2794  else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
2795    CC = llvm::CallingConv::MBLAZE_SVOL;
2796
2797  if (CC != llvm::CallingConv::C) {
2798      // Handle 'interrupt_handler' attribute:
2799      llvm::Function *F = cast<llvm::Function>(GV);
2800
2801      // Step 1: Set ISR calling convention.
2802      F->setCallingConv(CC);
2803
2804      // Step 2: Add attributes goodness.
2805      F->addFnAttr(llvm::Attribute::NoInline);
2806  }
2807
2808  // Step 3: Emit _interrupt_handler alias.
2809  if (CC == llvm::CallingConv::MBLAZE_INTR)
2810    new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
2811                          "_interrupt_handler", GV, &M.getModule());
2812}
2813
2814
2815//===----------------------------------------------------------------------===//
2816// MSP430 ABI Implementation
2817//===----------------------------------------------------------------------===//
2818
2819namespace {
2820
2821class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
2822public:
2823  MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
2824    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
2825  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2826                           CodeGen::CodeGenModule &M) const;
2827};
2828
2829}
2830
2831void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2832                                                  llvm::GlobalValue *GV,
2833                                             CodeGen::CodeGenModule &M) const {
2834  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2835    if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
2836      // Handle 'interrupt' attribute:
2837      llvm::Function *F = cast<llvm::Function>(GV);
2838
2839      // Step 1: Set ISR calling convention.
2840      F->setCallingConv(llvm::CallingConv::MSP430_INTR);
2841
2842      // Step 2: Add attributes goodness.
2843      F->addFnAttr(llvm::Attribute::NoInline);
2844
2845      // Step 3: Emit ISR vector alias.
2846      unsigned Num = attr->getNumber() + 0xffe0;
2847      new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
2848                            "vector_" + llvm::Twine::utohexstr(Num),
2849                            GV, &M.getModule());
2850    }
2851  }
2852}
2853
2854//===----------------------------------------------------------------------===//
2855// MIPS ABI Implementation.  This works for both little-endian and
2856// big-endian variants.
2857//===----------------------------------------------------------------------===//
2858
2859namespace {
2860class MipsABIInfo : public ABIInfo {
2861public:
2862  MipsABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2863
2864  ABIArgInfo classifyReturnType(QualType RetTy) const;
2865  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2866  virtual void computeInfo(CGFunctionInfo &FI) const;
2867  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2868                                 CodeGenFunction &CGF) const;
2869};
2870
2871class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
2872public:
2873  MIPSTargetCodeGenInfo(CodeGenTypes &CGT)
2874    : TargetCodeGenInfo(new MipsABIInfo(CGT)) {}
2875
2876  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
2877    return 29;
2878  }
2879
2880  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2881                               llvm::Value *Address) const;
2882};
2883}
2884
2885ABIArgInfo MipsABIInfo::classifyArgumentType(QualType Ty) const {
2886  if (isAggregateTypeForABI(Ty)) {
2887    // Ignore empty aggregates.
2888    if (getContext().getTypeSize(Ty) == 0)
2889      return ABIArgInfo::getIgnore();
2890
2891    return ABIArgInfo::getIndirect(0);
2892  }
2893
2894  // Treat an enum type as its underlying type.
2895  if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2896    Ty = EnumTy->getDecl()->getIntegerType();
2897
2898  return (Ty->isPromotableIntegerType() ?
2899          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2900}
2901
2902ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
2903  if (RetTy->isVoidType())
2904    return ABIArgInfo::getIgnore();
2905
2906  if (isAggregateTypeForABI(RetTy)) {
2907    if (RetTy->isAnyComplexType())
2908      return ABIArgInfo::getDirect();
2909
2910    return ABIArgInfo::getIndirect(0);
2911  }
2912
2913  // Treat an enum type as its underlying type.
2914  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2915    RetTy = EnumTy->getDecl()->getIntegerType();
2916
2917  return (RetTy->isPromotableIntegerType() ?
2918          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2919}
2920
2921void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
2922  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2923  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2924       it != ie; ++it)
2925    it->info = classifyArgumentType(it->type);
2926}
2927
2928llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2929                                    CodeGenFunction &CGF) const {
2930  return 0;
2931}
2932
2933bool
2934MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2935                                               llvm::Value *Address) const {
2936  // This information comes from gcc's implementation, which seems to
2937  // as canonical as it gets.
2938
2939  CodeGen::CGBuilderTy &Builder = CGF.Builder;
2940  llvm::LLVMContext &Context = CGF.getLLVMContext();
2941
2942  // Everything on MIPS is 4 bytes.  Double-precision FP registers
2943  // are aliased to pairs of single-precision FP registers.
2944  const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2945  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2946
2947  // 0-31 are the general purpose registers, $0 - $31.
2948  // 32-63 are the floating-point registers, $f0 - $f31.
2949  // 64 and 65 are the multiply/divide registers, $hi and $lo.
2950  // 66 is the (notional, I think) register for signal-handler return.
2951  AssignToArrayRange(Builder, Address, Four8, 0, 65);
2952
2953  // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
2954  // They are one bit wide and ignored here.
2955
2956  // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
2957  // (coprocessor 1 is the FP unit)
2958  // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
2959  // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
2960  // 176-181 are the DSP accumulator registers.
2961  AssignToArrayRange(Builder, Address, Four8, 80, 181);
2962
2963  return false;
2964}
2965
2966
2967const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
2968  if (TheTargetCodeGenInfo)
2969    return *TheTargetCodeGenInfo;
2970
2971  // For now we just cache the TargetCodeGenInfo in CodeGenModule and don't
2972  // free it.
2973
2974  const llvm::Triple &Triple = getContext().Target.getTriple();
2975  switch (Triple.getArch()) {
2976  default:
2977    return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
2978
2979  case llvm::Triple::mips:
2980  case llvm::Triple::mipsel:
2981    return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types));
2982
2983  case llvm::Triple::arm:
2984  case llvm::Triple::thumb:
2985    {
2986      ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
2987
2988      if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
2989        Kind = ARMABIInfo::APCS;
2990      else if (CodeGenOpts.FloatABI == "hard")
2991        Kind = ARMABIInfo::AAPCS_VFP;
2992
2993      return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
2994    }
2995
2996  case llvm::Triple::ppc:
2997    return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
2998
2999  case llvm::Triple::ptx32:
3000  case llvm::Triple::ptx64:
3001    return *(TheTargetCodeGenInfo = new PTXTargetCodeGenInfo(Types));
3002
3003  case llvm::Triple::systemz:
3004    return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
3005
3006  case llvm::Triple::mblaze:
3007    return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
3008
3009  case llvm::Triple::msp430:
3010    return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
3011
3012  case llvm::Triple::x86:
3013    if (Triple.isOSDarwin())
3014      return *(TheTargetCodeGenInfo =
3015               new X86_32TargetCodeGenInfo(Types, true, true));
3016
3017    switch (Triple.getOS()) {
3018    case llvm::Triple::Cygwin:
3019    case llvm::Triple::MinGW32:
3020    case llvm::Triple::AuroraUX:
3021    case llvm::Triple::DragonFly:
3022    case llvm::Triple::FreeBSD:
3023    case llvm::Triple::OpenBSD:
3024    case llvm::Triple::NetBSD:
3025      return *(TheTargetCodeGenInfo =
3026               new X86_32TargetCodeGenInfo(Types, false, true));
3027
3028    default:
3029      return *(TheTargetCodeGenInfo =
3030               new X86_32TargetCodeGenInfo(Types, false, false));
3031    }
3032
3033  case llvm::Triple::x86_64:
3034    switch (Triple.getOS()) {
3035    case llvm::Triple::Win32:
3036    case llvm::Triple::MinGW32:
3037    case llvm::Triple::Cygwin:
3038      return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
3039    default:
3040      return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));
3041    }
3042  }
3043}
3044