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