]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/TargetABIInfo.cpp
Update clang to r86025.
[FreeBSD/FreeBSD.git] / lib / CodeGen / TargetABIInfo.cpp
1 //===---- TargetABIInfo.cpp - Encapsulate target ABI 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 "ABIInfo.h"
16 #include "CodeGenFunction.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "llvm/Type.h"
19 #include "llvm/ADT/Triple.h"
20 #include <cstdio>
21
22 using namespace clang;
23 using namespace CodeGen;
24
25 ABIInfo::~ABIInfo() {}
26
27 void ABIArgInfo::dump() const {
28   fprintf(stderr, "(ABIArgInfo Kind=");
29   switch (TheKind) {
30   case Direct:
31     fprintf(stderr, "Direct");
32     break;
33   case Extend:
34     fprintf(stderr, "Extend");
35     break;
36   case Ignore:
37     fprintf(stderr, "Ignore");
38     break;
39   case Coerce:
40     fprintf(stderr, "Coerce Type=");
41     getCoerceToType()->print(llvm::errs());
42     break;
43   case Indirect:
44     fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
45     break;
46   case Expand:
47     fprintf(stderr, "Expand");
48     break;
49   }
50   fprintf(stderr, ")\n");
51 }
52
53 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
54
55 /// isEmptyField - Return true iff a the field is "empty", that is it
56 /// is an unnamed bit-field or an (array of) empty record(s).
57 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
58                          bool AllowArrays) {
59   if (FD->isUnnamedBitfield())
60     return true;
61
62   QualType FT = FD->getType();
63
64     // Constant arrays of empty records count as empty, strip them off.
65   if (AllowArrays)
66     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
67       FT = AT->getElementType();
68
69   return isEmptyRecord(Context, FT, AllowArrays);
70 }
71
72 /// isEmptyRecord - Return true iff a structure contains only empty
73 /// fields. Note that a structure with a flexible array member is not
74 /// considered empty.
75 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
76   const RecordType *RT = T->getAs<RecordType>();
77   if (!RT)
78     return 0;
79   const RecordDecl *RD = RT->getDecl();
80   if (RD->hasFlexibleArrayMember())
81     return false;
82   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
83          i != e; ++i)
84     if (!isEmptyField(Context, *i, AllowArrays))
85       return false;
86   return true;
87 }
88
89 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
90 /// a non-trivial destructor or a non-trivial copy constructor.
91 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
92   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
93   if (!RD)
94     return false;
95   
96   return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
97 }
98
99 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
100 /// a record type with either a non-trivial destructor or a non-trivial copy
101 /// constructor.
102 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
103   const RecordType *RT = T->getAs<RecordType>();
104   if (!RT)
105     return false;
106
107   return hasNonTrivialDestructorOrCopyConstructor(RT);
108 }
109
110 /// isSingleElementStruct - Determine if a structure is a "single
111 /// element struct", i.e. it has exactly one non-empty field or
112 /// exactly one field which is itself a single element
113 /// struct. Structures with flexible array members are never
114 /// considered single element structs.
115 ///
116 /// \return The field declaration for the single non-empty field, if
117 /// it exists.
118 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
119   const RecordType *RT = T->getAsStructureType();
120   if (!RT)
121     return 0;
122
123   const RecordDecl *RD = RT->getDecl();
124   if (RD->hasFlexibleArrayMember())
125     return 0;
126
127   const Type *Found = 0;
128   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
129          i != e; ++i) {
130     const FieldDecl *FD = *i;
131     QualType FT = FD->getType();
132
133     // Ignore empty fields.
134     if (isEmptyField(Context, FD, true))
135       continue;
136
137     // If we already found an element then this isn't a single-element
138     // struct.
139     if (Found)
140       return 0;
141
142     // Treat single element arrays as the element.
143     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
144       if (AT->getSize().getZExtValue() != 1)
145         break;
146       FT = AT->getElementType();
147     }
148
149     if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
150       Found = FT.getTypePtr();
151     } else {
152       Found = isSingleElementStruct(FT, Context);
153       if (!Found)
154         return 0;
155     }
156   }
157
158   return Found;
159 }
160
161 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
162   if (!Ty->getAs<BuiltinType>() && !Ty->isAnyPointerType() &&
163       !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
164       !Ty->isBlockPointerType())
165     return false;
166
167   uint64_t Size = Context.getTypeSize(Ty);
168   return Size == 32 || Size == 64;
169 }
170
171 static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
172                                            ASTContext &Context) {
173   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
174          i != e; ++i) {
175     const FieldDecl *FD = *i;
176
177     if (!is32Or64BitBasicType(FD->getType(), Context))
178       return false;
179
180     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
181     // how to expand them yet, and the predicate for telling if a bitfield still
182     // counts as "basic" is more complicated than what we were doing previously.
183     if (FD->isBitField())
184       return false;
185   }
186
187   return true;
188 }
189
190 static bool typeContainsSSEVector(const RecordDecl *RD, ASTContext &Context) {
191   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
192          i != e; ++i) {
193     const FieldDecl *FD = *i;
194
195     if (FD->getType()->isVectorType() &&
196         Context.getTypeSize(FD->getType()) >= 128)
197       return true;
198
199     if (const RecordType* RT = FD->getType()->getAs<RecordType>())
200       if (typeContainsSSEVector(RT->getDecl(), Context))
201         return true;
202   }
203
204   return false;
205 }
206
207 namespace {
208 /// DefaultABIInfo - The default implementation for ABI specific
209 /// details. This implementation provides information which results in
210 /// self-consistent and sensible LLVM IR generation, but does not
211 /// conform to any particular ABI.
212 class DefaultABIInfo : public ABIInfo {
213   ABIArgInfo classifyReturnType(QualType RetTy,
214                                 ASTContext &Context,
215                                 llvm::LLVMContext &VMContext) const;
216
217   ABIArgInfo classifyArgumentType(QualType RetTy,
218                                   ASTContext &Context,
219                                   llvm::LLVMContext &VMContext) const;
220
221   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
222                            llvm::LLVMContext &VMContext) const {
223     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
224                                             VMContext);
225     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
226          it != ie; ++it)
227       it->info = classifyArgumentType(it->type, Context, VMContext);
228   }
229
230   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
231                                  CodeGenFunction &CGF) const;
232 };
233
234 /// X86_32ABIInfo - The X86-32 ABI information.
235 class X86_32ABIInfo : public ABIInfo {
236   ASTContext &Context;
237   bool IsDarwinVectorABI;
238   bool IsSmallStructInRegABI;
239
240   static bool isRegisterSize(unsigned Size) {
241     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
242   }
243
244   static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
245
246   static unsigned getIndirectArgumentAlignment(QualType Ty,
247                                                ASTContext &Context);
248
249 public:
250   ABIArgInfo classifyReturnType(QualType RetTy,
251                                 ASTContext &Context,
252                                 llvm::LLVMContext &VMContext) const;
253
254   ABIArgInfo classifyArgumentType(QualType RetTy,
255                                   ASTContext &Context,
256                                   llvm::LLVMContext &VMContext) const;
257
258   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
259                            llvm::LLVMContext &VMContext) const {
260     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
261                                             VMContext);
262     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
263          it != ie; ++it)
264       it->info = classifyArgumentType(it->type, Context, VMContext);
265   }
266
267   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
268                                  CodeGenFunction &CGF) const;
269
270   X86_32ABIInfo(ASTContext &Context, bool d, bool p)
271     : ABIInfo(), Context(Context), IsDarwinVectorABI(d),
272       IsSmallStructInRegABI(p) {}
273 };
274 }
275
276
277 /// shouldReturnTypeInRegister - Determine if the given type should be
278 /// passed in a register (for the Darwin ABI).
279 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
280                                                ASTContext &Context) {
281   uint64_t Size = Context.getTypeSize(Ty);
282
283   // Type must be register sized.
284   if (!isRegisterSize(Size))
285     return false;
286
287   if (Ty->isVectorType()) {
288     // 64- and 128- bit vectors inside structures are not returned in
289     // registers.
290     if (Size == 64 || Size == 128)
291       return false;
292
293     return true;
294   }
295
296   // If this is a builtin, pointer, enum, or complex type, it is ok.
297   if (Ty->getAs<BuiltinType>() || Ty->isAnyPointerType() || 
298       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
299       Ty->isBlockPointerType())
300     return true;
301
302   // Arrays are treated like records.
303   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
304     return shouldReturnTypeInRegister(AT->getElementType(), Context);
305
306   // Otherwise, it must be a record type.
307   const RecordType *RT = Ty->getAs<RecordType>();
308   if (!RT) return false;
309
310   // Structure types are passed in register if all fields would be
311   // passed in a register.
312   for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
313          e = RT->getDecl()->field_end(); i != e; ++i) {
314     const FieldDecl *FD = *i;
315
316     // Empty fields are ignored.
317     if (isEmptyField(Context, FD, true))
318       continue;
319
320     // Check fields recursively.
321     if (!shouldReturnTypeInRegister(FD->getType(), Context))
322       return false;
323   }
324
325   return true;
326 }
327
328 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
329                                             ASTContext &Context,
330                                           llvm::LLVMContext &VMContext) const {
331   if (RetTy->isVoidType()) {
332     return ABIArgInfo::getIgnore();
333   } else if (const VectorType *VT = RetTy->getAs<VectorType>()) {
334     // On Darwin, some vectors are returned in registers.
335     if (IsDarwinVectorABI) {
336       uint64_t Size = Context.getTypeSize(RetTy);
337
338       // 128-bit vectors are a special case; they are returned in
339       // registers and we need to make sure to pick a type the LLVM
340       // backend will like.
341       if (Size == 128)
342         return ABIArgInfo::getCoerce(llvm::VectorType::get(
343                   llvm::Type::getInt64Ty(VMContext), 2));
344
345       // Always return in register if it fits in a general purpose
346       // register, or if it is 64 bits and has a single element.
347       if ((Size == 8 || Size == 16 || Size == 32) ||
348           (Size == 64 && VT->getNumElements() == 1))
349         return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
350
351       return ABIArgInfo::getIndirect(0);
352     }
353
354     return ABIArgInfo::getDirect();
355   } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
356     if (const RecordType *RT = RetTy->getAsStructureType()) {
357       // Structures with either a non-trivial destructor or a non-trivial
358       // copy constructor are always indirect.
359       if (hasNonTrivialDestructorOrCopyConstructor(RT))
360         return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
361       
362       // Structures with flexible arrays are always indirect.
363       if (RT->getDecl()->hasFlexibleArrayMember())
364         return ABIArgInfo::getIndirect(0);
365     }
366     
367     // If specified, structs and unions are always indirect.
368     if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
369       return ABIArgInfo::getIndirect(0);
370
371     // Classify "single element" structs as their element type.
372     if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
373       if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
374         if (BT->isIntegerType()) {
375           // We need to use the size of the structure, padding
376           // bit-fields can adjust that to be larger than the single
377           // element type.
378           uint64_t Size = Context.getTypeSize(RetTy);
379           return ABIArgInfo::getCoerce(
380             llvm::IntegerType::get(VMContext, (unsigned) Size));
381         } else if (BT->getKind() == BuiltinType::Float) {
382           assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
383                  "Unexpect single element structure size!");
384           return ABIArgInfo::getCoerce(llvm::Type::getFloatTy(VMContext));
385         } else if (BT->getKind() == BuiltinType::Double) {
386           assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
387                  "Unexpect single element structure size!");
388           return ABIArgInfo::getCoerce(llvm::Type::getDoubleTy(VMContext));
389         }
390       } else if (SeltTy->isPointerType()) {
391         // FIXME: It would be really nice if this could come out as the proper
392         // pointer type.
393         const llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(VMContext);
394         return ABIArgInfo::getCoerce(PtrTy);
395       } else if (SeltTy->isVectorType()) {
396         // 64- and 128-bit vectors are never returned in a
397         // register when inside a structure.
398         uint64_t Size = Context.getTypeSize(RetTy);
399         if (Size == 64 || Size == 128)
400           return ABIArgInfo::getIndirect(0);
401
402         return classifyReturnType(QualType(SeltTy, 0), Context, VMContext);
403       }
404     }
405
406     // Small structures which are register sized are generally returned
407     // in a register.
408     if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
409       uint64_t Size = Context.getTypeSize(RetTy);
410       return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
411     }
412
413     return ABIArgInfo::getIndirect(0);
414   } else {
415     return (RetTy->isPromotableIntegerType() ?
416             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
417   }
418 }
419
420 unsigned X86_32ABIInfo::getIndirectArgumentAlignment(QualType Ty,
421                                                      ASTContext &Context) {
422   unsigned Align = Context.getTypeAlign(Ty);
423   if (Align < 128) return 0;
424   if (const RecordType* RT = Ty->getAs<RecordType>())
425     if (typeContainsSSEVector(RT->getDecl(), Context))
426       return 16;
427   return 0;
428 }
429
430 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
431                                                ASTContext &Context,
432                                            llvm::LLVMContext &VMContext) const {
433   // FIXME: Set alignment on indirect arguments.
434   if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
435     // Structures with flexible arrays are always indirect.
436     if (const RecordType *RT = Ty->getAsStructureType())
437       if (RT->getDecl()->hasFlexibleArrayMember())
438         return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty,
439                                                                     Context));
440
441     // Ignore empty structs.
442     if (Ty->isStructureType() && Context.getTypeSize(Ty) == 0)
443       return ABIArgInfo::getIgnore();
444
445     // Expand structs with size <= 128-bits which consist only of
446     // basic types (int, long long, float, double, xxx*). This is
447     // non-recursive and does not ignore empty fields.
448     if (const RecordType *RT = Ty->getAsStructureType()) {
449       if (Context.getTypeSize(Ty) <= 4*32 &&
450           areAllFields32Or64BitBasicType(RT->getDecl(), Context))
451         return ABIArgInfo::getExpand();
452     }
453
454     return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, Context));
455   } else {
456     return (Ty->isPromotableIntegerType() ?
457             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
458   }
459 }
460
461 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462                                       CodeGenFunction &CGF) const {
463   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
464   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
465
466   CGBuilderTy &Builder = CGF.Builder;
467   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
468                                                        "ap");
469   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
470   llvm::Type *PTy =
471     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
472   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
473
474   uint64_t Offset =
475     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
476   llvm::Value *NextAddr =
477     Builder.CreateGEP(Addr, llvm::ConstantInt::get(
478                           llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
479                       "ap.next");
480   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
481
482   return AddrTyped;
483 }
484
485 namespace {
486 /// X86_64ABIInfo - The X86_64 ABI information.
487 class X86_64ABIInfo : public ABIInfo {
488   enum Class {
489     Integer = 0,
490     SSE,
491     SSEUp,
492     X87,
493     X87Up,
494     ComplexX87,
495     NoClass,
496     Memory
497   };
498
499   /// merge - Implement the X86_64 ABI merging algorithm.
500   ///
501   /// Merge an accumulating classification \arg Accum with a field
502   /// classification \arg Field.
503   ///
504   /// \param Accum - The accumulating classification. This should
505   /// always be either NoClass or the result of a previous merge
506   /// call. In addition, this should never be Memory (the caller
507   /// should just return Memory for the aggregate).
508   Class merge(Class Accum, Class Field) const;
509
510   /// classify - Determine the x86_64 register classes in which the
511   /// given type T should be passed.
512   ///
513   /// \param Lo - The classification for the parts of the type
514   /// residing in the low word of the containing object.
515   ///
516   /// \param Hi - The classification for the parts of the type
517   /// residing in the high word of the containing object.
518   ///
519   /// \param OffsetBase - The bit offset of this type in the
520   /// containing object.  Some parameters are classified different
521   /// depending on whether they straddle an eightbyte boundary.
522   ///
523   /// If a word is unused its result will be NoClass; if a type should
524   /// be passed in Memory then at least the classification of \arg Lo
525   /// will be Memory.
526   ///
527   /// The \arg Lo class will be NoClass iff the argument is ignored.
528   ///
529   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
530   /// also be ComplexX87.
531   void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
532                 Class &Lo, Class &Hi) const;
533
534   /// getCoerceResult - Given a source type \arg Ty and an LLVM type
535   /// to coerce to, chose the best way to pass Ty in the same place
536   /// that \arg CoerceTo would be passed, but while keeping the
537   /// emitted code as simple as possible.
538   ///
539   /// FIXME: Note, this should be cleaned up to just take an enumeration of all
540   /// the ways we might want to pass things, instead of constructing an LLVM
541   /// type. This makes this code more explicit, and it makes it clearer that we
542   /// are also doing this for correctness in the case of passing scalar types.
543   ABIArgInfo getCoerceResult(QualType Ty,
544                              const llvm::Type *CoerceTo,
545                              ASTContext &Context) const;
546
547   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
548   /// such that the argument will be passed in memory.
549   ABIArgInfo getIndirectResult(QualType Ty,
550                                ASTContext &Context) const;
551
552   ABIArgInfo classifyReturnType(QualType RetTy,
553                                 ASTContext &Context,
554                                 llvm::LLVMContext &VMContext) const;
555
556   ABIArgInfo classifyArgumentType(QualType Ty,
557                                   ASTContext &Context,
558                                   llvm::LLVMContext &VMContext,
559                                   unsigned &neededInt,
560                                   unsigned &neededSSE) const;
561
562 public:
563   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
564                            llvm::LLVMContext &VMContext) const;
565
566   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
567                                  CodeGenFunction &CGF) const;
568 };
569 }
570
571 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
572                                           Class Field) const {
573   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
574   // classified recursively so that always two fields are
575   // considered. The resulting class is calculated according to
576   // the classes of the fields in the eightbyte:
577   //
578   // (a) If both classes are equal, this is the resulting class.
579   //
580   // (b) If one of the classes is NO_CLASS, the resulting class is
581   // the other class.
582   //
583   // (c) If one of the classes is MEMORY, the result is the MEMORY
584   // class.
585   //
586   // (d) If one of the classes is INTEGER, the result is the
587   // INTEGER.
588   //
589   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
590   // MEMORY is used as class.
591   //
592   // (f) Otherwise class SSE is used.
593
594   // Accum should never be memory (we should have returned) or
595   // ComplexX87 (because this cannot be passed in a structure).
596   assert((Accum != Memory && Accum != ComplexX87) &&
597          "Invalid accumulated classification during merge.");
598   if (Accum == Field || Field == NoClass)
599     return Accum;
600   else if (Field == Memory)
601     return Memory;
602   else if (Accum == NoClass)
603     return Field;
604   else if (Accum == Integer || Field == Integer)
605     return Integer;
606   else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
607            Accum == X87 || Accum == X87Up)
608     return Memory;
609   else
610     return SSE;
611 }
612
613 void X86_64ABIInfo::classify(QualType Ty,
614                              ASTContext &Context,
615                              uint64_t OffsetBase,
616                              Class &Lo, Class &Hi) const {
617   // FIXME: This code can be simplified by introducing a simple value class for
618   // Class pairs with appropriate constructor methods for the various
619   // situations.
620
621   // FIXME: Some of the split computations are wrong; unaligned vectors
622   // shouldn't be passed in registers for example, so there is no chance they
623   // can straddle an eightbyte. Verify & simplify.
624
625   Lo = Hi = NoClass;
626
627   Class &Current = OffsetBase < 64 ? Lo : Hi;
628   Current = Memory;
629
630   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
631     BuiltinType::Kind k = BT->getKind();
632
633     if (k == BuiltinType::Void) {
634       Current = NoClass;
635     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
636       Lo = Integer;
637       Hi = Integer;
638     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
639       Current = Integer;
640     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
641       Current = SSE;
642     } else if (k == BuiltinType::LongDouble) {
643       Lo = X87;
644       Hi = X87Up;
645     }
646     // FIXME: _Decimal32 and _Decimal64 are SSE.
647     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
648   } else if (const EnumType *ET = Ty->getAs<EnumType>()) {
649     // Classify the underlying integer type.
650     classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
651   } else if (Ty->hasPointerRepresentation()) {
652     Current = Integer;
653   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
654     uint64_t Size = Context.getTypeSize(VT);
655     if (Size == 32) {
656       // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
657       // float> as integer.
658       Current = Integer;
659
660       // If this type crosses an eightbyte boundary, it should be
661       // split.
662       uint64_t EB_Real = (OffsetBase) / 64;
663       uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
664       if (EB_Real != EB_Imag)
665         Hi = Lo;
666     } else if (Size == 64) {
667       // gcc passes <1 x double> in memory. :(
668       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
669         return;
670
671       // gcc passes <1 x long long> as INTEGER.
672       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
673         Current = Integer;
674       else
675         Current = SSE;
676
677       // If this type crosses an eightbyte boundary, it should be
678       // split.
679       if (OffsetBase && OffsetBase != 64)
680         Hi = Lo;
681     } else if (Size == 128) {
682       Lo = SSE;
683       Hi = SSEUp;
684     }
685   } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
686     QualType ET = Context.getCanonicalType(CT->getElementType());
687
688     uint64_t Size = Context.getTypeSize(Ty);
689     if (ET->isIntegralType()) {
690       if (Size <= 64)
691         Current = Integer;
692       else if (Size <= 128)
693         Lo = Hi = Integer;
694     } else if (ET == Context.FloatTy)
695       Current = SSE;
696     else if (ET == Context.DoubleTy)
697       Lo = Hi = SSE;
698     else if (ET == Context.LongDoubleTy)
699       Current = ComplexX87;
700
701     // If this complex type crosses an eightbyte boundary then it
702     // should be split.
703     uint64_t EB_Real = (OffsetBase) / 64;
704     uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
705     if (Hi == NoClass && EB_Real != EB_Imag)
706       Hi = Lo;
707   } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
708     // Arrays are treated like structures.
709
710     uint64_t Size = Context.getTypeSize(Ty);
711
712     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
713     // than two eightbytes, ..., it has class MEMORY.
714     if (Size > 128)
715       return;
716
717     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
718     // fields, it has class MEMORY.
719     //
720     // Only need to check alignment of array base.
721     if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
722       return;
723
724     // Otherwise implement simplified merge. We could be smarter about
725     // this, but it isn't worth it and would be harder to verify.
726     Current = NoClass;
727     uint64_t EltSize = Context.getTypeSize(AT->getElementType());
728     uint64_t ArraySize = AT->getSize().getZExtValue();
729     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
730       Class FieldLo, FieldHi;
731       classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
732       Lo = merge(Lo, FieldLo);
733       Hi = merge(Hi, FieldHi);
734       if (Lo == Memory || Hi == Memory)
735         break;
736     }
737
738     // Do post merger cleanup (see below). Only case we worry about is Memory.
739     if (Hi == Memory)
740       Lo = Memory;
741     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
742   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
743     uint64_t Size = Context.getTypeSize(Ty);
744
745     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
746     // than two eightbytes, ..., it has class MEMORY.
747     if (Size > 128)
748       return;
749
750     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
751     // copy constructor or a non-trivial destructor, it is passed by invisible
752     // reference.
753     if (hasNonTrivialDestructorOrCopyConstructor(RT))
754       return;
755     
756     const RecordDecl *RD = RT->getDecl();
757
758     // Assume variable sized types are passed in memory.
759     if (RD->hasFlexibleArrayMember())
760       return;
761
762     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
763
764     // Reset Lo class, this will be recomputed.
765     Current = NoClass;
766     unsigned idx = 0;
767     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
768            i != e; ++i, ++idx) {
769       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
770       bool BitField = i->isBitField();
771
772       // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
773       // fields, it has class MEMORY.
774       //
775       // Note, skip this test for bit-fields, see below.
776       if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
777         Lo = Memory;
778         return;
779       }
780
781       // Classify this field.
782       //
783       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
784       // exceeds a single eightbyte, each is classified
785       // separately. Each eightbyte gets initialized to class
786       // NO_CLASS.
787       Class FieldLo, FieldHi;
788
789       // Bit-fields require special handling, they do not force the
790       // structure to be passed in memory even if unaligned, and
791       // therefore they can straddle an eightbyte.
792       if (BitField) {
793         // Ignore padding bit-fields.
794         if (i->isUnnamedBitfield())
795           continue;
796
797         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
798         uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
799
800         uint64_t EB_Lo = Offset / 64;
801         uint64_t EB_Hi = (Offset + Size - 1) / 64;
802         FieldLo = FieldHi = NoClass;
803         if (EB_Lo) {
804           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
805           FieldLo = NoClass;
806           FieldHi = Integer;
807         } else {
808           FieldLo = Integer;
809           FieldHi = EB_Hi ? Integer : NoClass;
810         }
811       } else
812         classify(i->getType(), Context, Offset, FieldLo, FieldHi);
813       Lo = merge(Lo, FieldLo);
814       Hi = merge(Hi, FieldHi);
815       if (Lo == Memory || Hi == Memory)
816         break;
817     }
818
819     // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
820     //
821     // (a) If one of the classes is MEMORY, the whole argument is
822     // passed in memory.
823     //
824     // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
825
826     // The first of these conditions is guaranteed by how we implement
827     // the merge (just bail).
828     //
829     // The second condition occurs in the case of unions; for example
830     // union { _Complex double; unsigned; }.
831     if (Hi == Memory)
832       Lo = Memory;
833     if (Hi == SSEUp && Lo != SSE)
834       Hi = SSE;
835   }
836 }
837
838 ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
839                                           const llvm::Type *CoerceTo,
840                                           ASTContext &Context) const {
841   if (CoerceTo == llvm::Type::getInt64Ty(CoerceTo->getContext())) {
842     // Integer and pointer types will end up in a general purpose
843     // register.
844     if (Ty->isIntegralType() || Ty->hasPointerRepresentation())
845       return (Ty->isPromotableIntegerType() ?
846               ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
847   } else if (CoerceTo == llvm::Type::getDoubleTy(CoerceTo->getContext())) {
848     // FIXME: It would probably be better to make CGFunctionInfo only map using
849     // canonical types than to canonize here.
850     QualType CTy = Context.getCanonicalType(Ty);
851
852     // Float and double end up in a single SSE reg.
853     if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
854       return ABIArgInfo::getDirect();
855
856   }
857
858   return ABIArgInfo::getCoerce(CoerceTo);
859 }
860
861 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
862                                             ASTContext &Context) const {
863   // If this is a scalar LLVM value then assume LLVM will pass it in the right
864   // place naturally.
865   if (!CodeGenFunction::hasAggregateLLVMType(Ty))
866     return (Ty->isPromotableIntegerType() ?
867             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
868
869   bool ByVal = !isRecordWithNonTrivialDestructorOrCopyConstructor(Ty);
870
871   // FIXME: Set alignment correctly.
872   return ABIArgInfo::getIndirect(0, ByVal);
873 }
874
875 ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
876                                             ASTContext &Context,
877                                           llvm::LLVMContext &VMContext) const {
878   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
879   // classification algorithm.
880   X86_64ABIInfo::Class Lo, Hi;
881   classify(RetTy, Context, 0, Lo, Hi);
882
883   // Check some invariants.
884   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
885   assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
886   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
887
888   const llvm::Type *ResType = 0;
889   switch (Lo) {
890   case NoClass:
891     return ABIArgInfo::getIgnore();
892
893   case SSEUp:
894   case X87Up:
895     assert(0 && "Invalid classification for lo word.");
896
897     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
898     // hidden argument.
899   case Memory:
900     return getIndirectResult(RetTy, Context);
901
902     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
903     // available register of the sequence %rax, %rdx is used.
904   case Integer:
905     ResType = llvm::Type::getInt64Ty(VMContext); break;
906
907     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
908     // available SSE register of the sequence %xmm0, %xmm1 is used.
909   case SSE:
910     ResType = llvm::Type::getDoubleTy(VMContext); break;
911
912     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
913     // returned on the X87 stack in %st0 as 80-bit x87 number.
914   case X87:
915     ResType = llvm::Type::getX86_FP80Ty(VMContext); break;
916
917     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
918     // part of the value is returned in %st0 and the imaginary part in
919     // %st1.
920   case ComplexX87:
921     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
922     ResType = llvm::StructType::get(VMContext, llvm::Type::getX86_FP80Ty(VMContext),
923                                     llvm::Type::getX86_FP80Ty(VMContext),
924                                     NULL);
925     break;
926   }
927
928   switch (Hi) {
929     // Memory was handled previously and X87 should
930     // never occur as a hi class.
931   case Memory:
932   case X87:
933     assert(0 && "Invalid classification for hi word.");
934
935   case ComplexX87: // Previously handled.
936   case NoClass: break;
937
938   case Integer:
939     ResType = llvm::StructType::get(VMContext, ResType,
940                                     llvm::Type::getInt64Ty(VMContext), NULL);
941     break;
942   case SSE:
943     ResType = llvm::StructType::get(VMContext, ResType,
944                                     llvm::Type::getDoubleTy(VMContext), NULL);
945     break;
946
947     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
948     // is passed in the upper half of the last used SSE register.
949     //
950     // SSEUP should always be preceeded by SSE, just widen.
951   case SSEUp:
952     assert(Lo == SSE && "Unexpected SSEUp classification.");
953     ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
954     break;
955
956     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
957     // returned together with the previous X87 value in %st0.
958   case X87Up:
959     // If X87Up is preceeded by X87, we don't need to do
960     // anything. However, in some cases with unions it may not be
961     // preceeded by X87. In such situations we follow gcc and pass the
962     // extra bits in an SSE reg.
963     if (Lo != X87)
964       ResType = llvm::StructType::get(VMContext, ResType,
965                                       llvm::Type::getDoubleTy(VMContext), NULL);
966     break;
967   }
968
969   return getCoerceResult(RetTy, ResType, Context);
970 }
971
972 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
973                                                llvm::LLVMContext &VMContext,
974                                                unsigned &neededInt,
975                                                unsigned &neededSSE) const {
976   X86_64ABIInfo::Class Lo, Hi;
977   classify(Ty, Context, 0, Lo, Hi);
978
979   // Check some invariants.
980   // FIXME: Enforce these by construction.
981   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
982   assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
983   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
984
985   neededInt = 0;
986   neededSSE = 0;
987   const llvm::Type *ResType = 0;
988   switch (Lo) {
989   case NoClass:
990     return ABIArgInfo::getIgnore();
991
992     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
993     // on the stack.
994   case Memory:
995
996     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
997     // COMPLEX_X87, it is passed in memory.
998   case X87:
999   case ComplexX87:
1000     return getIndirectResult(Ty, Context);
1001
1002   case SSEUp:
1003   case X87Up:
1004     assert(0 && "Invalid classification for lo word.");
1005
1006     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1007     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1008     // and %r9 is used.
1009   case Integer:
1010     ++neededInt;
1011     ResType = llvm::Type::getInt64Ty(VMContext);
1012     break;
1013
1014     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1015     // available SSE register is used, the registers are taken in the
1016     // order from %xmm0 to %xmm7.
1017   case SSE:
1018     ++neededSSE;
1019     ResType = llvm::Type::getDoubleTy(VMContext);
1020     break;
1021   }
1022
1023   switch (Hi) {
1024     // Memory was handled previously, ComplexX87 and X87 should
1025     // never occur as hi classes, and X87Up must be preceed by X87,
1026     // which is passed in memory.
1027   case Memory:
1028   case X87:
1029   case ComplexX87:
1030     assert(0 && "Invalid classification for hi word.");
1031     break;
1032
1033   case NoClass: break;
1034   case Integer:
1035     ResType = llvm::StructType::get(VMContext, ResType,
1036                                     llvm::Type::getInt64Ty(VMContext), NULL);
1037     ++neededInt;
1038     break;
1039
1040     // X87Up generally doesn't occur here (long double is passed in
1041     // memory), except in situations involving unions.
1042   case X87Up:
1043   case SSE:
1044     ResType = llvm::StructType::get(VMContext, ResType,
1045                                     llvm::Type::getDoubleTy(VMContext), NULL);
1046     ++neededSSE;
1047     break;
1048
1049     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1050     // eightbyte is passed in the upper half of the last used SSE
1051     // register.
1052   case SSEUp:
1053     assert(Lo == SSE && "Unexpected SSEUp classification.");
1054     ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
1055     break;
1056   }
1057
1058   return getCoerceResult(Ty, ResType, Context);
1059 }
1060
1061 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1062                                 llvm::LLVMContext &VMContext) const {
1063   FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1064                                           Context, VMContext);
1065
1066   // Keep track of the number of assigned registers.
1067   unsigned freeIntRegs = 6, freeSSERegs = 8;
1068
1069   // If the return value is indirect, then the hidden argument is consuming one
1070   // integer register.
1071   if (FI.getReturnInfo().isIndirect())
1072     --freeIntRegs;
1073
1074   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1075   // get assigned (in left-to-right order) for passing as follows...
1076   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1077        it != ie; ++it) {
1078     unsigned neededInt, neededSSE;
1079     it->info = classifyArgumentType(it->type, Context, VMContext,
1080                                     neededInt, neededSSE);
1081
1082     // AMD64-ABI 3.2.3p3: If there are no registers available for any
1083     // eightbyte of an argument, the whole argument is passed on the
1084     // stack. If registers have already been assigned for some
1085     // eightbytes of such an argument, the assignments get reverted.
1086     if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1087       freeIntRegs -= neededInt;
1088       freeSSERegs -= neededSSE;
1089     } else {
1090       it->info = getIndirectResult(it->type, Context);
1091     }
1092   }
1093 }
1094
1095 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1096                                         QualType Ty,
1097                                         CodeGenFunction &CGF) {
1098   llvm::Value *overflow_arg_area_p =
1099     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1100   llvm::Value *overflow_arg_area =
1101     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1102
1103   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1104   // byte boundary if alignment needed by type exceeds 8 byte boundary.
1105   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1106   if (Align > 8) {
1107     // Note that we follow the ABI & gcc here, even though the type
1108     // could in theory have an alignment greater than 16. This case
1109     // shouldn't ever matter in practice.
1110
1111     // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1112     llvm::Value *Offset =
1113       llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), 15);
1114     overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1115     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1116                                  llvm::Type::getInt64Ty(CGF.getLLVMContext()));
1117     llvm::Value *Mask = llvm::ConstantInt::get(
1118         llvm::Type::getInt64Ty(CGF.getLLVMContext()), ~15LL);
1119     overflow_arg_area =
1120       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1121                                  overflow_arg_area->getType(),
1122                                  "overflow_arg_area.align");
1123   }
1124
1125   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1126   const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1127   llvm::Value *Res =
1128     CGF.Builder.CreateBitCast(overflow_arg_area,
1129                               llvm::PointerType::getUnqual(LTy));
1130
1131   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1132   // l->overflow_arg_area + sizeof(type).
1133   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1134   // an 8 byte boundary.
1135
1136   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1137   llvm::Value *Offset =
1138       llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
1139                                                (SizeInBytes + 7)  & ~7);
1140   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1141                                             "overflow_arg_area.next");
1142   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1143
1144   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1145   return Res;
1146 }
1147
1148 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1149                                       CodeGenFunction &CGF) const {
1150   llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1151   const llvm::Type *i32Ty = llvm::Type::getInt32Ty(VMContext);
1152   const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
1153
1154   // Assume that va_list type is correct; should be pointer to LLVM type:
1155   // struct {
1156   //   i32 gp_offset;
1157   //   i32 fp_offset;
1158   //   i8* overflow_arg_area;
1159   //   i8* reg_save_area;
1160   // };
1161   unsigned neededInt, neededSSE;
1162   ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(), VMContext,
1163                                        neededInt, neededSSE);
1164
1165   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1166   // in the registers. If not go to step 7.
1167   if (!neededInt && !neededSSE)
1168     return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1169
1170   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1171   // general purpose registers needed to pass type and num_fp to hold
1172   // the number of floating point registers needed.
1173
1174   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1175   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1176   // l->fp_offset > 304 - num_fp * 16 go to step 7.
1177   //
1178   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1179   // register save space).
1180
1181   llvm::Value *InRegs = 0;
1182   llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1183   llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1184   if (neededInt) {
1185     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1186     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1187     InRegs =
1188       CGF.Builder.CreateICmpULE(gp_offset,
1189                                 llvm::ConstantInt::get(i32Ty,
1190                                                        48 - neededInt * 8),
1191                                 "fits_in_gp");
1192   }
1193
1194   if (neededSSE) {
1195     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1196     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1197     llvm::Value *FitsInFP =
1198       CGF.Builder.CreateICmpULE(fp_offset,
1199                                 llvm::ConstantInt::get(i32Ty,
1200                                                        176 - neededSSE * 16),
1201                                 "fits_in_fp");
1202     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1203   }
1204
1205   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1206   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1207   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1208   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1209
1210   // Emit code to load the value if it was passed in registers.
1211
1212   CGF.EmitBlock(InRegBlock);
1213
1214   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1215   // an offset of l->gp_offset and/or l->fp_offset. This may require
1216   // copying to a temporary location in case the parameter is passed
1217   // in different register classes or requires an alignment greater
1218   // than 8 for general purpose registers and 16 for XMM registers.
1219   //
1220   // FIXME: This really results in shameful code when we end up needing to
1221   // collect arguments from different places; often what should result in a
1222   // simple assembling of a structure from scattered addresses has many more
1223   // loads than necessary. Can we clean this up?
1224   const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1225   llvm::Value *RegAddr =
1226     CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1227                            "reg_save_area");
1228   if (neededInt && neededSSE) {
1229     // FIXME: Cleanup.
1230     assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1231     const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1232     llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1233     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1234     const llvm::Type *TyLo = ST->getElementType(0);
1235     const llvm::Type *TyHi = ST->getElementType(1);
1236     assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1237            "Unexpected ABI info for mixed regs");
1238     const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1239     const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1240     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1241     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1242     llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1243     llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1244     llvm::Value *V =
1245       CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1246     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1247     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1248     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1249
1250     RegAddr = CGF.Builder.CreateBitCast(Tmp,
1251                                         llvm::PointerType::getUnqual(LTy));
1252   } else if (neededInt) {
1253     RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1254     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1255                                         llvm::PointerType::getUnqual(LTy));
1256   } else {
1257     if (neededSSE == 1) {
1258       RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1259       RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1260                                           llvm::PointerType::getUnqual(LTy));
1261     } else {
1262       assert(neededSSE == 2 && "Invalid number of needed registers!");
1263       // SSE registers are spaced 16 bytes apart in the register save
1264       // area, we need to collect the two eightbytes together.
1265       llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1266       llvm::Value *RegAddrHi =
1267         CGF.Builder.CreateGEP(RegAddrLo,
1268                             llvm::ConstantInt::get(i32Ty, 16));
1269       const llvm::Type *DblPtrTy =
1270         llvm::PointerType::getUnqual(DoubleTy);
1271       const llvm::StructType *ST = llvm::StructType::get(VMContext, DoubleTy,
1272                                                          DoubleTy, NULL);
1273       llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1274       V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1275                                                            DblPtrTy));
1276       CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1277       V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1278                                                            DblPtrTy));
1279       CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1280       RegAddr = CGF.Builder.CreateBitCast(Tmp,
1281                                           llvm::PointerType::getUnqual(LTy));
1282     }
1283   }
1284
1285   // AMD64-ABI 3.5.7p5: Step 5. Set:
1286   // l->gp_offset = l->gp_offset + num_gp * 8
1287   // l->fp_offset = l->fp_offset + num_fp * 16.
1288   if (neededInt) {
1289     llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededInt * 8);
1290     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1291                             gp_offset_p);
1292   }
1293   if (neededSSE) {
1294     llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededSSE * 16);
1295     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1296                             fp_offset_p);
1297   }
1298   CGF.EmitBranch(ContBlock);
1299
1300   // Emit code to load the value if it was passed in memory.
1301
1302   CGF.EmitBlock(InMemBlock);
1303   llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1304
1305   // Return the appropriate result.
1306
1307   CGF.EmitBlock(ContBlock);
1308   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1309                                                  "vaarg.addr");
1310   ResAddr->reserveOperandSpace(2);
1311   ResAddr->addIncoming(RegAddr, InRegBlock);
1312   ResAddr->addIncoming(MemAddr, InMemBlock);
1313
1314   return ResAddr;
1315 }
1316
1317 // PIC16 ABI Implementation
1318
1319 namespace {
1320
1321 class PIC16ABIInfo : public ABIInfo {
1322   ABIArgInfo classifyReturnType(QualType RetTy,
1323                                 ASTContext &Context,
1324                                 llvm::LLVMContext &VMContext) const;
1325
1326   ABIArgInfo classifyArgumentType(QualType RetTy,
1327                                   ASTContext &Context,
1328                                   llvm::LLVMContext &VMContext) const;
1329
1330   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1331                            llvm::LLVMContext &VMContext) const {
1332     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1333                                             VMContext);
1334     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1335          it != ie; ++it)
1336       it->info = classifyArgumentType(it->type, Context, VMContext);
1337   }
1338
1339   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1340                                  CodeGenFunction &CGF) const;
1341 };
1342
1343 }
1344
1345 ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1346                                             ASTContext &Context,
1347                                           llvm::LLVMContext &VMContext) const {
1348   if (RetTy->isVoidType()) {
1349     return ABIArgInfo::getIgnore();
1350   } else {
1351     return ABIArgInfo::getDirect();
1352   }
1353 }
1354
1355 ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1356                                               ASTContext &Context,
1357                                           llvm::LLVMContext &VMContext) const {
1358   return ABIArgInfo::getDirect();
1359 }
1360
1361 llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1362                                        CodeGenFunction &CGF) const {
1363   return 0;
1364 }
1365
1366 // ARM ABI Implementation
1367
1368 namespace {
1369
1370 class ARMABIInfo : public ABIInfo {
1371 public:
1372   enum ABIKind {
1373     APCS = 0,
1374     AAPCS = 1,
1375     AAPCS_VFP
1376   };
1377
1378 private:
1379   ABIKind Kind;
1380
1381 public:
1382   ARMABIInfo(ABIKind _Kind) : Kind(_Kind) {}
1383
1384 private:
1385   ABIKind getABIKind() const { return Kind; }
1386
1387   ABIArgInfo classifyReturnType(QualType RetTy,
1388                                 ASTContext &Context,
1389                                 llvm::LLVMContext &VMCOntext) const;
1390
1391   ABIArgInfo classifyArgumentType(QualType RetTy,
1392                                   ASTContext &Context,
1393                                   llvm::LLVMContext &VMContext) const;
1394
1395   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1396                            llvm::LLVMContext &VMContext) const;
1397
1398   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1399                                  CodeGenFunction &CGF) const;
1400 };
1401
1402 }
1403
1404 void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1405                              llvm::LLVMContext &VMContext) const {
1406   FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1407                                           VMContext);
1408   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1409        it != ie; ++it) {
1410     it->info = classifyArgumentType(it->type, Context, VMContext);
1411   }
1412
1413   // ARM always overrides the calling convention.
1414   switch (getABIKind()) {
1415   case APCS:
1416     FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
1417     break;
1418
1419   case AAPCS:
1420     FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
1421     break;
1422
1423   case AAPCS_VFP:
1424     FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
1425     break;
1426   }
1427 }
1428
1429 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1430                                             ASTContext &Context,
1431                                           llvm::LLVMContext &VMContext) const {
1432   if (!CodeGenFunction::hasAggregateLLVMType(Ty))
1433     return (Ty->isPromotableIntegerType() ?
1434             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1435
1436   // Ignore empty records.
1437   if (isEmptyRecord(Context, Ty, true))
1438     return ABIArgInfo::getIgnore();
1439
1440   // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1441   // backend doesn't support byval.
1442   // FIXME: This doesn't handle alignment > 64 bits.
1443   const llvm::Type* ElemTy;
1444   unsigned SizeRegs;
1445   if (Context.getTypeAlign(Ty) > 32) {
1446     ElemTy = llvm::Type::getInt64Ty(VMContext);
1447     SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1448   } else {
1449     ElemTy = llvm::Type::getInt32Ty(VMContext);
1450     SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1451   }
1452   std::vector<const llvm::Type*> LLVMFields;
1453   LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1454   const llvm::Type* STy = llvm::StructType::get(VMContext, LLVMFields, true);
1455   return ABIArgInfo::getCoerce(STy);
1456 }
1457
1458 static bool isIntegerLikeType(QualType Ty,
1459                               ASTContext &Context,
1460                               llvm::LLVMContext &VMContext) {
1461   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
1462   // is called integer-like if its size is less than or equal to one word, and
1463   // the offset of each of its addressable sub-fields is zero.
1464
1465   uint64_t Size = Context.getTypeSize(Ty);
1466
1467   // Check that the type fits in a word.
1468   if (Size > 32)
1469     return false;
1470
1471   // FIXME: Handle vector types!
1472   if (Ty->isVectorType())
1473     return false;
1474
1475   // Float types are never treated as "integer like".
1476   if (Ty->isRealFloatingType())
1477     return false;
1478
1479   // If this is a builtin or pointer type then it is ok.
1480   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
1481     return true;
1482
1483   // Complex types "should" be ok by the definition above, but they are not.
1484   if (Ty->isAnyComplexType())
1485     return false;
1486
1487   // Single element and zero sized arrays should be allowed, by the definition
1488   // above, but they are not.
1489
1490   // Otherwise, it must be a record type.
1491   const RecordType *RT = Ty->getAs<RecordType>();
1492   if (!RT) return false;
1493
1494   // Ignore records with flexible arrays.
1495   const RecordDecl *RD = RT->getDecl();
1496   if (RD->hasFlexibleArrayMember())
1497     return false;
1498
1499   // Check that all sub-fields are at offset 0, and are themselves "integer
1500   // like".
1501   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1502
1503   bool HadField = false;
1504   unsigned idx = 0;
1505   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1506        i != e; ++i, ++idx) {
1507     const FieldDecl *FD = *i;
1508
1509     // Check if this field is at offset 0.
1510     uint64_t Offset = Layout.getFieldOffset(idx);
1511     if (Offset != 0) {
1512       // Allow padding bit-fields, but only if they are all at the end of the
1513       // structure (despite the wording above, this matches gcc).
1514       if (FD->isBitField() && 
1515           !FD->getBitWidth()->EvaluateAsInt(Context).getZExtValue()) {
1516         for (; i != e; ++i)
1517           if (!i->isBitField() ||
1518               i->getBitWidth()->EvaluateAsInt(Context).getZExtValue())
1519             return false;
1520
1521         // All remaining fields are padding, allow this.
1522         return true;
1523       }
1524
1525       return false;
1526     }
1527
1528     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
1529       return false;
1530     
1531     // Only allow at most one field in a structure. Again this doesn't match the
1532     // wording above, but follows gcc.
1533     if (!RD->isUnion()) {
1534       if (HadField)
1535         return false;
1536
1537       HadField = true;
1538     }
1539   }
1540
1541   return true;
1542 }
1543
1544 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1545                                           ASTContext &Context,
1546                                           llvm::LLVMContext &VMContext) const {
1547   if (RetTy->isVoidType())
1548     return ABIArgInfo::getIgnore();
1549
1550   if (!CodeGenFunction::hasAggregateLLVMType(RetTy))
1551     return (RetTy->isPromotableIntegerType() ?
1552             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1553
1554   // Are we following APCS?
1555   if (getABIKind() == APCS) {
1556     if (isEmptyRecord(Context, RetTy, false))
1557       return ABIArgInfo::getIgnore();
1558
1559     // Integer like structures are returned in r0.
1560     if (isIntegerLikeType(RetTy, Context, VMContext)) {
1561       // Return in the smallest viable integer type.
1562       uint64_t Size = Context.getTypeSize(RetTy);
1563       if (Size <= 8)
1564         return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1565       if (Size <= 16)
1566         return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1567       return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1568     }
1569
1570     // Otherwise return in memory.
1571     return ABIArgInfo::getIndirect(0);
1572   }
1573
1574   // Otherwise this is an AAPCS variant.
1575
1576   if (isEmptyRecord(Context, RetTy, true))
1577     return ABIArgInfo::getIgnore();
1578
1579   // Aggregates <= 4 bytes are returned in r0; other aggregates
1580   // are returned indirectly.
1581   uint64_t Size = Context.getTypeSize(RetTy);
1582   if (Size <= 32) {
1583     // Return in the smallest viable integer type.
1584     if (Size <= 8)
1585       return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1586     if (Size <= 16)
1587       return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1588     return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1589   }
1590
1591   return ABIArgInfo::getIndirect(0);
1592 }
1593
1594 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1595                                       CodeGenFunction &CGF) const {
1596   // FIXME: Need to handle alignment
1597   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1598   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1599
1600   CGBuilderTy &Builder = CGF.Builder;
1601   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1602                                                        "ap");
1603   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1604   llvm::Type *PTy =
1605     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1606   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1607
1608   uint64_t Offset =
1609     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1610   llvm::Value *NextAddr =
1611     Builder.CreateGEP(Addr, llvm::ConstantInt::get(
1612                           llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
1613                       "ap.next");
1614   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1615
1616   return AddrTyped;
1617 }
1618
1619 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1620                                               ASTContext &Context,
1621                                           llvm::LLVMContext &VMContext) const {
1622   if (RetTy->isVoidType()) {
1623     return ABIArgInfo::getIgnore();
1624   } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1625     return ABIArgInfo::getIndirect(0);
1626   } else {
1627     return (RetTy->isPromotableIntegerType() ?
1628             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1629   }
1630 }
1631
1632 // SystemZ ABI Implementation
1633
1634 namespace {
1635
1636 class SystemZABIInfo : public ABIInfo {
1637   bool isPromotableIntegerType(QualType Ty) const;
1638
1639   ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context,
1640                                 llvm::LLVMContext &VMContext) const;
1641
1642   ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context,
1643                                   llvm::LLVMContext &VMContext) const;
1644
1645   virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1646                           llvm::LLVMContext &VMContext) const {
1647     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1648                                             Context, VMContext);
1649     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1650          it != ie; ++it)
1651       it->info = classifyArgumentType(it->type, Context, VMContext);
1652   }
1653
1654   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1655                                  CodeGenFunction &CGF) const;
1656 };
1657
1658 }
1659
1660 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
1661   // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
1662   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
1663     switch (BT->getKind()) {
1664     case BuiltinType::Bool:
1665     case BuiltinType::Char_S:
1666     case BuiltinType::Char_U:
1667     case BuiltinType::SChar:
1668     case BuiltinType::UChar:
1669     case BuiltinType::Short:
1670     case BuiltinType::UShort:
1671     case BuiltinType::Int:
1672     case BuiltinType::UInt:
1673       return true;
1674     default:
1675       return false;
1676     }
1677   return false;
1678 }
1679
1680 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1681                                        CodeGenFunction &CGF) const {
1682   // FIXME: Implement
1683   return 0;
1684 }
1685
1686
1687 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy,
1688                                               ASTContext &Context,
1689                                            llvm::LLVMContext &VMContext) const {
1690   if (RetTy->isVoidType()) {
1691     return ABIArgInfo::getIgnore();
1692   } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1693     return ABIArgInfo::getIndirect(0);
1694   } else {
1695     return (isPromotableIntegerType(RetTy) ?
1696             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1697   }
1698 }
1699
1700 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty,
1701                                                 ASTContext &Context,
1702                                            llvm::LLVMContext &VMContext) const {
1703   if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1704     return ABIArgInfo::getIndirect(0);
1705   } else {
1706     return (isPromotableIntegerType(Ty) ?
1707             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1708   }
1709 }
1710
1711 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
1712                                                 ASTContext &Context,
1713                                           llvm::LLVMContext &VMContext) const {
1714   if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1715     return ABIArgInfo::getIndirect(0);
1716   } else {
1717     return (Ty->isPromotableIntegerType() ?
1718             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1719   }
1720 }
1721
1722 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1723                                        CodeGenFunction &CGF) const {
1724   return 0;
1725 }
1726
1727 const ABIInfo &CodeGenTypes::getABIInfo() const {
1728   if (TheABIInfo)
1729     return *TheABIInfo;
1730
1731   // For now we just cache the ABIInfo in CodeGenTypes and don't free it.
1732
1733   const llvm::Triple &Triple(getContext().Target.getTriple());
1734   switch (Triple.getArch()) {
1735   default:
1736     return *(TheABIInfo = new DefaultABIInfo);
1737
1738   case llvm::Triple::arm:
1739   case llvm::Triple::thumb:
1740     // FIXME: We want to know the float calling convention as well.
1741     if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
1742       return *(TheABIInfo = new ARMABIInfo(ARMABIInfo::APCS));
1743
1744     return *(TheABIInfo = new ARMABIInfo(ARMABIInfo::AAPCS));
1745
1746   case llvm::Triple::pic16:
1747     return *(TheABIInfo = new PIC16ABIInfo());
1748
1749   case llvm::Triple::systemz:
1750     return *(TheABIInfo = new SystemZABIInfo());
1751
1752   case llvm::Triple::x86:
1753     switch (Triple.getOS()) {
1754     case llvm::Triple::Darwin:
1755       return *(TheABIInfo = new X86_32ABIInfo(Context, true, true));
1756     case llvm::Triple::Cygwin:
1757     case llvm::Triple::MinGW32:
1758     case llvm::Triple::MinGW64:
1759     case llvm::Triple::AuroraUX:
1760     case llvm::Triple::DragonFly:
1761     case llvm::Triple::FreeBSD:
1762     case llvm::Triple::OpenBSD:
1763       return *(TheABIInfo = new X86_32ABIInfo(Context, false, true));
1764
1765     default:
1766       return *(TheABIInfo = new X86_32ABIInfo(Context, false, false));
1767     }
1768
1769   case llvm::Triple::x86_64:
1770     return *(TheABIInfo = new X86_64ABIInfo());
1771   }
1772 }