blob: 361e5c0005cc7811e081c8ddbdf564b1cc0681cb [file] [log] [blame]
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001//===---- TargetABIInfo.cpp - Encapsulate target ABI details ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ABIInfo.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/RecordLayout.h"
18#include "llvm/Type.h"
19
20using namespace clang;
21using namespace CodeGen;
22
23ABIInfo::~ABIInfo() {}
24
25void ABIArgInfo::dump() const {
26 fprintf(stderr, "(ABIArgInfo Kind=");
27 switch (TheKind) {
28 case Direct:
29 fprintf(stderr, "Direct");
30 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +000031 case Extend:
32 fprintf(stderr, "Extend");
33 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000034 case Ignore:
35 fprintf(stderr, "Ignore");
36 break;
37 case Coerce:
38 fprintf(stderr, "Coerce Type=");
39 getCoerceToType()->print(llvm::errs());
40 break;
41 case Indirect:
42 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
43 break;
44 case Expand:
45 fprintf(stderr, "Expand");
46 break;
47 }
48 fprintf(stderr, ")\n");
49}
50
51static bool isEmptyRecord(ASTContext &Context, QualType T);
52
53/// isEmptyField - Return true iff a the field is "empty", that is it
54/// is an unnamed bit-field or an (array of) empty record(s).
55static bool isEmptyField(ASTContext &Context, const FieldDecl *FD) {
56 if (FD->isUnnamedBitfield())
57 return true;
58
59 QualType FT = FD->getType();
60 // Constant arrays of empty records count as empty, strip them off.
61 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
62 FT = AT->getElementType();
63
64 return isEmptyRecord(Context, FT);
65}
66
67/// isEmptyRecord - Return true iff a structure contains only empty
68/// fields. Note that a structure with a flexible array member is not
69/// considered empty.
70static bool isEmptyRecord(ASTContext &Context, QualType T) {
71 const RecordType *RT = T->getAsRecordType();
72 if (!RT)
73 return 0;
74 const RecordDecl *RD = RT->getDecl();
75 if (RD->hasFlexibleArrayMember())
76 return false;
77 for (RecordDecl::field_iterator i = RD->field_begin(Context),
78 e = RD->field_end(Context); i != e; ++i)
79 if (!isEmptyField(Context, *i))
80 return false;
81 return true;
82}
83
84/// isSingleElementStruct - Determine if a structure is a "single
85/// element struct", i.e. it has exactly one non-empty field or
86/// exactly one field which is itself a single element
87/// struct. Structures with flexible array members are never
88/// considered single element structs.
89///
90/// \return The field declaration for the single non-empty field, if
91/// it exists.
92static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
93 const RecordType *RT = T->getAsStructureType();
94 if (!RT)
95 return 0;
96
97 const RecordDecl *RD = RT->getDecl();
98 if (RD->hasFlexibleArrayMember())
99 return 0;
100
101 const Type *Found = 0;
102 for (RecordDecl::field_iterator i = RD->field_begin(Context),
103 e = RD->field_end(Context); i != e; ++i) {
104 const FieldDecl *FD = *i;
105 QualType FT = FD->getType();
106
107 // Ignore empty fields.
108 if (isEmptyField(Context, FD))
109 continue;
110
111 // If we already found an element then this isn't a single-element
112 // struct.
113 if (Found)
114 return 0;
115
116 // Treat single element arrays as the element.
117 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
118 if (AT->getSize().getZExtValue() != 1)
119 break;
120 FT = AT->getElementType();
121 }
122
123 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
124 Found = FT.getTypePtr();
125 } else {
126 Found = isSingleElementStruct(FT, Context);
127 if (!Found)
128 return 0;
129 }
130 }
131
132 return Found;
133}
134
135static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
136 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
137 return false;
138
139 uint64_t Size = Context.getTypeSize(Ty);
140 return Size == 32 || Size == 64;
141}
142
143static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
144 ASTContext &Context) {
145 for (RecordDecl::field_iterator i = RD->field_begin(Context),
146 e = RD->field_end(Context); i != e; ++i) {
147 const FieldDecl *FD = *i;
148
149 if (!is32Or64BitBasicType(FD->getType(), Context))
150 return false;
151
152 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
153 // how to expand them yet, and the predicate for telling if a bitfield still
154 // counts as "basic" is more complicated than what we were doing previously.
155 if (FD->isBitField())
156 return false;
157 }
158
159 return true;
160}
161
Eli Friedmana1e6de92009-06-13 21:37:10 +0000162static bool typeContainsSSEVector(const RecordDecl *RD, ASTContext &Context) {
163 for (RecordDecl::field_iterator i = RD->field_begin(Context),
164 e = RD->field_end(Context); i != e; ++i) {
165 const FieldDecl *FD = *i;
166
167 if (FD->getType()->isVectorType() &&
168 Context.getTypeSize(FD->getType()) >= 128)
169 return true;
170
171 if (const RecordType* RT = FD->getType()->getAsRecordType())
172 if (typeContainsSSEVector(RT->getDecl(), Context))
173 return true;
174 }
175
176 return false;
177}
178
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000179namespace {
180/// DefaultABIInfo - The default implementation for ABI specific
181/// details. This implementation provides information which results in
182/// self-consistent and sensible LLVM IR generation, but does not
183/// conform to any particular ABI.
184class DefaultABIInfo : public ABIInfo {
185 ABIArgInfo classifyReturnType(QualType RetTy,
186 ASTContext &Context) const;
187
188 ABIArgInfo classifyArgumentType(QualType RetTy,
189 ASTContext &Context) const;
190
191 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
192 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
193 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
194 it != ie; ++it)
195 it->info = classifyArgumentType(it->type, Context);
196 }
197
198 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
199 CodeGenFunction &CGF) const;
200};
201
202/// X86_32ABIInfo - The X86-32 ABI information.
203class X86_32ABIInfo : public ABIInfo {
204 ASTContext &Context;
205 bool IsDarwin;
206
207 static bool isRegisterSize(unsigned Size) {
208 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
209 }
210
211 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
212
Eli Friedmana1e6de92009-06-13 21:37:10 +0000213 static unsigned getIndirectArgumentAlignment(QualType Ty,
214 ASTContext &Context);
215
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000216public:
217 ABIArgInfo classifyReturnType(QualType RetTy,
218 ASTContext &Context) const;
219
220 ABIArgInfo classifyArgumentType(QualType RetTy,
221 ASTContext &Context) const;
222
223 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
224 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
225 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
226 it != ie; ++it)
227 it->info = classifyArgumentType(it->type, Context);
228 }
229
230 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
231 CodeGenFunction &CGF) const;
232
233 X86_32ABIInfo(ASTContext &Context, bool d)
234 : ABIInfo(), Context(Context), IsDarwin(d) {}
235};
236}
237
238
239/// shouldReturnTypeInRegister - Determine if the given type should be
240/// passed in a register (for the Darwin ABI).
241bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
242 ASTContext &Context) {
243 uint64_t Size = Context.getTypeSize(Ty);
244
245 // Type must be register sized.
246 if (!isRegisterSize(Size))
247 return false;
248
249 if (Ty->isVectorType()) {
250 // 64- and 128- bit vectors inside structures are not returned in
251 // registers.
252 if (Size == 64 || Size == 128)
253 return false;
254
255 return true;
256 }
257
258 // If this is a builtin, pointer, or complex type, it is ok.
259 if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType())
260 return true;
261
262 // Arrays are treated like records.
263 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
264 return shouldReturnTypeInRegister(AT->getElementType(), Context);
265
266 // Otherwise, it must be a record type.
267 const RecordType *RT = Ty->getAsRecordType();
268 if (!RT) return false;
269
270 // Structure types are passed in register if all fields would be
271 // passed in a register.
272 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context),
273 e = RT->getDecl()->field_end(Context); i != e; ++i) {
274 const FieldDecl *FD = *i;
275
276 // Empty fields are ignored.
277 if (isEmptyField(Context, FD))
278 continue;
279
280 // Check fields recursively.
281 if (!shouldReturnTypeInRegister(FD->getType(), Context))
282 return false;
283 }
284
285 return true;
286}
287
288ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
289 ASTContext &Context) const {
290 if (RetTy->isVoidType()) {
291 return ABIArgInfo::getIgnore();
292 } else if (const VectorType *VT = RetTy->getAsVectorType()) {
293 // On Darwin, some vectors are returned in registers.
294 if (IsDarwin) {
295 uint64_t Size = Context.getTypeSize(RetTy);
296
297 // 128-bit vectors are a special case; they are returned in
298 // registers and we need to make sure to pick a type the LLVM
299 // backend will like.
300 if (Size == 128)
301 return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty,
302 2));
303
304 // Always return in register if it fits in a general purpose
305 // register, or if it is 64 bits and has a single element.
306 if ((Size == 8 || Size == 16 || Size == 32) ||
307 (Size == 64 && VT->getNumElements() == 1))
308 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
309
310 return ABIArgInfo::getIndirect(0);
311 }
312
313 return ABIArgInfo::getDirect();
314 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
315 // Structures with flexible arrays are always indirect.
316 if (const RecordType *RT = RetTy->getAsStructureType())
317 if (RT->getDecl()->hasFlexibleArrayMember())
318 return ABIArgInfo::getIndirect(0);
319
320 // Outside of Darwin, structs and unions are always indirect.
321 if (!IsDarwin && !RetTy->isAnyComplexType())
322 return ABIArgInfo::getIndirect(0);
323
324 // Classify "single element" structs as their element type.
325 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
326 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
327 if (BT->isIntegerType()) {
328 // We need to use the size of the structure, padding
329 // bit-fields can adjust that to be larger than the single
330 // element type.
331 uint64_t Size = Context.getTypeSize(RetTy);
332 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
333 } else if (BT->getKind() == BuiltinType::Float) {
334 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
335 "Unexpect single element structure size!");
336 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
337 } else if (BT->getKind() == BuiltinType::Double) {
338 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
339 "Unexpect single element structure size!");
340 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
341 }
342 } else if (SeltTy->isPointerType()) {
343 // FIXME: It would be really nice if this could come out as the proper
344 // pointer type.
345 llvm::Type *PtrTy =
346 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
347 return ABIArgInfo::getCoerce(PtrTy);
348 } else if (SeltTy->isVectorType()) {
349 // 64- and 128-bit vectors are never returned in a
350 // register when inside a structure.
351 uint64_t Size = Context.getTypeSize(RetTy);
352 if (Size == 64 || Size == 128)
353 return ABIArgInfo::getIndirect(0);
354
355 return classifyReturnType(QualType(SeltTy, 0), Context);
356 }
357 }
358
359 // Small structures which are register sized are generally returned
360 // in a register.
361 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
362 uint64_t Size = Context.getTypeSize(RetTy);
363 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
364 }
365
366 return ABIArgInfo::getIndirect(0);
367 } else {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000368 return (RetTy->isPromotableIntegerType() ?
369 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000370 }
371}
372
Eli Friedmana1e6de92009-06-13 21:37:10 +0000373unsigned X86_32ABIInfo::getIndirectArgumentAlignment(QualType Ty,
374 ASTContext &Context) {
375 unsigned Align = Context.getTypeAlign(Ty);
376 if (Align < 128) return 0;
377 if (const RecordType* RT = Ty->getAsRecordType())
378 if (typeContainsSSEVector(RT->getDecl(), Context))
379 return 16;
380 return 0;
381}
382
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000383ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
384 ASTContext &Context) const {
385 // FIXME: Set alignment on indirect arguments.
386 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
387 // Structures with flexible arrays are always indirect.
388 if (const RecordType *RT = Ty->getAsStructureType())
389 if (RT->getDecl()->hasFlexibleArrayMember())
Eli Friedmana1e6de92009-06-13 21:37:10 +0000390 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty,
391 Context));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000392
393 // Ignore empty structs.
Eli Friedmana1e6de92009-06-13 21:37:10 +0000394 if (Ty->isStructureType() && Context.getTypeSize(Ty) == 0)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000395 return ABIArgInfo::getIgnore();
396
397 // Expand structs with size <= 128-bits which consist only of
398 // basic types (int, long long, float, double, xxx*). This is
399 // non-recursive and does not ignore empty fields.
400 if (const RecordType *RT = Ty->getAsStructureType()) {
401 if (Context.getTypeSize(Ty) <= 4*32 &&
402 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
403 return ABIArgInfo::getExpand();
404 }
405
Eli Friedmana1e6de92009-06-13 21:37:10 +0000406 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, Context));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000407 } else {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000408 return (Ty->isPromotableIntegerType() ?
409 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000410 }
411}
412
413llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
414 CodeGenFunction &CGF) const {
415 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
416 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
417
418 CGBuilderTy &Builder = CGF.Builder;
419 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
420 "ap");
421 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
422 llvm::Type *PTy =
423 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
424 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
425
426 uint64_t Offset =
427 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
428 llvm::Value *NextAddr =
429 Builder.CreateGEP(Addr,
430 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
431 "ap.next");
432 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
433
434 return AddrTyped;
435}
436
437namespace {
438/// X86_64ABIInfo - The X86_64 ABI information.
439class X86_64ABIInfo : public ABIInfo {
440 enum Class {
441 Integer = 0,
442 SSE,
443 SSEUp,
444 X87,
445 X87Up,
446 ComplexX87,
447 NoClass,
448 Memory
449 };
450
451 /// merge - Implement the X86_64 ABI merging algorithm.
452 ///
453 /// Merge an accumulating classification \arg Accum with a field
454 /// classification \arg Field.
455 ///
456 /// \param Accum - The accumulating classification. This should
457 /// always be either NoClass or the result of a previous merge
458 /// call. In addition, this should never be Memory (the caller
459 /// should just return Memory for the aggregate).
460 Class merge(Class Accum, Class Field) const;
461
462 /// classify - Determine the x86_64 register classes in which the
463 /// given type T should be passed.
464 ///
465 /// \param Lo - The classification for the parts of the type
466 /// residing in the low word of the containing object.
467 ///
468 /// \param Hi - The classification for the parts of the type
469 /// residing in the high word of the containing object.
470 ///
471 /// \param OffsetBase - The bit offset of this type in the
472 /// containing object. Some parameters are classified different
473 /// depending on whether they straddle an eightbyte boundary.
474 ///
475 /// If a word is unused its result will be NoClass; if a type should
476 /// be passed in Memory then at least the classification of \arg Lo
477 /// will be Memory.
478 ///
479 /// The \arg Lo class will be NoClass iff the argument is ignored.
480 ///
481 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
482 /// also be ComplexX87.
483 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
484 Class &Lo, Class &Hi) const;
485
486 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
487 /// to coerce to, chose the best way to pass Ty in the same place
488 /// that \arg CoerceTo would be passed, but while keeping the
489 /// emitted code as simple as possible.
490 ///
491 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
492 /// the ways we might want to pass things, instead of constructing an LLVM
493 /// type. This makes this code more explicit, and it makes it clearer that we
494 /// are also doing this for correctness in the case of passing scalar types.
495 ABIArgInfo getCoerceResult(QualType Ty,
496 const llvm::Type *CoerceTo,
497 ASTContext &Context) const;
498
499 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
500 /// such that the argument will be passed in memory.
501 ABIArgInfo getIndirectResult(QualType Ty,
502 ASTContext &Context) const;
503
504 ABIArgInfo classifyReturnType(QualType RetTy,
505 ASTContext &Context) const;
506
507 ABIArgInfo classifyArgumentType(QualType Ty,
508 ASTContext &Context,
509 unsigned &neededInt,
510 unsigned &neededSSE) const;
511
512public:
513 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
514
515 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
516 CodeGenFunction &CGF) const;
517};
518}
519
520X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
521 Class Field) const {
522 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
523 // classified recursively so that always two fields are
524 // considered. The resulting class is calculated according to
525 // the classes of the fields in the eightbyte:
526 //
527 // (a) If both classes are equal, this is the resulting class.
528 //
529 // (b) If one of the classes is NO_CLASS, the resulting class is
530 // the other class.
531 //
532 // (c) If one of the classes is MEMORY, the result is the MEMORY
533 // class.
534 //
535 // (d) If one of the classes is INTEGER, the result is the
536 // INTEGER.
537 //
538 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
539 // MEMORY is used as class.
540 //
541 // (f) Otherwise class SSE is used.
542
543 // Accum should never be memory (we should have returned) or
544 // ComplexX87 (because this cannot be passed in a structure).
545 assert((Accum != Memory && Accum != ComplexX87) &&
546 "Invalid accumulated classification during merge.");
547 if (Accum == Field || Field == NoClass)
548 return Accum;
549 else if (Field == Memory)
550 return Memory;
551 else if (Accum == NoClass)
552 return Field;
553 else if (Accum == Integer || Field == Integer)
554 return Integer;
555 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
556 Accum == X87 || Accum == X87Up)
557 return Memory;
558 else
559 return SSE;
560}
561
562void X86_64ABIInfo::classify(QualType Ty,
563 ASTContext &Context,
564 uint64_t OffsetBase,
565 Class &Lo, Class &Hi) const {
566 // FIXME: This code can be simplified by introducing a simple value class for
567 // Class pairs with appropriate constructor methods for the various
568 // situations.
569
570 // FIXME: Some of the split computations are wrong; unaligned vectors
571 // shouldn't be passed in registers for example, so there is no chance they
572 // can straddle an eightbyte. Verify & simplify.
573
574 Lo = Hi = NoClass;
575
576 Class &Current = OffsetBase < 64 ? Lo : Hi;
577 Current = Memory;
578
579 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
580 BuiltinType::Kind k = BT->getKind();
581
582 if (k == BuiltinType::Void) {
583 Current = NoClass;
584 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
585 Lo = Integer;
586 Hi = Integer;
587 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
588 Current = Integer;
589 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
590 Current = SSE;
591 } else if (k == BuiltinType::LongDouble) {
592 Lo = X87;
593 Hi = X87Up;
594 }
595 // FIXME: _Decimal32 and _Decimal64 are SSE.
596 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
597 } else if (const EnumType *ET = Ty->getAsEnumType()) {
598 // Classify the underlying integer type.
599 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
600 } else if (Ty->hasPointerRepresentation()) {
601 Current = Integer;
602 } else if (const VectorType *VT = Ty->getAsVectorType()) {
603 uint64_t Size = Context.getTypeSize(VT);
604 if (Size == 32) {
605 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
606 // float> as integer.
607 Current = Integer;
608
609 // If this type crosses an eightbyte boundary, it should be
610 // split.
611 uint64_t EB_Real = (OffsetBase) / 64;
612 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
613 if (EB_Real != EB_Imag)
614 Hi = Lo;
615 } else if (Size == 64) {
616 // gcc passes <1 x double> in memory. :(
617 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
618 return;
619
620 // gcc passes <1 x long long> as INTEGER.
621 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
622 Current = Integer;
623 else
624 Current = SSE;
625
626 // If this type crosses an eightbyte boundary, it should be
627 // split.
628 if (OffsetBase && OffsetBase != 64)
629 Hi = Lo;
630 } else if (Size == 128) {
631 Lo = SSE;
632 Hi = SSEUp;
633 }
634 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
635 QualType ET = Context.getCanonicalType(CT->getElementType());
636
637 uint64_t Size = Context.getTypeSize(Ty);
638 if (ET->isIntegralType()) {
639 if (Size <= 64)
640 Current = Integer;
641 else if (Size <= 128)
642 Lo = Hi = Integer;
643 } else if (ET == Context.FloatTy)
644 Current = SSE;
645 else if (ET == Context.DoubleTy)
646 Lo = Hi = SSE;
647 else if (ET == Context.LongDoubleTy)
648 Current = ComplexX87;
649
650 // If this complex type crosses an eightbyte boundary then it
651 // should be split.
652 uint64_t EB_Real = (OffsetBase) / 64;
653 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
654 if (Hi == NoClass && EB_Real != EB_Imag)
655 Hi = Lo;
656 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
657 // Arrays are treated like structures.
658
659 uint64_t Size = Context.getTypeSize(Ty);
660
661 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
662 // than two eightbytes, ..., it has class MEMORY.
663 if (Size > 128)
664 return;
665
666 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
667 // fields, it has class MEMORY.
668 //
669 // Only need to check alignment of array base.
670 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
671 return;
672
673 // Otherwise implement simplified merge. We could be smarter about
674 // this, but it isn't worth it and would be harder to verify.
675 Current = NoClass;
676 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
677 uint64_t ArraySize = AT->getSize().getZExtValue();
678 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
679 Class FieldLo, FieldHi;
680 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
681 Lo = merge(Lo, FieldLo);
682 Hi = merge(Hi, FieldHi);
683 if (Lo == Memory || Hi == Memory)
684 break;
685 }
686
687 // Do post merger cleanup (see below). Only case we worry about is Memory.
688 if (Hi == Memory)
689 Lo = Memory;
690 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
691 } else if (const RecordType *RT = Ty->getAsRecordType()) {
692 uint64_t Size = Context.getTypeSize(Ty);
693
694 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
695 // than two eightbytes, ..., it has class MEMORY.
696 if (Size > 128)
697 return;
698
699 const RecordDecl *RD = RT->getDecl();
700
701 // Assume variable sized types are passed in memory.
702 if (RD->hasFlexibleArrayMember())
703 return;
704
705 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
706
707 // Reset Lo class, this will be recomputed.
708 Current = NoClass;
709 unsigned idx = 0;
710 for (RecordDecl::field_iterator i = RD->field_begin(Context),
711 e = RD->field_end(Context); i != e; ++i, ++idx) {
712 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
713 bool BitField = i->isBitField();
714
715 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
716 // fields, it has class MEMORY.
717 //
718 // Note, skip this test for bit-fields, see below.
719 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
720 Lo = Memory;
721 return;
722 }
723
724 // Classify this field.
725 //
726 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
727 // exceeds a single eightbyte, each is classified
728 // separately. Each eightbyte gets initialized to class
729 // NO_CLASS.
730 Class FieldLo, FieldHi;
731
732 // Bit-fields require special handling, they do not force the
733 // structure to be passed in memory even if unaligned, and
734 // therefore they can straddle an eightbyte.
735 if (BitField) {
736 // Ignore padding bit-fields.
737 if (i->isUnnamedBitfield())
738 continue;
739
740 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
741 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
742
743 uint64_t EB_Lo = Offset / 64;
744 uint64_t EB_Hi = (Offset + Size - 1) / 64;
745 FieldLo = FieldHi = NoClass;
746 if (EB_Lo) {
747 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
748 FieldLo = NoClass;
749 FieldHi = Integer;
750 } else {
751 FieldLo = Integer;
752 FieldHi = EB_Hi ? Integer : NoClass;
753 }
754 } else
755 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
756 Lo = merge(Lo, FieldLo);
757 Hi = merge(Hi, FieldHi);
758 if (Lo == Memory || Hi == Memory)
759 break;
760 }
761
762 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
763 //
764 // (a) If one of the classes is MEMORY, the whole argument is
765 // passed in memory.
766 //
767 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
768
769 // The first of these conditions is guaranteed by how we implement
770 // the merge (just bail).
771 //
772 // The second condition occurs in the case of unions; for example
773 // union { _Complex double; unsigned; }.
774 if (Hi == Memory)
775 Lo = Memory;
776 if (Hi == SSEUp && Lo != SSE)
777 Hi = SSE;
778 }
779}
780
781ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
782 const llvm::Type *CoerceTo,
783 ASTContext &Context) const {
784 if (CoerceTo == llvm::Type::Int64Ty) {
785 // Integer and pointer types will end up in a general purpose
786 // register.
787 if (Ty->isIntegralType() || Ty->isPointerType())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000788 return (Ty->isPromotableIntegerType() ?
789 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000790 } else if (CoerceTo == llvm::Type::DoubleTy) {
791 // FIXME: It would probably be better to make CGFunctionInfo only map using
792 // canonical types than to canonize here.
793 QualType CTy = Context.getCanonicalType(Ty);
794
795 // Float and double end up in a single SSE reg.
796 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
797 return ABIArgInfo::getDirect();
798
799 }
800
801 return ABIArgInfo::getCoerce(CoerceTo);
802}
803
804ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
805 ASTContext &Context) const {
806 // If this is a scalar LLVM value then assume LLVM will pass it in the right
807 // place naturally.
808 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000809 return (Ty->isPromotableIntegerType() ?
810 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000811
812 // FIXME: Set alignment correctly.
813 return ABIArgInfo::getIndirect(0);
814}
815
816ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
817 ASTContext &Context) const {
818 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
819 // classification algorithm.
820 X86_64ABIInfo::Class Lo, Hi;
821 classify(RetTy, Context, 0, Lo, Hi);
822
823 // Check some invariants.
824 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
825 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
826 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
827
828 const llvm::Type *ResType = 0;
829 switch (Lo) {
830 case NoClass:
831 return ABIArgInfo::getIgnore();
832
833 case SSEUp:
834 case X87Up:
835 assert(0 && "Invalid classification for lo word.");
836
837 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
838 // hidden argument.
839 case Memory:
840 return getIndirectResult(RetTy, Context);
841
842 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
843 // available register of the sequence %rax, %rdx is used.
844 case Integer:
845 ResType = llvm::Type::Int64Ty; break;
846
847 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
848 // available SSE register of the sequence %xmm0, %xmm1 is used.
849 case SSE:
850 ResType = llvm::Type::DoubleTy; break;
851
852 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
853 // returned on the X87 stack in %st0 as 80-bit x87 number.
854 case X87:
855 ResType = llvm::Type::X86_FP80Ty; break;
856
857 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
858 // part of the value is returned in %st0 and the imaginary part in
859 // %st1.
860 case ComplexX87:
861 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
862 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
863 llvm::Type::X86_FP80Ty,
864 NULL);
865 break;
866 }
867
868 switch (Hi) {
869 // Memory was handled previously and X87 should
870 // never occur as a hi class.
871 case Memory:
872 case X87:
873 assert(0 && "Invalid classification for hi word.");
874
875 case ComplexX87: // Previously handled.
876 case NoClass: break;
877
878 case Integer:
879 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
880 break;
881 case SSE:
882 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
883 break;
884
885 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
886 // is passed in the upper half of the last used SSE register.
887 //
888 // SSEUP should always be preceeded by SSE, just widen.
889 case SSEUp:
890 assert(Lo == SSE && "Unexpected SSEUp classification.");
891 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
892 break;
893
894 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
895 // returned together with the previous X87 value in %st0.
896 case X87Up:
897 // If X87Up is preceeded by X87, we don't need to do
898 // anything. However, in some cases with unions it may not be
899 // preceeded by X87. In such situations we follow gcc and pass the
900 // extra bits in an SSE reg.
901 if (Lo != X87)
902 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
903 break;
904 }
905
906 return getCoerceResult(RetTy, ResType, Context);
907}
908
909ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
910 unsigned &neededInt,
911 unsigned &neededSSE) const {
912 X86_64ABIInfo::Class Lo, Hi;
913 classify(Ty, Context, 0, Lo, Hi);
914
915 // Check some invariants.
916 // FIXME: Enforce these by construction.
917 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
918 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
919 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
920
921 neededInt = 0;
922 neededSSE = 0;
923 const llvm::Type *ResType = 0;
924 switch (Lo) {
925 case NoClass:
926 return ABIArgInfo::getIgnore();
927
928 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
929 // on the stack.
930 case Memory:
931
932 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
933 // COMPLEX_X87, it is passed in memory.
934 case X87:
935 case ComplexX87:
936 return getIndirectResult(Ty, Context);
937
938 case SSEUp:
939 case X87Up:
940 assert(0 && "Invalid classification for lo word.");
941
942 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
943 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
944 // and %r9 is used.
945 case Integer:
946 ++neededInt;
947 ResType = llvm::Type::Int64Ty;
948 break;
949
950 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
951 // available SSE register is used, the registers are taken in the
952 // order from %xmm0 to %xmm7.
953 case SSE:
954 ++neededSSE;
955 ResType = llvm::Type::DoubleTy;
956 break;
957 }
958
959 switch (Hi) {
960 // Memory was handled previously, ComplexX87 and X87 should
961 // never occur as hi classes, and X87Up must be preceed by X87,
962 // which is passed in memory.
963 case Memory:
964 case X87:
965 case ComplexX87:
966 assert(0 && "Invalid classification for hi word.");
967 break;
968
969 case NoClass: break;
970 case Integer:
971 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
972 ++neededInt;
973 break;
974
975 // X87Up generally doesn't occur here (long double is passed in
976 // memory), except in situations involving unions.
977 case X87Up:
978 case SSE:
979 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
980 ++neededSSE;
981 break;
982
983 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
984 // eightbyte is passed in the upper half of the last used SSE
985 // register.
986 case SSEUp:
987 assert(Lo == SSE && "Unexpected SSEUp classification.");
988 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
989 break;
990 }
991
992 return getCoerceResult(Ty, ResType, Context);
993}
994
995void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
996 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
997
998 // Keep track of the number of assigned registers.
999 unsigned freeIntRegs = 6, freeSSERegs = 8;
1000
1001 // If the return value is indirect, then the hidden argument is consuming one
1002 // integer register.
1003 if (FI.getReturnInfo().isIndirect())
1004 --freeIntRegs;
1005
1006 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1007 // get assigned (in left-to-right order) for passing as follows...
1008 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1009 it != ie; ++it) {
1010 unsigned neededInt, neededSSE;
1011 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
1012
1013 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1014 // eightbyte of an argument, the whole argument is passed on the
1015 // stack. If registers have already been assigned for some
1016 // eightbytes of such an argument, the assignments get reverted.
1017 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1018 freeIntRegs -= neededInt;
1019 freeSSERegs -= neededSSE;
1020 } else {
1021 it->info = getIndirectResult(it->type, Context);
1022 }
1023 }
1024}
1025
1026static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1027 QualType Ty,
1028 CodeGenFunction &CGF) {
1029 llvm::Value *overflow_arg_area_p =
1030 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1031 llvm::Value *overflow_arg_area =
1032 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1033
1034 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1035 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1036 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1037 if (Align > 8) {
1038 // Note that we follow the ABI & gcc here, even though the type
1039 // could in theory have an alignment greater than 16. This case
1040 // shouldn't ever matter in practice.
1041
1042 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1043 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
1044 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1045 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1046 llvm::Type::Int64Ty);
1047 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
1048 overflow_arg_area =
1049 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1050 overflow_arg_area->getType(),
1051 "overflow_arg_area.align");
1052 }
1053
1054 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1055 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1056 llvm::Value *Res =
1057 CGF.Builder.CreateBitCast(overflow_arg_area,
1058 llvm::PointerType::getUnqual(LTy));
1059
1060 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1061 // l->overflow_arg_area + sizeof(type).
1062 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1063 // an 8 byte boundary.
1064
1065 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1066 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1067 (SizeInBytes + 7) & ~7);
1068 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1069 "overflow_arg_area.next");
1070 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1071
1072 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1073 return Res;
1074}
1075
1076llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1077 CodeGenFunction &CGF) const {
1078 // Assume that va_list type is correct; should be pointer to LLVM type:
1079 // struct {
1080 // i32 gp_offset;
1081 // i32 fp_offset;
1082 // i8* overflow_arg_area;
1083 // i8* reg_save_area;
1084 // };
1085 unsigned neededInt, neededSSE;
1086 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1087 neededInt, neededSSE);
1088
1089 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1090 // in the registers. If not go to step 7.
1091 if (!neededInt && !neededSSE)
1092 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1093
1094 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1095 // general purpose registers needed to pass type and num_fp to hold
1096 // the number of floating point registers needed.
1097
1098 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1099 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1100 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1101 //
1102 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1103 // register save space).
1104
1105 llvm::Value *InRegs = 0;
1106 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1107 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1108 if (neededInt) {
1109 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1110 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1111 InRegs =
1112 CGF.Builder.CreateICmpULE(gp_offset,
1113 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1114 48 - neededInt * 8),
1115 "fits_in_gp");
1116 }
1117
1118 if (neededSSE) {
1119 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1120 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1121 llvm::Value *FitsInFP =
1122 CGF.Builder.CreateICmpULE(fp_offset,
1123 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1124 176 - neededSSE * 16),
1125 "fits_in_fp");
1126 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1127 }
1128
1129 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1130 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1131 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1132 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1133
1134 // Emit code to load the value if it was passed in registers.
1135
1136 CGF.EmitBlock(InRegBlock);
1137
1138 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1139 // an offset of l->gp_offset and/or l->fp_offset. This may require
1140 // copying to a temporary location in case the parameter is passed
1141 // in different register classes or requires an alignment greater
1142 // than 8 for general purpose registers and 16 for XMM registers.
1143 //
1144 // FIXME: This really results in shameful code when we end up needing to
1145 // collect arguments from different places; often what should result in a
1146 // simple assembling of a structure from scattered addresses has many more
1147 // loads than necessary. Can we clean this up?
1148 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1149 llvm::Value *RegAddr =
1150 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1151 "reg_save_area");
1152 if (neededInt && neededSSE) {
1153 // FIXME: Cleanup.
1154 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1155 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1156 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1157 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1158 const llvm::Type *TyLo = ST->getElementType(0);
1159 const llvm::Type *TyHi = ST->getElementType(1);
1160 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1161 "Unexpected ABI info for mixed regs");
1162 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1163 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1164 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1165 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1166 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1167 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1168 llvm::Value *V =
1169 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1170 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1171 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1172 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1173
1174 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
1175 } else if (neededInt) {
1176 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1177 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1178 llvm::PointerType::getUnqual(LTy));
1179 } else {
1180 if (neededSSE == 1) {
1181 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1182 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1183 llvm::PointerType::getUnqual(LTy));
1184 } else {
1185 assert(neededSSE == 2 && "Invalid number of needed registers!");
1186 // SSE registers are spaced 16 bytes apart in the register save
1187 // area, we need to collect the two eightbytes together.
1188 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1189 llvm::Value *RegAddrHi =
1190 CGF.Builder.CreateGEP(RegAddrLo,
1191 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1192 const llvm::Type *DblPtrTy =
1193 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1194 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1195 llvm::Type::DoubleTy,
1196 NULL);
1197 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1198 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1199 DblPtrTy));
1200 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1201 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1202 DblPtrTy));
1203 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1204 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1205 llvm::PointerType::getUnqual(LTy));
1206 }
1207 }
1208
1209 // AMD64-ABI 3.5.7p5: Step 5. Set:
1210 // l->gp_offset = l->gp_offset + num_gp * 8
1211 // l->fp_offset = l->fp_offset + num_fp * 16.
1212 if (neededInt) {
1213 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1214 neededInt * 8);
1215 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1216 gp_offset_p);
1217 }
1218 if (neededSSE) {
1219 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1220 neededSSE * 16);
1221 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1222 fp_offset_p);
1223 }
1224 CGF.EmitBranch(ContBlock);
1225
1226 // Emit code to load the value if it was passed in memory.
1227
1228 CGF.EmitBlock(InMemBlock);
1229 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1230
1231 // Return the appropriate result.
1232
1233 CGF.EmitBlock(ContBlock);
1234 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1235 "vaarg.addr");
1236 ResAddr->reserveOperandSpace(2);
1237 ResAddr->addIncoming(RegAddr, InRegBlock);
1238 ResAddr->addIncoming(MemAddr, InMemBlock);
1239
1240 return ResAddr;
1241}
1242
1243// ABI Info for PIC16
1244class PIC16ABIInfo : public ABIInfo {
1245 ABIArgInfo classifyReturnType(QualType RetTy,
1246 ASTContext &Context) const;
1247
1248 ABIArgInfo classifyArgumentType(QualType RetTy,
1249 ASTContext &Context) const;
1250
1251 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1252 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1253 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1254 it != ie; ++it)
1255 it->info = classifyArgumentType(it->type, Context);
1256 }
1257
1258 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1259 CodeGenFunction &CGF) const;
1260
1261};
1262
1263ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1264 ASTContext &Context) const {
1265 if (RetTy->isVoidType()) {
1266 return ABIArgInfo::getIgnore();
1267 } else {
1268 return ABIArgInfo::getDirect();
1269 }
1270}
1271
1272ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1273 ASTContext &Context) const {
1274 return ABIArgInfo::getDirect();
1275}
1276
1277llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1278 CodeGenFunction &CGF) const {
1279 return 0;
1280}
1281
1282class ARMABIInfo : public ABIInfo {
1283 ABIArgInfo classifyReturnType(QualType RetTy,
1284 ASTContext &Context) const;
1285
1286 ABIArgInfo classifyArgumentType(QualType RetTy,
1287 ASTContext &Context) const;
1288
1289 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
1290
1291 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1292 CodeGenFunction &CGF) const;
1293};
1294
1295void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1296 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1297 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1298 it != ie; ++it) {
1299 it->info = classifyArgumentType(it->type, Context);
1300 }
1301}
1302
1303ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1304 ASTContext &Context) const {
1305 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001306 return (Ty->isPromotableIntegerType() ?
1307 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001308 }
1309 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1310 // backend doesn't support byval.
1311 // FIXME: This doesn't handle alignment > 64 bits.
1312 const llvm::Type* ElemTy;
1313 unsigned SizeRegs;
1314 if (Context.getTypeAlign(Ty) > 32) {
1315 ElemTy = llvm::Type::Int64Ty;
1316 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1317 } else {
1318 ElemTy = llvm::Type::Int32Ty;
1319 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1320 }
1321 std::vector<const llvm::Type*> LLVMFields;
1322 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1323 const llvm::Type* STy = llvm::StructType::get(LLVMFields, true);
1324 return ABIArgInfo::getCoerce(STy);
1325}
1326
1327ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1328 ASTContext &Context) const {
1329 if (RetTy->isVoidType()) {
1330 return ABIArgInfo::getIgnore();
1331 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1332 // Aggregates <= 4 bytes are returned in r0; other aggregates
1333 // are returned indirectly.
1334 uint64_t Size = Context.getTypeSize(RetTy);
1335 if (Size <= 32)
1336 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
1337 return ABIArgInfo::getIndirect(0);
1338 } else {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001339 return (RetTy->isPromotableIntegerType() ?
1340 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001341 }
1342}
1343
1344llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1345 CodeGenFunction &CGF) const {
1346 // FIXME: Need to handle alignment
1347 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1348 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1349
1350 CGBuilderTy &Builder = CGF.Builder;
1351 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1352 "ap");
1353 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1354 llvm::Type *PTy =
1355 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1356 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1357
1358 uint64_t Offset =
1359 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1360 llvm::Value *NextAddr =
1361 Builder.CreateGEP(Addr,
1362 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
1363 "ap.next");
1364 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1365
1366 return AddrTyped;
1367}
1368
1369ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1370 ASTContext &Context) const {
1371 if (RetTy->isVoidType()) {
1372 return ABIArgInfo::getIgnore();
1373 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1374 return ABIArgInfo::getIndirect(0);
1375 } else {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001376 return (RetTy->isPromotableIntegerType() ?
1377 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001378 }
1379}
1380
1381ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
1382 ASTContext &Context) const {
1383 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1384 return ABIArgInfo::getIndirect(0);
1385 } else {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001386 return (Ty->isPromotableIntegerType() ?
1387 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001388 }
1389}
1390
1391llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1392 CodeGenFunction &CGF) const {
1393 return 0;
1394}
1395
1396const ABIInfo &CodeGenTypes::getABIInfo() const {
1397 if (TheABIInfo)
1398 return *TheABIInfo;
1399
1400 // For now we just cache this in the CodeGenTypes and don't bother
1401 // to free it.
1402 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1403 if (strcmp(TargetPrefix, "x86") == 0) {
1404 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
1405 switch (getContext().Target.getPointerWidth(0)) {
1406 case 32:
1407 return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin));
1408 case 64:
1409 return *(TheABIInfo = new X86_64ABIInfo());
1410 }
1411 } else if (strcmp(TargetPrefix, "arm") == 0) {
1412 // FIXME: Support for OABI?
1413 return *(TheABIInfo = new ARMABIInfo());
1414 } else if (strcmp(TargetPrefix, "pic16") == 0) {
1415 return *(TheABIInfo = new PIC16ABIInfo());
1416 }
1417
1418 return *(TheABIInfo = new DefaultABIInfo);
1419}