TargetInfo.cpp revision 4711cb065922d46bfe80383b2001ae681f74780a
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";
60    break;
61  case Extend:
62    OS << "Extend";
63    break;
64  case Ignore:
65    OS << "Ignore";
66    break;
67  case Coerce:
68    OS << "Coerce Type=";
69    getCoerceToType()->print(OS);
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::getCoerce(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::getCoerce(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::getCoerce(
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::getCoerce(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::getCoerce(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::getCoerce(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::getCoerce(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 *Get8ByteTypeAtOffset(const llvm::Type *IRType,
721                                         unsigned IROffset, QualType SourceTy,
722                                         unsigned SourceOffset) const;
723
724  /// getCoerceResult - Given a source type \arg Ty and an LLVM type
725  /// to coerce to, chose the best way to pass Ty in the same place
726  /// that \arg CoerceTo would be passed, but while keeping the
727  /// emitted code as simple as possible.
728  ///
729  /// FIXME: Note, this should be cleaned up to just take an enumeration of all
730  /// the ways we might want to pass things, instead of constructing an LLVM
731  /// type. This makes this code more explicit, and it makes it clearer that we
732  /// are also doing this for correctness in the case of passing scalar types.
733  ABIArgInfo getCoerceResult(QualType Ty,
734                             const llvm::Type *CoerceTo) const;
735
736  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
737  /// such that the argument will be returned in memory.
738  ABIArgInfo getIndirectReturnResult(QualType Ty) const;
739
740  /// getIndirectResult - Give a source type \arg Ty, return a suitable result
741  /// such that the argument will be passed in memory.
742  ABIArgInfo getIndirectResult(QualType Ty) const;
743
744  ABIArgInfo classifyReturnType(QualType RetTy) const;
745
746  ABIArgInfo classifyArgumentType(QualType Ty, unsigned &neededInt,
747                                  unsigned &neededSSE) const;
748
749public:
750  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
751
752  virtual void computeInfo(CGFunctionInfo &FI) const;
753
754  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
755                                 CodeGenFunction &CGF) const;
756};
757
758class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
759public:
760  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
761    : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
762
763  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
764    return 7;
765  }
766
767  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
768                               llvm::Value *Address) const {
769    CodeGen::CGBuilderTy &Builder = CGF.Builder;
770    llvm::LLVMContext &Context = CGF.getLLVMContext();
771
772    const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
773    llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
774
775    // 0-15 are the 16 integer registers.
776    // 16 is %rip.
777    AssignToArrayRange(Builder, Address, Eight8, 0, 16);
778
779    return false;
780  }
781};
782
783}
784
785X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
786  // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
787  // classified recursively so that always two fields are
788  // considered. The resulting class is calculated according to
789  // the classes of the fields in the eightbyte:
790  //
791  // (a) If both classes are equal, this is the resulting class.
792  //
793  // (b) If one of the classes is NO_CLASS, the resulting class is
794  // the other class.
795  //
796  // (c) If one of the classes is MEMORY, the result is the MEMORY
797  // class.
798  //
799  // (d) If one of the classes is INTEGER, the result is the
800  // INTEGER.
801  //
802  // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
803  // MEMORY is used as class.
804  //
805  // (f) Otherwise class SSE is used.
806
807  // Accum should never be memory (we should have returned) or
808  // ComplexX87 (because this cannot be passed in a structure).
809  assert((Accum != Memory && Accum != ComplexX87) &&
810         "Invalid accumulated classification during merge.");
811  if (Accum == Field || Field == NoClass)
812    return Accum;
813  if (Field == Memory)
814    return Memory;
815  if (Accum == NoClass)
816    return Field;
817  if (Accum == Integer || Field == Integer)
818    return Integer;
819  if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
820      Accum == X87 || Accum == X87Up)
821    return Memory;
822  return SSE;
823}
824
825void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
826                             Class &Lo, Class &Hi) const {
827  // FIXME: This code can be simplified by introducing a simple value class for
828  // Class pairs with appropriate constructor methods for the various
829  // situations.
830
831  // FIXME: Some of the split computations are wrong; unaligned vectors
832  // shouldn't be passed in registers for example, so there is no chance they
833  // can straddle an eightbyte. Verify & simplify.
834
835  Lo = Hi = NoClass;
836
837  Class &Current = OffsetBase < 64 ? Lo : Hi;
838  Current = Memory;
839
840  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
841    BuiltinType::Kind k = BT->getKind();
842
843    if (k == BuiltinType::Void) {
844      Current = NoClass;
845    } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
846      Lo = Integer;
847      Hi = Integer;
848    } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
849      Current = Integer;
850    } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
851      Current = SSE;
852    } else if (k == BuiltinType::LongDouble) {
853      Lo = X87;
854      Hi = X87Up;
855    }
856    // FIXME: _Decimal32 and _Decimal64 are SSE.
857    // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
858    return;
859  }
860
861  if (const EnumType *ET = Ty->getAs<EnumType>()) {
862    // Classify the underlying integer type.
863    classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
864    return;
865  }
866
867  if (Ty->hasPointerRepresentation()) {
868    Current = Integer;
869    return;
870  }
871
872  if (Ty->isMemberPointerType()) {
873    if (Ty->isMemberFunctionPointerType())
874      Lo = Hi = Integer;
875    else
876      Current = Integer;
877    return;
878  }
879
880  if (const VectorType *VT = Ty->getAs<VectorType>()) {
881    uint64_t Size = getContext().getTypeSize(VT);
882    if (Size == 32) {
883      // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
884      // float> as integer.
885      Current = Integer;
886
887      // If this type crosses an eightbyte boundary, it should be
888      // split.
889      uint64_t EB_Real = (OffsetBase) / 64;
890      uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
891      if (EB_Real != EB_Imag)
892        Hi = Lo;
893    } else if (Size == 64) {
894      // gcc passes <1 x double> in memory. :(
895      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
896        return;
897
898      // gcc passes <1 x long long> as INTEGER.
899      if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
900        Current = Integer;
901      else
902        Current = SSE;
903
904      // If this type crosses an eightbyte boundary, it should be
905      // split.
906      if (OffsetBase && OffsetBase != 64)
907        Hi = Lo;
908    } else if (Size == 128) {
909      Lo = SSE;
910      Hi = SSEUp;
911    }
912    return;
913  }
914
915  if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
916    QualType ET = getContext().getCanonicalType(CT->getElementType());
917
918    uint64_t Size = getContext().getTypeSize(Ty);
919    if (ET->isIntegralOrEnumerationType()) {
920      if (Size <= 64)
921        Current = Integer;
922      else if (Size <= 128)
923        Lo = Hi = Integer;
924    } else if (ET == getContext().FloatTy)
925      Current = SSE;
926    else if (ET == getContext().DoubleTy)
927      Lo = Hi = SSE;
928    else if (ET == getContext().LongDoubleTy)
929      Current = ComplexX87;
930
931    // If this complex type crosses an eightbyte boundary then it
932    // should be split.
933    uint64_t EB_Real = (OffsetBase) / 64;
934    uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
935    if (Hi == NoClass && EB_Real != EB_Imag)
936      Hi = Lo;
937
938    return;
939  }
940
941  if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
942    // Arrays are treated like structures.
943
944    uint64_t Size = getContext().getTypeSize(Ty);
945
946    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
947    // than two eightbytes, ..., it has class MEMORY.
948    if (Size > 128)
949      return;
950
951    // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
952    // fields, it has class MEMORY.
953    //
954    // Only need to check alignment of array base.
955    if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
956      return;
957
958    // Otherwise implement simplified merge. We could be smarter about
959    // this, but it isn't worth it and would be harder to verify.
960    Current = NoClass;
961    uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
962    uint64_t ArraySize = AT->getSize().getZExtValue();
963    for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
964      Class FieldLo, FieldHi;
965      classify(AT->getElementType(), Offset, FieldLo, FieldHi);
966      Lo = merge(Lo, FieldLo);
967      Hi = merge(Hi, FieldHi);
968      if (Lo == Memory || Hi == Memory)
969        break;
970    }
971
972    // Do post merger cleanup (see below). Only case we worry about is Memory.
973    if (Hi == Memory)
974      Lo = Memory;
975    assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
976    return;
977  }
978
979  if (const RecordType *RT = Ty->getAs<RecordType>()) {
980    uint64_t Size = getContext().getTypeSize(Ty);
981
982    // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
983    // than two eightbytes, ..., it has class MEMORY.
984    if (Size > 128)
985      return;
986
987    // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
988    // copy constructor or a non-trivial destructor, it is passed by invisible
989    // reference.
990    if (hasNonTrivialDestructorOrCopyConstructor(RT))
991      return;
992
993    const RecordDecl *RD = RT->getDecl();
994
995    // Assume variable sized types are passed in memory.
996    if (RD->hasFlexibleArrayMember())
997      return;
998
999    const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1000
1001    // Reset Lo class, this will be recomputed.
1002    Current = NoClass;
1003
1004    // If this is a C++ record, classify the bases first.
1005    if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1006      for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1007             e = CXXRD->bases_end(); i != e; ++i) {
1008        assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1009               "Unexpected base class!");
1010        const CXXRecordDecl *Base =
1011          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1012
1013        // Classify this field.
1014        //
1015        // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1016        // single eightbyte, each is classified separately. Each eightbyte gets
1017        // initialized to class NO_CLASS.
1018        Class FieldLo, FieldHi;
1019        uint64_t Offset = OffsetBase + Layout.getBaseClassOffset(Base);
1020        classify(i->getType(), Offset, FieldLo, FieldHi);
1021        Lo = merge(Lo, FieldLo);
1022        Hi = merge(Hi, FieldHi);
1023        if (Lo == Memory || Hi == Memory)
1024          break;
1025      }
1026
1027      // If this record has no fields but isn't empty, classify as INTEGER.
1028      if (RD->field_empty() && Size)
1029        Current = Integer;
1030    }
1031
1032    // Classify the fields one at a time, merging the results.
1033    unsigned idx = 0;
1034    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1035           i != e; ++i, ++idx) {
1036      uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1037      bool BitField = i->isBitField();
1038
1039      // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1040      // fields, it has class MEMORY.
1041      //
1042      // Note, skip this test for bit-fields, see below.
1043      if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1044        Lo = Memory;
1045        return;
1046      }
1047
1048      // Classify this field.
1049      //
1050      // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1051      // exceeds a single eightbyte, each is classified
1052      // separately. Each eightbyte gets initialized to class
1053      // NO_CLASS.
1054      Class FieldLo, FieldHi;
1055
1056      // Bit-fields require special handling, they do not force the
1057      // structure to be passed in memory even if unaligned, and
1058      // therefore they can straddle an eightbyte.
1059      if (BitField) {
1060        // Ignore padding bit-fields.
1061        if (i->isUnnamedBitfield())
1062          continue;
1063
1064        uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1065        uint64_t Size =
1066          i->getBitWidth()->EvaluateAsInt(getContext()).getZExtValue();
1067
1068        uint64_t EB_Lo = Offset / 64;
1069        uint64_t EB_Hi = (Offset + Size - 1) / 64;
1070        FieldLo = FieldHi = NoClass;
1071        if (EB_Lo) {
1072          assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1073          FieldLo = NoClass;
1074          FieldHi = Integer;
1075        } else {
1076          FieldLo = Integer;
1077          FieldHi = EB_Hi ? Integer : NoClass;
1078        }
1079      } else
1080        classify(i->getType(), Offset, FieldLo, FieldHi);
1081      Lo = merge(Lo, FieldLo);
1082      Hi = merge(Hi, FieldHi);
1083      if (Lo == Memory || Hi == Memory)
1084        break;
1085    }
1086
1087    // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1088    //
1089    // (a) If one of the classes is MEMORY, the whole argument is
1090    // passed in memory.
1091    //
1092    // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
1093
1094    // The first of these conditions is guaranteed by how we implement
1095    // the merge (just bail).
1096    //
1097    // The second condition occurs in the case of unions; for example
1098    // union { _Complex double; unsigned; }.
1099    if (Hi == Memory)
1100      Lo = Memory;
1101    if (Hi == SSEUp && Lo != SSE)
1102      Hi = SSE;
1103  }
1104}
1105
1106ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
1107                                          const llvm::Type *CoerceTo) const {
1108  // If this is a pointer passed as a pointer, just pass it directly.
1109  if ((isa<llvm::PointerType>(CoerceTo) || CoerceTo->isIntegerTy(64)) &&
1110      Ty->hasPointerRepresentation())
1111    return ABIArgInfo::getExtend();
1112
1113  if (isa<llvm::IntegerType>(CoerceTo)) {
1114    // Integer and pointer types will end up in a general purpose
1115    // register.
1116
1117    // Treat an enum type as its underlying type.
1118    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1119      Ty = EnumTy->getDecl()->getIntegerType();
1120
1121    if (Ty->isIntegralOrEnumerationType())
1122      return (Ty->isPromotableIntegerType() ?
1123              ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1124
1125  } else if (CoerceTo->isDoubleTy()) {
1126    assert(Ty.isCanonical() && "should always have a canonical type here");
1127    assert(!Ty.hasQualifiers() && "should never have a qualified type here");
1128
1129    // Float and double end up in a single SSE reg.
1130    if (Ty == getContext().FloatTy || Ty == getContext().DoubleTy)
1131      return ABIArgInfo::getDirect();
1132
1133    // If this is a 32-bit structure that is passed as a double, then it will be
1134    // passed in the low 32-bits of the XMM register, which is the same as how a
1135    // float is passed.  Coerce to a float instead of a double.
1136    if (getContext().getTypeSizeInChars(Ty).getQuantity() == 4)
1137      CoerceTo = llvm::Type::getFloatTy(CoerceTo->getContext());
1138  }
1139
1140  return ABIArgInfo::getCoerce(CoerceTo);
1141}
1142
1143ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1144  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1145  // place naturally.
1146  if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1147    // Treat an enum type as its underlying type.
1148    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1149      Ty = EnumTy->getDecl()->getIntegerType();
1150
1151    return (Ty->isPromotableIntegerType() ?
1152            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1153  }
1154
1155  return ABIArgInfo::getIndirect(0);
1156}
1157
1158ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const {
1159  // If this is a scalar LLVM value then assume LLVM will pass it in the right
1160  // place naturally.
1161  if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1162    // Treat an enum type as its underlying type.
1163    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1164      Ty = EnumTy->getDecl()->getIntegerType();
1165
1166    return (Ty->isPromotableIntegerType() ?
1167            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1168  }
1169
1170  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1171    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1172
1173  // Compute the byval alignment. We trust the back-end to honor the
1174  // minimum ABI alignment for byval, to make cleaner IR.
1175  const unsigned MinABIAlign = 8;
1176  unsigned Align = getContext().getTypeAlign(Ty) / 8;
1177  if (Align > MinABIAlign)
1178    return ABIArgInfo::getIndirect(Align);
1179  return ABIArgInfo::getIndirect(0);
1180}
1181
1182/// Get8ByteTypeAtOffset - The ABI specifies that a value should be passed in an
1183/// 8-byte GPR.  This means that we either have a scalar or we are talking about
1184/// the high or low part of an up-to-16-byte struct.  This routine picks the
1185/// best LLVM IR type to represent this, which may be i64 or may be anything
1186/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1187/// etc).
1188///
1189/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1190/// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1191/// the 8-byte value references.  PrefType may be null.
1192///
1193/// SourceTy is the source level type for the entire argument.  SourceOffset is
1194/// an offset into this that we're processing (which is always either 0 or 8).
1195///
1196const llvm::Type *X86_64ABIInfo::
1197Get8ByteTypeAtOffset(const llvm::Type *IRType, unsigned IROffset,
1198                     QualType SourceTy, unsigned SourceOffset) const {
1199  // Pointers are always 8-bytes at offset 0.
1200  if (IROffset == 0 && IRType && isa<llvm::PointerType>(IRType))
1201    return IRType;
1202
1203  // TODO: 1/2/4/8 byte integers are also interesting, but we have to know that
1204  // the "hole" is not used in the containing struct (just undef padding).
1205
1206  if (const llvm::StructType *STy = dyn_cast_or_null<llvm::StructType>(IRType)){
1207    // If this is a struct, recurse into the field at the specified offset.
1208    const llvm::StructLayout *SL = getTargetData().getStructLayout(STy);
1209    if (IROffset < SL->getSizeInBytes()) {
1210      unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1211      IROffset -= SL->getElementOffset(FieldIdx);
1212
1213      return Get8ByteTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1214                                  SourceTy, SourceOffset);
1215    }
1216  }
1217
1218  // Okay, we don't have any better idea of what to pass, so we pass this in an
1219  // integer register that isn't too big to fit the rest of the struct.
1220  uint64_t TySizeInBytes =
1221    getContext().getTypeSizeInChars(SourceTy).getQuantity();
1222
1223  // It is always safe to classify this as an integer type up to i64 that
1224  // isn't larger than the structure.
1225  switch (unsigned(TySizeInBytes-SourceOffset)) {
1226  case 1:  return llvm::Type::getInt8Ty(getVMContext());
1227  case 2:  return llvm::Type::getInt16Ty(getVMContext());
1228  case 3:
1229  case 4:  return llvm::Type::getInt32Ty(getVMContext());
1230  default: return llvm::Type::getInt64Ty(getVMContext());
1231  }
1232}
1233
1234ABIArgInfo X86_64ABIInfo::
1235classifyReturnType(QualType RetTy) const {
1236  // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1237  // classification algorithm.
1238  X86_64ABIInfo::Class Lo, Hi;
1239  classify(RetTy, 0, Lo, Hi);
1240
1241  // Check some invariants.
1242  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1243  assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
1244  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1245
1246  const llvm::Type *IRType = 0;
1247  const llvm::Type *ResType = 0;
1248  switch (Lo) {
1249  case NoClass:
1250    return ABIArgInfo::getIgnore();
1251
1252  case SSEUp:
1253  case X87Up:
1254    assert(0 && "Invalid classification for lo word.");
1255
1256    // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1257    // hidden argument.
1258  case Memory:
1259    return getIndirectReturnResult(RetTy);
1260
1261    // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1262    // available register of the sequence %rax, %rdx is used.
1263  case Integer:
1264    if (IRType == 0)
1265      IRType = CGT.ConvertTypeRecursive(RetTy);
1266
1267    ResType = Get8ByteTypeAtOffset(IRType, 0, RetTy, 0);
1268    break;
1269
1270    // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1271    // available SSE register of the sequence %xmm0, %xmm1 is used.
1272  case SSE:
1273    ResType = llvm::Type::getDoubleTy(getVMContext());
1274    break;
1275
1276    // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1277    // returned on the X87 stack in %st0 as 80-bit x87 number.
1278  case X87:
1279    ResType = llvm::Type::getX86_FP80Ty(getVMContext());
1280    break;
1281
1282    // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1283    // part of the value is returned in %st0 and the imaginary part in
1284    // %st1.
1285  case ComplexX87:
1286    assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1287    ResType = llvm::StructType::get(getVMContext(),
1288                                    llvm::Type::getX86_FP80Ty(getVMContext()),
1289                                    llvm::Type::getX86_FP80Ty(getVMContext()),
1290                                    NULL);
1291    break;
1292  }
1293
1294  switch (Hi) {
1295    // Memory was handled previously and X87 should
1296    // never occur as a hi class.
1297  case Memory:
1298  case X87:
1299    assert(0 && "Invalid classification for hi word.");
1300
1301  case ComplexX87: // Previously handled.
1302  case NoClass:
1303    break;
1304
1305  case Integer: {
1306    if (IRType == 0)
1307      IRType = CGT.ConvertTypeRecursive(RetTy);
1308
1309    const llvm::Type *HiType =  Get8ByteTypeAtOffset(IRType, 8, RetTy, 8);
1310    ResType = llvm::StructType::get(getVMContext(), ResType, HiType, NULL);
1311    break;
1312  }
1313  case SSE:
1314    ResType = llvm::StructType::get(getVMContext(), ResType,
1315                                    llvm::Type::getDoubleTy(getVMContext()),
1316                                    NULL);
1317    break;
1318
1319    // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1320    // is passed in the upper half of the last used SSE register.
1321    //
1322    // SSEUP should always be preceeded by SSE, just widen.
1323  case SSEUp:
1324    assert(Lo == SSE && "Unexpected SSEUp classification.");
1325    ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1326    break;
1327
1328    // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1329    // returned together with the previous X87 value in %st0.
1330  case X87Up:
1331    // If X87Up is preceeded by X87, we don't need to do
1332    // anything. However, in some cases with unions it may not be
1333    // preceeded by X87. In such situations we follow gcc and pass the
1334    // extra bits in an SSE reg.
1335    if (Lo != X87)
1336      ResType = llvm::StructType::get(getVMContext(), ResType,
1337                                      llvm::Type::getDoubleTy(getVMContext()),
1338                                      NULL);
1339    break;
1340  }
1341
1342  return getCoerceResult(RetTy, ResType);
1343}
1344
1345ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &neededInt,
1346                                               unsigned &neededSSE) const {
1347  X86_64ABIInfo::Class Lo, Hi;
1348  classify(Ty, 0, Lo, Hi);
1349
1350
1351  // Determine the preferred IR type to use and pass it down to
1352  // classifyArgumentType.
1353  const llvm::Type *IRType = 0;
1354
1355  // Check some invariants.
1356  // FIXME: Enforce these by construction.
1357  assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1358  assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
1359  assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1360
1361  neededInt = 0;
1362  neededSSE = 0;
1363  const llvm::Type *ResType = 0;
1364  switch (Lo) {
1365  case NoClass:
1366    return ABIArgInfo::getIgnore();
1367
1368    // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1369    // on the stack.
1370  case Memory:
1371
1372    // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1373    // COMPLEX_X87, it is passed in memory.
1374  case X87:
1375  case ComplexX87:
1376    return getIndirectResult(Ty);
1377
1378  case SSEUp:
1379  case X87Up:
1380    assert(0 && "Invalid classification for lo word.");
1381
1382    // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1383    // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1384    // and %r9 is used.
1385  case Integer:
1386    ++neededInt;
1387
1388    if (IRType == 0)
1389      IRType = CGT.ConvertTypeRecursive(Ty);
1390
1391    // Pick an 8-byte type based on the preferred type.
1392    ResType = Get8ByteTypeAtOffset(IRType, 0, Ty, 0);
1393    break;
1394
1395    // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1396    // available SSE register is used, the registers are taken in the
1397    // order from %xmm0 to %xmm7.
1398  case SSE:
1399    ++neededSSE;
1400    ResType = llvm::Type::getDoubleTy(getVMContext());
1401    break;
1402  }
1403
1404  switch (Hi) {
1405    // Memory was handled previously, ComplexX87 and X87 should
1406    // never occur as hi classes, and X87Up must be preceed by X87,
1407    // which is passed in memory.
1408  case Memory:
1409  case X87:
1410  case ComplexX87:
1411    assert(0 && "Invalid classification for hi word.");
1412    break;
1413
1414  case NoClass: break;
1415
1416  case Integer: {
1417    ++neededInt;
1418
1419    if (IRType == 0)
1420      IRType = CGT.ConvertTypeRecursive(Ty);
1421
1422    // Pick an 8-byte type based on the preferred type.
1423    const llvm::Type *HiType = Get8ByteTypeAtOffset(IRType, 8, Ty, 8);
1424    ResType = llvm::StructType::get(getVMContext(), ResType, HiType, NULL);
1425    break;
1426  }
1427
1428    // X87Up generally doesn't occur here (long double is passed in
1429    // memory), except in situations involving unions.
1430  case X87Up:
1431  case SSE:
1432    ResType = llvm::StructType::get(getVMContext(), ResType,
1433                                    llvm::Type::getDoubleTy(getVMContext()),
1434                                    NULL);
1435    ++neededSSE;
1436    break;
1437
1438    // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1439    // eightbyte is passed in the upper half of the last used SSE
1440    // register.  This only happens when 128-bit vectors are passed.
1441  case SSEUp:
1442    assert(Lo == SSE && "Unexpected SSEUp classification");
1443    ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1444
1445    if (IRType == 0)
1446      IRType = CGT.ConvertTypeRecursive(Ty);
1447
1448    // If the preferred type is a 16-byte vector, prefer to pass it.
1449    if (const llvm::VectorType *VT =dyn_cast_or_null<llvm::VectorType>(IRType)){
1450      const llvm::Type *EltTy = VT->getElementType();
1451      if (VT->getBitWidth() == 128 &&
1452          (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1453           EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1454           EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1455           EltTy->isIntegerTy(128)))
1456        ResType = IRType;
1457    }
1458    break;
1459  }
1460
1461  return getCoerceResult(Ty, ResType);
1462}
1463
1464void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1465
1466  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1467
1468  // Keep track of the number of assigned registers.
1469  unsigned freeIntRegs = 6, freeSSERegs = 8;
1470
1471  // If the return value is indirect, then the hidden argument is consuming one
1472  // integer register.
1473  if (FI.getReturnInfo().isIndirect())
1474    --freeIntRegs;
1475
1476  // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1477  // get assigned (in left-to-right order) for passing as follows...
1478  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1479       it != ie; ++it) {
1480    unsigned neededInt, neededSSE;
1481    it->info = classifyArgumentType(it->type, neededInt, neededSSE);
1482
1483    // AMD64-ABI 3.2.3p3: If there are no registers available for any
1484    // eightbyte of an argument, the whole argument is passed on the
1485    // stack. If registers have already been assigned for some
1486    // eightbytes of such an argument, the assignments get reverted.
1487    if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1488      freeIntRegs -= neededInt;
1489      freeSSERegs -= neededSSE;
1490    } else {
1491      it->info = getIndirectResult(it->type);
1492    }
1493  }
1494}
1495
1496static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1497                                        QualType Ty,
1498                                        CodeGenFunction &CGF) {
1499  llvm::Value *overflow_arg_area_p =
1500    CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1501  llvm::Value *overflow_arg_area =
1502    CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1503
1504  // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1505  // byte boundary if alignment needed by type exceeds 8 byte boundary.
1506  uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1507  if (Align > 8) {
1508    // Note that we follow the ABI & gcc here, even though the type
1509    // could in theory have an alignment greater than 16. This case
1510    // shouldn't ever matter in practice.
1511
1512    // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1513    llvm::Value *Offset =
1514      llvm::ConstantInt::get(CGF.Int32Ty, 15);
1515    overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1516    llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1517                                                    CGF.Int64Ty);
1518    llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~15LL);
1519    overflow_arg_area =
1520      CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1521                                 overflow_arg_area->getType(),
1522                                 "overflow_arg_area.align");
1523  }
1524
1525  // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1526  const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1527  llvm::Value *Res =
1528    CGF.Builder.CreateBitCast(overflow_arg_area,
1529                              llvm::PointerType::getUnqual(LTy));
1530
1531  // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1532  // l->overflow_arg_area + sizeof(type).
1533  // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1534  // an 8 byte boundary.
1535
1536  uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1537  llvm::Value *Offset =
1538      llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
1539  overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1540                                            "overflow_arg_area.next");
1541  CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1542
1543  // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1544  return Res;
1545}
1546
1547llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1548                                      CodeGenFunction &CGF) const {
1549  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1550
1551  // Assume that va_list type is correct; should be pointer to LLVM type:
1552  // struct {
1553  //   i32 gp_offset;
1554  //   i32 fp_offset;
1555  //   i8* overflow_arg_area;
1556  //   i8* reg_save_area;
1557  // };
1558  unsigned neededInt, neededSSE;
1559
1560  Ty = CGF.getContext().getCanonicalType(Ty);
1561  ABIArgInfo AI = classifyArgumentType(Ty, neededInt, neededSSE);
1562
1563  // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1564  // in the registers. If not go to step 7.
1565  if (!neededInt && !neededSSE)
1566    return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1567
1568  // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1569  // general purpose registers needed to pass type and num_fp to hold
1570  // the number of floating point registers needed.
1571
1572  // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1573  // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1574  // l->fp_offset > 304 - num_fp * 16 go to step 7.
1575  //
1576  // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1577  // register save space).
1578
1579  llvm::Value *InRegs = 0;
1580  llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1581  llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1582  if (neededInt) {
1583    gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1584    gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1585    InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
1586    InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
1587  }
1588
1589  if (neededSSE) {
1590    fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1591    fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1592    llvm::Value *FitsInFP =
1593      llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
1594    FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
1595    InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1596  }
1597
1598  llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1599  llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1600  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1601  CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1602
1603  // Emit code to load the value if it was passed in registers.
1604
1605  CGF.EmitBlock(InRegBlock);
1606
1607  // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1608  // an offset of l->gp_offset and/or l->fp_offset. This may require
1609  // copying to a temporary location in case the parameter is passed
1610  // in different register classes or requires an alignment greater
1611  // than 8 for general purpose registers and 16 for XMM registers.
1612  //
1613  // FIXME: This really results in shameful code when we end up needing to
1614  // collect arguments from different places; often what should result in a
1615  // simple assembling of a structure from scattered addresses has many more
1616  // loads than necessary. Can we clean this up?
1617  const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1618  llvm::Value *RegAddr =
1619    CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1620                           "reg_save_area");
1621  if (neededInt && neededSSE) {
1622    // FIXME: Cleanup.
1623    assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1624    const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1625    llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1626    assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1627    const llvm::Type *TyLo = ST->getElementType(0);
1628    const llvm::Type *TyHi = ST->getElementType(1);
1629    assert((TyLo->isFloatingPointTy() ^ TyHi->isFloatingPointTy()) &&
1630           "Unexpected ABI info for mixed regs");
1631    const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1632    const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1633    llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1634    llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1635    llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
1636    llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
1637    llvm::Value *V =
1638      CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1639    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1640    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1641    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1642
1643    RegAddr = CGF.Builder.CreateBitCast(Tmp,
1644                                        llvm::PointerType::getUnqual(LTy));
1645  } else if (neededInt) {
1646    RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1647    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1648                                        llvm::PointerType::getUnqual(LTy));
1649  } else if (neededSSE == 1) {
1650    RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1651    RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1652                                        llvm::PointerType::getUnqual(LTy));
1653  } else {
1654    assert(neededSSE == 2 && "Invalid number of needed registers!");
1655    // SSE registers are spaced 16 bytes apart in the register save
1656    // area, we need to collect the two eightbytes together.
1657    llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1658    llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
1659    const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
1660    const llvm::Type *DblPtrTy =
1661      llvm::PointerType::getUnqual(DoubleTy);
1662    const llvm::StructType *ST = llvm::StructType::get(VMContext, DoubleTy,
1663                                                       DoubleTy, NULL);
1664    llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1665    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1666                                                         DblPtrTy));
1667    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1668    V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1669                                                         DblPtrTy));
1670    CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1671    RegAddr = CGF.Builder.CreateBitCast(Tmp,
1672                                        llvm::PointerType::getUnqual(LTy));
1673  }
1674
1675  // AMD64-ABI 3.5.7p5: Step 5. Set:
1676  // l->gp_offset = l->gp_offset + num_gp * 8
1677  // l->fp_offset = l->fp_offset + num_fp * 16.
1678  if (neededInt) {
1679    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
1680    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1681                            gp_offset_p);
1682  }
1683  if (neededSSE) {
1684    llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
1685    CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1686                            fp_offset_p);
1687  }
1688  CGF.EmitBranch(ContBlock);
1689
1690  // Emit code to load the value if it was passed in memory.
1691
1692  CGF.EmitBlock(InMemBlock);
1693  llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1694
1695  // Return the appropriate result.
1696
1697  CGF.EmitBlock(ContBlock);
1698  llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1699                                                 "vaarg.addr");
1700  ResAddr->reserveOperandSpace(2);
1701  ResAddr->addIncoming(RegAddr, InRegBlock);
1702  ResAddr->addIncoming(MemAddr, InMemBlock);
1703  return ResAddr;
1704}
1705
1706
1707
1708//===----------------------------------------------------------------------===//
1709// PIC16 ABI Implementation
1710//===----------------------------------------------------------------------===//
1711
1712namespace {
1713
1714class PIC16ABIInfo : public ABIInfo {
1715public:
1716  PIC16ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
1717
1718  ABIArgInfo classifyReturnType(QualType RetTy) const;
1719
1720  ABIArgInfo classifyArgumentType(QualType RetTy) const;
1721
1722  virtual void computeInfo(CGFunctionInfo &FI) const {
1723    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1724    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1725         it != ie; ++it)
1726      it->info = classifyArgumentType(it->type);
1727  }
1728
1729  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1730                                 CodeGenFunction &CGF) const;
1731};
1732
1733class PIC16TargetCodeGenInfo : public TargetCodeGenInfo {
1734public:
1735  PIC16TargetCodeGenInfo(CodeGenTypes &CGT)
1736    : TargetCodeGenInfo(new PIC16ABIInfo(CGT)) {}
1737};
1738
1739}
1740
1741ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy) const {
1742  if (RetTy->isVoidType()) {
1743    return ABIArgInfo::getIgnore();
1744  } else {
1745    return ABIArgInfo::getDirect();
1746  }
1747}
1748
1749ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty) const {
1750  return ABIArgInfo::getDirect();
1751}
1752
1753llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1754                                     CodeGenFunction &CGF) const {
1755  const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1756  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1757
1758  CGBuilderTy &Builder = CGF.Builder;
1759  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1760                                                       "ap");
1761  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1762  llvm::Type *PTy =
1763    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1764  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1765
1766  uint64_t Offset = CGF.getContext().getTypeSize(Ty) / 8;
1767
1768  llvm::Value *NextAddr =
1769    Builder.CreateGEP(Addr, llvm::ConstantInt::get(
1770                          llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
1771                      "ap.next");
1772  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1773
1774  return AddrTyped;
1775}
1776
1777
1778// PowerPC-32
1779
1780namespace {
1781class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
1782public:
1783  PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
1784
1785  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
1786    // This is recovered from gcc output.
1787    return 1; // r1 is the dedicated stack pointer
1788  }
1789
1790  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1791                               llvm::Value *Address) const;
1792};
1793
1794}
1795
1796bool
1797PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1798                                                llvm::Value *Address) const {
1799  // This is calculated from the LLVM and GCC tables and verified
1800  // against gcc output.  AFAIK all ABIs use the same encoding.
1801
1802  CodeGen::CGBuilderTy &Builder = CGF.Builder;
1803  llvm::LLVMContext &Context = CGF.getLLVMContext();
1804
1805  const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
1806  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
1807  llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
1808  llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
1809
1810  // 0-31: r0-31, the 4-byte general-purpose registers
1811  AssignToArrayRange(Builder, Address, Four8, 0, 31);
1812
1813  // 32-63: fp0-31, the 8-byte floating-point registers
1814  AssignToArrayRange(Builder, Address, Eight8, 32, 63);
1815
1816  // 64-76 are various 4-byte special-purpose registers:
1817  // 64: mq
1818  // 65: lr
1819  // 66: ctr
1820  // 67: ap
1821  // 68-75 cr0-7
1822  // 76: xer
1823  AssignToArrayRange(Builder, Address, Four8, 64, 76);
1824
1825  // 77-108: v0-31, the 16-byte vector registers
1826  AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
1827
1828  // 109: vrsave
1829  // 110: vscr
1830  // 111: spe_acc
1831  // 112: spefscr
1832  // 113: sfp
1833  AssignToArrayRange(Builder, Address, Four8, 109, 113);
1834
1835  return false;
1836}
1837
1838
1839//===----------------------------------------------------------------------===//
1840// ARM ABI Implementation
1841//===----------------------------------------------------------------------===//
1842
1843namespace {
1844
1845class ARMABIInfo : public ABIInfo {
1846public:
1847  enum ABIKind {
1848    APCS = 0,
1849    AAPCS = 1,
1850    AAPCS_VFP
1851  };
1852
1853private:
1854  ABIKind Kind;
1855
1856public:
1857  ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
1858
1859private:
1860  ABIKind getABIKind() const { return Kind; }
1861
1862  ABIArgInfo classifyReturnType(QualType RetTy) const;
1863  ABIArgInfo classifyArgumentType(QualType RetTy) const;
1864
1865  virtual void computeInfo(CGFunctionInfo &FI) const;
1866
1867  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1868                                 CodeGenFunction &CGF) const;
1869};
1870
1871class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
1872public:
1873  ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
1874    :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
1875
1876  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
1877    return 13;
1878  }
1879};
1880
1881}
1882
1883void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
1884  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1885  for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1886       it != ie; ++it)
1887    it->info = classifyArgumentType(it->type);
1888
1889  const llvm::Triple &Triple(getContext().Target.getTriple());
1890  llvm::CallingConv::ID DefaultCC;
1891  if (Triple.getEnvironmentName() == "gnueabi" ||
1892      Triple.getEnvironmentName() == "eabi")
1893    DefaultCC = llvm::CallingConv::ARM_AAPCS;
1894  else
1895    DefaultCC = llvm::CallingConv::ARM_APCS;
1896
1897  switch (getABIKind()) {
1898  case APCS:
1899    if (DefaultCC != llvm::CallingConv::ARM_APCS)
1900      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
1901    break;
1902
1903  case AAPCS:
1904    if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
1905      FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
1906    break;
1907
1908  case AAPCS_VFP:
1909    FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
1910    break;
1911  }
1912}
1913
1914ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
1915  if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1916    // Treat an enum type as its underlying type.
1917    if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1918      Ty = EnumTy->getDecl()->getIntegerType();
1919
1920    return (Ty->isPromotableIntegerType() ?
1921            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1922  }
1923
1924  // Ignore empty records.
1925  if (isEmptyRecord(getContext(), Ty, true))
1926    return ABIArgInfo::getIgnore();
1927
1928  // Structures with either a non-trivial destructor or a non-trivial
1929  // copy constructor are always indirect.
1930  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1931    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1932
1933  // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1934  // backend doesn't support byval.
1935  // FIXME: This doesn't handle alignment > 64 bits.
1936  const llvm::Type* ElemTy;
1937  unsigned SizeRegs;
1938  if (getContext().getTypeAlign(Ty) > 32) {
1939    ElemTy = llvm::Type::getInt64Ty(getVMContext());
1940    SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
1941  } else {
1942    ElemTy = llvm::Type::getInt32Ty(getVMContext());
1943    SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1944  }
1945  std::vector<const llvm::Type*> LLVMFields;
1946  LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1947  const llvm::Type* STy = llvm::StructType::get(getVMContext(), LLVMFields,
1948                                                true);
1949  return ABIArgInfo::getCoerce(STy);
1950}
1951
1952static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
1953                              llvm::LLVMContext &VMContext) {
1954  // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
1955  // is called integer-like if its size is less than or equal to one word, and
1956  // the offset of each of its addressable sub-fields is zero.
1957
1958  uint64_t Size = Context.getTypeSize(Ty);
1959
1960  // Check that the type fits in a word.
1961  if (Size > 32)
1962    return false;
1963
1964  // FIXME: Handle vector types!
1965  if (Ty->isVectorType())
1966    return false;
1967
1968  // Float types are never treated as "integer like".
1969  if (Ty->isRealFloatingType())
1970    return false;
1971
1972  // If this is a builtin or pointer type then it is ok.
1973  if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
1974    return true;
1975
1976  // Small complex integer types are "integer like".
1977  if (const ComplexType *CT = Ty->getAs<ComplexType>())
1978    return isIntegerLikeType(CT->getElementType(), Context, VMContext);
1979
1980  // Single element and zero sized arrays should be allowed, by the definition
1981  // above, but they are not.
1982
1983  // Otherwise, it must be a record type.
1984  const RecordType *RT = Ty->getAs<RecordType>();
1985  if (!RT) return false;
1986
1987  // Ignore records with flexible arrays.
1988  const RecordDecl *RD = RT->getDecl();
1989  if (RD->hasFlexibleArrayMember())
1990    return false;
1991
1992  // Check that all sub-fields are at offset 0, and are themselves "integer
1993  // like".
1994  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1995
1996  bool HadField = false;
1997  unsigned idx = 0;
1998  for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1999       i != e; ++i, ++idx) {
2000    const FieldDecl *FD = *i;
2001
2002    // Bit-fields are not addressable, we only need to verify they are "integer
2003    // like". We still have to disallow a subsequent non-bitfield, for example:
2004    //   struct { int : 0; int x }
2005    // is non-integer like according to gcc.
2006    if (FD->isBitField()) {
2007      if (!RD->isUnion())
2008        HadField = true;
2009
2010      if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2011        return false;
2012
2013      continue;
2014    }
2015
2016    // Check if this field is at offset 0.
2017    if (Layout.getFieldOffset(idx) != 0)
2018      return false;
2019
2020    if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2021      return false;
2022
2023    // Only allow at most one field in a structure. This doesn't match the
2024    // wording above, but follows gcc in situations with a field following an
2025    // empty structure.
2026    if (!RD->isUnion()) {
2027      if (HadField)
2028        return false;
2029
2030      HadField = true;
2031    }
2032  }
2033
2034  return true;
2035}
2036
2037ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
2038  if (RetTy->isVoidType())
2039    return ABIArgInfo::getIgnore();
2040
2041  if (!CodeGenFunction::hasAggregateLLVMType(RetTy)) {
2042    // Treat an enum type as its underlying type.
2043    if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2044      RetTy = EnumTy->getDecl()->getIntegerType();
2045
2046    return (RetTy->isPromotableIntegerType() ?
2047            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2048  }
2049
2050  // Structures with either a non-trivial destructor or a non-trivial
2051  // copy constructor are always indirect.
2052  if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
2053    return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2054
2055  // Are we following APCS?
2056  if (getABIKind() == APCS) {
2057    if (isEmptyRecord(getContext(), RetTy, false))
2058      return ABIArgInfo::getIgnore();
2059
2060    // Complex types are all returned as packed integers.
2061    //
2062    // FIXME: Consider using 2 x vector types if the back end handles them
2063    // correctly.
2064    if (RetTy->isAnyComplexType())
2065      return ABIArgInfo::getCoerce(llvm::IntegerType::get(getVMContext(),
2066                                              getContext().getTypeSize(RetTy)));
2067
2068    // Integer like structures are returned in r0.
2069    if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
2070      // Return in the smallest viable integer type.
2071      uint64_t Size = getContext().getTypeSize(RetTy);
2072      if (Size <= 8)
2073        return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(getVMContext()));
2074      if (Size <= 16)
2075        return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(getVMContext()));
2076      return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(getVMContext()));
2077    }
2078
2079    // Otherwise return in memory.
2080    return ABIArgInfo::getIndirect(0);
2081  }
2082
2083  // Otherwise this is an AAPCS variant.
2084
2085  if (isEmptyRecord(getContext(), RetTy, true))
2086    return ABIArgInfo::getIgnore();
2087
2088  // Aggregates <= 4 bytes are returned in r0; other aggregates
2089  // are returned indirectly.
2090  uint64_t Size = getContext().getTypeSize(RetTy);
2091  if (Size <= 32) {
2092    // Return in the smallest viable integer type.
2093    if (Size <= 8)
2094      return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(getVMContext()));
2095    if (Size <= 16)
2096      return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(getVMContext()));
2097    return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(getVMContext()));
2098  }
2099
2100  return ABIArgInfo::getIndirect(0);
2101}
2102
2103llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2104                                   CodeGenFunction &CGF) const {
2105  // FIXME: Need to handle alignment
2106  const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2107  const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2108
2109  CGBuilderTy &Builder = CGF.Builder;
2110  llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2111                                                       "ap");
2112  llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2113  llvm::Type *PTy =
2114    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2115  llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2116
2117  uint64_t Offset =
2118    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
2119  llvm::Value *NextAddr =
2120    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2121                      "ap.next");
2122  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2123
2124  return AddrTyped;
2125}
2126
2127ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
2128  if (RetTy->isVoidType())
2129    return ABIArgInfo::getIgnore();
2130
2131  if (CodeGenFunction::hasAggregateLLVMType(RetTy))
2132    return ABIArgInfo::getIndirect(0);
2133
2134  // Treat an enum type as its underlying type.
2135  if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2136    RetTy = EnumTy->getDecl()->getIntegerType();
2137
2138  return (RetTy->isPromotableIntegerType() ?
2139          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2140}
2141
2142//===----------------------------------------------------------------------===//
2143// SystemZ ABI Implementation
2144//===----------------------------------------------------------------------===//
2145
2146namespace {
2147
2148class SystemZABIInfo : public ABIInfo {
2149public:
2150  SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2151
2152  bool isPromotableIntegerType(QualType Ty) const;
2153
2154  ABIArgInfo classifyReturnType(QualType RetTy) const;
2155  ABIArgInfo classifyArgumentType(QualType RetTy) const;
2156
2157  virtual void computeInfo(CGFunctionInfo &FI) const {
2158    FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2159    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2160         it != ie; ++it)
2161      it->info = classifyArgumentType(it->type);
2162  }
2163
2164  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2165                                 CodeGenFunction &CGF) const;
2166};
2167
2168class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
2169public:
2170  SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
2171    : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
2172};
2173
2174}
2175
2176bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
2177  // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
2178  if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2179    switch (BT->getKind()) {
2180    case BuiltinType::Bool:
2181    case BuiltinType::Char_S:
2182    case BuiltinType::Char_U:
2183    case BuiltinType::SChar:
2184    case BuiltinType::UChar:
2185    case BuiltinType::Short:
2186    case BuiltinType::UShort:
2187    case BuiltinType::Int:
2188    case BuiltinType::UInt:
2189      return true;
2190    default:
2191      return false;
2192    }
2193  return false;
2194}
2195
2196llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2197                                       CodeGenFunction &CGF) const {
2198  // FIXME: Implement
2199  return 0;
2200}
2201
2202
2203ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
2204  if (RetTy->isVoidType())
2205    return ABIArgInfo::getIgnore();
2206  if (CodeGenFunction::hasAggregateLLVMType(RetTy))
2207    return ABIArgInfo::getIndirect(0);
2208
2209  return (isPromotableIntegerType(RetTy) ?
2210          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2211}
2212
2213ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
2214  if (CodeGenFunction::hasAggregateLLVMType(Ty))
2215    return ABIArgInfo::getIndirect(0);
2216
2217  return (isPromotableIntegerType(Ty) ?
2218          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2219}
2220
2221//===----------------------------------------------------------------------===//
2222// MSP430 ABI Implementation
2223//===----------------------------------------------------------------------===//
2224
2225namespace {
2226
2227class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
2228public:
2229  MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
2230    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
2231  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2232                           CodeGen::CodeGenModule &M) const;
2233};
2234
2235}
2236
2237void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2238                                                  llvm::GlobalValue *GV,
2239                                             CodeGen::CodeGenModule &M) const {
2240  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2241    if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
2242      // Handle 'interrupt' attribute:
2243      llvm::Function *F = cast<llvm::Function>(GV);
2244
2245      // Step 1: Set ISR calling convention.
2246      F->setCallingConv(llvm::CallingConv::MSP430_INTR);
2247
2248      // Step 2: Add attributes goodness.
2249      F->addFnAttr(llvm::Attribute::NoInline);
2250
2251      // Step 3: Emit ISR vector alias.
2252      unsigned Num = attr->getNumber() + 0xffe0;
2253      new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
2254                            "vector_" +
2255                            llvm::LowercaseString(llvm::utohexstr(Num)),
2256                            GV, &M.getModule());
2257    }
2258  }
2259}
2260
2261//===----------------------------------------------------------------------===//
2262// MIPS ABI Implementation.  This works for both little-endian and
2263// big-endian variants.
2264//===----------------------------------------------------------------------===//
2265
2266namespace {
2267class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
2268public:
2269  MIPSTargetCodeGenInfo(CodeGenTypes &CGT)
2270    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
2271
2272  int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
2273    return 29;
2274  }
2275
2276  bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2277                               llvm::Value *Address) const;
2278};
2279}
2280
2281bool
2282MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2283                                               llvm::Value *Address) const {
2284  // This information comes from gcc's implementation, which seems to
2285  // as canonical as it gets.
2286
2287  CodeGen::CGBuilderTy &Builder = CGF.Builder;
2288  llvm::LLVMContext &Context = CGF.getLLVMContext();
2289
2290  // Everything on MIPS is 4 bytes.  Double-precision FP registers
2291  // are aliased to pairs of single-precision FP registers.
2292  const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2293  llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2294
2295  // 0-31 are the general purpose registers, $0 - $31.
2296  // 32-63 are the floating-point registers, $f0 - $f31.
2297  // 64 and 65 are the multiply/divide registers, $hi and $lo.
2298  // 66 is the (notional, I think) register for signal-handler return.
2299  AssignToArrayRange(Builder, Address, Four8, 0, 65);
2300
2301  // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
2302  // They are one bit wide and ignored here.
2303
2304  // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
2305  // (coprocessor 1 is the FP unit)
2306  // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
2307  // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
2308  // 176-181 are the DSP accumulator registers.
2309  AssignToArrayRange(Builder, Address, Four8, 80, 181);
2310
2311  return false;
2312}
2313
2314
2315const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
2316  if (TheTargetCodeGenInfo)
2317    return *TheTargetCodeGenInfo;
2318
2319  // For now we just cache the TargetCodeGenInfo in CodeGenModule and don't
2320  // free it.
2321
2322  const llvm::Triple &Triple = getContext().Target.getTriple();
2323  switch (Triple.getArch()) {
2324  default:
2325    return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
2326
2327  case llvm::Triple::mips:
2328  case llvm::Triple::mipsel:
2329    return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types));
2330
2331  case llvm::Triple::arm:
2332  case llvm::Triple::thumb:
2333    // FIXME: We want to know the float calling convention as well.
2334    if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
2335      return *(TheTargetCodeGenInfo =
2336               new ARMTargetCodeGenInfo(Types, ARMABIInfo::APCS));
2337
2338    return *(TheTargetCodeGenInfo =
2339             new ARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS));
2340
2341  case llvm::Triple::pic16:
2342    return *(TheTargetCodeGenInfo = new PIC16TargetCodeGenInfo(Types));
2343
2344  case llvm::Triple::ppc:
2345    return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
2346
2347  case llvm::Triple::systemz:
2348    return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
2349
2350  case llvm::Triple::msp430:
2351    return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
2352
2353  case llvm::Triple::x86:
2354    switch (Triple.getOS()) {
2355    case llvm::Triple::Darwin:
2356      return *(TheTargetCodeGenInfo =
2357               new X86_32TargetCodeGenInfo(Types, true, true));
2358    case llvm::Triple::Cygwin:
2359    case llvm::Triple::MinGW32:
2360    case llvm::Triple::MinGW64:
2361    case llvm::Triple::AuroraUX:
2362    case llvm::Triple::DragonFly:
2363    case llvm::Triple::FreeBSD:
2364    case llvm::Triple::OpenBSD:
2365      return *(TheTargetCodeGenInfo =
2366               new X86_32TargetCodeGenInfo(Types, false, true));
2367
2368    default:
2369      return *(TheTargetCodeGenInfo =
2370               new X86_32TargetCodeGenInfo(Types, false, false));
2371    }
2372
2373  case llvm::Triple::x86_64:
2374    return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));
2375  }
2376}
2377