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