blob: ce98f8c25699a3aae29c091d500cf1f02b571689 [file] [log] [blame]
Daniel Dunbara8f02052008-09-08 21:33:45 +00001//===----- CGCall.h - Encapsulate calling convention 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 "CGCall.h"
16#include "CodeGenFunction.h"
Daniel Dunbar3ef2e852008-09-10 00:41:16 +000017#include "CodeGenModule.h"
Daniel Dunbarf98eeff2008-10-13 17:02:26 +000018#include "clang/Basic/TargetInfo.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
Anders Carlsson7a785352009-04-03 22:48:58 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000022#include "clang/AST/DeclObjC.h"
Daniel Dunbar51a2d192009-01-29 08:13:58 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbar04d35782008-09-17 00:51:38 +000024#include "llvm/ADT/StringExtras.h"
Devang Patel98bfe502008-09-24 01:01:36 +000025#include "llvm/Attributes.h"
Daniel Dunbar90e43452009-03-02 04:32:35 +000026#include "llvm/Support/CallSite.h"
Daniel Dunbar3cfcec72009-02-12 09:04:14 +000027#include "llvm/Support/MathExtras.h"
Daniel Dunbar708d8a82009-01-27 01:36:03 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbard283e632009-02-03 01:05:53 +000029
30#include "ABIInfo.h"
31
Daniel Dunbara8f02052008-09-08 21:33:45 +000032using namespace clang;
33using namespace CodeGen;
34
35/***/
36
Daniel Dunbara8f02052008-09-08 21:33:45 +000037// FIXME: Use iterator and sidestep silly type array creation.
38
Daniel Dunbar34bda882009-02-02 23:23:47 +000039const
Douglas Gregor4fa58902009-02-26 23:50:07 +000040CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) {
Daniel Dunbar34bda882009-02-02 23:23:47 +000041 return getFunctionInfo(FTNP->getResultType(),
42 llvm::SmallVector<QualType, 16>());
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000043}
44
Daniel Dunbar34bda882009-02-02 23:23:47 +000045const
Douglas Gregor4fa58902009-02-26 23:50:07 +000046CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) {
Daniel Dunbar34bda882009-02-02 23:23:47 +000047 llvm::SmallVector<QualType, 16> ArgTys;
48 // FIXME: Kill copy.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000049 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000050 ArgTys.push_back(FTP->getArgType(i));
51 return getFunctionInfo(FTP->getResultType(), ArgTys);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000052}
53
Anders Carlsson7a785352009-04-03 22:48:58 +000054const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
55 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerd36c9d52009-05-12 20:27:19 +000056 // Add the 'this' pointer unless this is a static method.
57 if (MD->isInstance())
58 ArgTys.push_back(MD->getThisType(Context));
Anders Carlsson7a785352009-04-03 22:48:58 +000059
60 const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType();
61 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
62 ArgTys.push_back(FTP->getArgType(i));
63 return getFunctionInfo(FTP->getResultType(), ArgTys);
64}
65
Daniel Dunbar34bda882009-02-02 23:23:47 +000066const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Chris Lattnerd36c9d52009-05-12 20:27:19 +000067 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlsson7a785352009-04-03 22:48:58 +000068 if (MD->isInstance())
69 return getFunctionInfo(MD);
Anders Carlsson7a785352009-04-03 22:48:58 +000070
Daniel Dunbara8f02052008-09-08 21:33:45 +000071 const FunctionType *FTy = FD->getType()->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +000072 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy))
Daniel Dunbar34bda882009-02-02 23:23:47 +000073 return getFunctionInfo(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +000074 return getFunctionInfo(cast<FunctionNoProtoType>(FTy));
Daniel Dunbara8f02052008-09-08 21:33:45 +000075}
76
Daniel Dunbar34bda882009-02-02 23:23:47 +000077const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
78 llvm::SmallVector<QualType, 16> ArgTys;
79 ArgTys.push_back(MD->getSelfDecl()->getType());
80 ArgTys.push_back(Context.getObjCSelType());
81 // FIXME: Kill copy?
Chris Lattner9408eb12009-02-20 06:23:21 +000082 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
Daniel Dunbara8f02052008-09-08 21:33:45 +000083 e = MD->param_end(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000084 ArgTys.push_back((*i)->getType());
85 return getFunctionInfo(MD->getResultType(), ArgTys);
Daniel Dunbara8f02052008-09-08 21:33:45 +000086}
87
Daniel Dunbar34bda882009-02-02 23:23:47 +000088const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
89 const CallArgList &Args) {
90 // FIXME: Kill copy.
91 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000092 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
93 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000094 ArgTys.push_back(i->second);
95 return getFunctionInfo(ResTy, ArgTys);
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000096}
97
Daniel Dunbar34bda882009-02-02 23:23:47 +000098const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
99 const FunctionArgList &Args) {
100 // FIXME: Kill copy.
101 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbar9fc15a82009-02-02 21:43:58 +0000102 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
103 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +0000104 ArgTys.push_back(i->second);
105 return getFunctionInfo(ResTy, ArgTys);
106}
107
108const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
109 const llvm::SmallVector<QualType, 16> &ArgTys) {
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000110 // Lookup or create unique function info.
111 llvm::FoldingSetNodeID ID;
112 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end());
113
114 void *InsertPos = 0;
115 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
116 if (FI)
117 return *FI;
118
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000119 // Construct the function info.
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000120 FI = new CGFunctionInfo(ResTy, ArgTys);
Daniel Dunbarb944cc92009-02-05 00:00:23 +0000121 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000122
123 // Compute ABI information.
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000124 getABIInfo().computeInfo(*FI, getContext());
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000125
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000126 return *FI;
Daniel Dunbar34bda882009-02-02 23:23:47 +0000127}
128
129/***/
130
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000131ABIInfo::~ABIInfo() {}
132
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000133void ABIArgInfo::dump() const {
134 fprintf(stderr, "(ABIArgInfo Kind=");
135 switch (TheKind) {
136 case Direct:
137 fprintf(stderr, "Direct");
138 break;
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000139 case Ignore:
140 fprintf(stderr, "Ignore");
141 break;
142 case Coerce:
143 fprintf(stderr, "Coerce Type=");
144 getCoerceToType()->print(llvm::errs());
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000145 break;
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000146 case Indirect:
147 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000148 break;
149 case Expand:
150 fprintf(stderr, "Expand");
151 break;
152 }
153 fprintf(stderr, ")\n");
154}
155
156/***/
157
Daniel Dunbar8ac59ae2009-05-11 18:58:49 +0000158static bool isEmptyRecord(ASTContext &Context, QualType T);
159
160/// isEmptyField - Return true iff a the field is "empty", that is it
161/// is an unnamed bit-field or an (array of) empty record(s).
162static bool isEmptyField(ASTContext &Context, const FieldDecl *FD) {
163 if (FD->isUnnamedBitfield())
164 return true;
165
166 QualType FT = FD->getType();
Daniel Dunbar46bf0102009-05-11 23:01:34 +0000167 // Constant arrays of empty records count as empty, strip them off.
168 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
169 FT = AT->getElementType();
Daniel Dunbar8ac59ae2009-05-11 18:58:49 +0000170
171 return isEmptyRecord(Context, FT);
172}
173
174/// isEmptyRecord - Return true iff a structure contains only empty
175/// fields. Note that a structure with a flexible array member is not
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000176/// considered empty.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000177static bool isEmptyRecord(ASTContext &Context, QualType T) {
Daniel Dunbara7446422009-03-31 19:01:39 +0000178 const RecordType *RT = T->getAsRecordType();
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000179 if (!RT)
180 return 0;
181 const RecordDecl *RD = RT->getDecl();
182 if (RD->hasFlexibleArrayMember())
183 return false;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000184 for (RecordDecl::field_iterator i = RD->field_begin(Context),
Daniel Dunbar8ac59ae2009-05-11 18:58:49 +0000185 e = RD->field_end(Context); i != e; ++i)
186 if (!isEmptyField(Context, *i))
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000187 return false;
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000188 return true;
189}
190
191/// isSingleElementStruct - Determine if a structure is a "single
192/// element struct", i.e. it has exactly one non-empty field or
193/// exactly one field which is itself a single element
194/// struct. Structures with flexible array members are never
195/// considered single element structs.
196///
197/// \return The field declaration for the single non-empty field, if
198/// it exists.
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000199static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000200 const RecordType *RT = T->getAsStructureType();
201 if (!RT)
202 return 0;
203
204 const RecordDecl *RD = RT->getDecl();
205 if (RD->hasFlexibleArrayMember())
206 return 0;
207
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000208 const Type *Found = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000209 for (RecordDecl::field_iterator i = RD->field_begin(Context),
210 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000211 const FieldDecl *FD = *i;
212 QualType FT = FD->getType();
213
Daniel Dunbar8ac59ae2009-05-11 18:58:49 +0000214 // Ignore empty fields.
215 if (isEmptyField(Context, FD))
216 continue;
217
Daniel Dunbar46bf0102009-05-11 23:01:34 +0000218 // If we already found an element then this isn't a single-element
219 // struct.
Daniel Dunbar6f3d7602009-05-08 21:04:47 +0000220 if (Found)
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000221 return 0;
Daniel Dunbar6f3d7602009-05-08 21:04:47 +0000222
Daniel Dunbar46bf0102009-05-11 23:01:34 +0000223 // Treat single element arrays as the element.
224 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
225 if (AT->getSize().getZExtValue() != 1)
226 break;
227 FT = AT->getElementType();
228 }
229
Daniel Dunbar6f3d7602009-05-08 21:04:47 +0000230 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000231 Found = FT.getTypePtr();
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000232 } else {
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000233 Found = isSingleElementStruct(FT, Context);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000234 if (!Found)
235 return 0;
236 }
237 }
238
239 return Found;
240}
241
242static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
243 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
244 return false;
245
246 uint64_t Size = Context.getTypeSize(Ty);
247 return Size == 32 || Size == 64;
248}
249
250static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
251 ASTContext &Context) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000252 for (RecordDecl::field_iterator i = RD->field_begin(Context),
253 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000254 const FieldDecl *FD = *i;
255
256 if (!is32Or64BitBasicType(FD->getType(), Context))
257 return false;
258
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000259 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
260 // how to expand them yet, and the predicate for telling if a bitfield still
261 // counts as "basic" is more complicated than what we were doing previously.
Daniel Dunbar9f052cb2009-03-11 22:05:26 +0000262 if (FD->isBitField())
263 return false;
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000264 }
Daniel Dunbar9f052cb2009-03-11 22:05:26 +0000265
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000266 return true;
267}
268
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000269namespace {
270/// DefaultABIInfo - The default implementation for ABI specific
271/// details. This implementation provides information which results in
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000272/// self-consistent and sensible LLVM IR generation, but does not
273/// conform to any particular ABI.
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000274class DefaultABIInfo : public ABIInfo {
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000275 ABIArgInfo classifyReturnType(QualType RetTy,
276 ASTContext &Context) const;
277
278 ABIArgInfo classifyArgumentType(QualType RetTy,
279 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000280
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000281 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
282 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
283 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
284 it != ie; ++it)
285 it->info = classifyArgumentType(it->type, Context);
286 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000287
288 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
289 CodeGenFunction &CGF) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000290};
291
292/// X86_32ABIInfo - The X86-32 ABI information.
293class X86_32ABIInfo : public ABIInfo {
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000294 ASTContext &Context;
Eli Friedman5e175802009-03-23 23:26:24 +0000295 bool IsDarwin;
296
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000297 static bool isRegisterSize(unsigned Size) {
298 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
299 }
300
Daniel Dunbar558e7fb2009-04-01 07:45:00 +0000301 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
302
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000303public:
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000304 ABIArgInfo classifyReturnType(QualType RetTy,
305 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000306
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000307 ABIArgInfo classifyArgumentType(QualType RetTy,
308 ASTContext &Context) const;
309
310 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
311 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
312 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
313 it != ie; ++it)
314 it->info = classifyArgumentType(it->type, Context);
315 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000316
317 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
318 CodeGenFunction &CGF) const;
Eli Friedman5e175802009-03-23 23:26:24 +0000319
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000320 X86_32ABIInfo(ASTContext &Context, bool d)
321 : ABIInfo(), Context(Context), IsDarwin(d) {}
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000322};
323}
324
Daniel Dunbar558e7fb2009-04-01 07:45:00 +0000325
326/// shouldReturnTypeInRegister - Determine if the given type should be
327/// passed in a register (for the Darwin ABI).
328bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
329 ASTContext &Context) {
330 uint64_t Size = Context.getTypeSize(Ty);
331
332 // Type must be register sized.
333 if (!isRegisterSize(Size))
334 return false;
335
336 if (Ty->isVectorType()) {
337 // 64- and 128- bit vectors inside structures are not returned in
338 // registers.
339 if (Size == 64 || Size == 128)
340 return false;
341
342 return true;
343 }
344
345 // If this is a builtin, pointer, or complex type, it is ok.
346 if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType())
347 return true;
348
349 // Arrays are treated like records.
350 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
351 return shouldReturnTypeInRegister(AT->getElementType(), Context);
352
353 // Otherwise, it must be a record type.
354 const RecordType *RT = Ty->getAsRecordType();
355 if (!RT) return false;
356
357 // Structure types are passed in register if all fields would be
358 // passed in a register.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000359 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context),
360 e = RT->getDecl()->field_end(Context); i != e; ++i) {
Daniel Dunbar558e7fb2009-04-01 07:45:00 +0000361 const FieldDecl *FD = *i;
362
Daniel Dunbar8ac59ae2009-05-11 18:58:49 +0000363 // Empty fields are ignored.
364 if (isEmptyField(Context, FD))
Daniel Dunbar558e7fb2009-04-01 07:45:00 +0000365 continue;
366
367 // Check fields recursively.
368 if (!shouldReturnTypeInRegister(FD->getType(), Context))
369 return false;
370 }
371
372 return true;
373}
374
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000375ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
376 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +0000377 if (RetTy->isVoidType()) {
378 return ABIArgInfo::getIgnore();
Daniel Dunbar2a7bb3f2009-04-01 06:13:08 +0000379 } else if (const VectorType *VT = RetTy->getAsVectorType()) {
380 // On Darwin, some vectors are returned in registers.
381 if (IsDarwin) {
382 uint64_t Size = Context.getTypeSize(RetTy);
383
384 // 128-bit vectors are a special case; they are returned in
385 // registers and we need to make sure to pick a type the LLVM
386 // backend will like.
387 if (Size == 128)
388 return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty,
389 2));
390
391 // Always return in register if it fits in a general purpose
392 // register, or if it is 64 bits and has a single element.
393 if ((Size == 8 || Size == 16 || Size == 32) ||
394 (Size == 64 && VT->getNumElements() == 1))
395 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
396
397 return ABIArgInfo::getIndirect(0);
398 }
399
400 return ABIArgInfo::getDirect();
Daniel Dunbareec02622009-02-03 06:30:17 +0000401 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbaref495d42009-04-27 18:31:32 +0000402 // Structures with flexible arrays are always indirect.
403 if (const RecordType *RT = RetTy->getAsStructureType())
404 if (RT->getDecl()->hasFlexibleArrayMember())
405 return ABIArgInfo::getIndirect(0);
406
Eli Friedman5e175802009-03-23 23:26:24 +0000407 // Outside of Darwin, structs and unions are always indirect.
408 if (!IsDarwin && !RetTy->isAnyComplexType())
409 return ABIArgInfo::getIndirect(0);
Daniel Dunbaref495d42009-04-27 18:31:32 +0000410
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000411 // Classify "single element" structs as their element type.
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000412 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000413 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000414 if (BT->isIntegerType()) {
Daniel Dunbar9f4a5a42009-05-08 21:30:11 +0000415 // We need to use the size of the structure, padding
416 // bit-fields can adjust that to be larger than the single
417 // element type.
418 uint64_t Size = Context.getTypeSize(RetTy);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000419 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
420 } else if (BT->getKind() == BuiltinType::Float) {
Daniel Dunbar9f4a5a42009-05-08 21:30:11 +0000421 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
422 "Unexpect single element structure size!");
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000423 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
424 } else if (BT->getKind() == BuiltinType::Double) {
Daniel Dunbar9f4a5a42009-05-08 21:30:11 +0000425 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
426 "Unexpect single element structure size!");
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000427 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
428 }
429 } else if (SeltTy->isPointerType()) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000430 // FIXME: It would be really nice if this could come out as the proper
431 // pointer type.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000432 llvm::Type *PtrTy =
433 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
434 return ABIArgInfo::getCoerce(PtrTy);
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000435 } else if (SeltTy->isVectorType()) {
436 // 64- and 128-bit vectors are never returned in a
437 // register when inside a structure.
438 uint64_t Size = Context.getTypeSize(RetTy);
439 if (Size == 64 || Size == 128)
440 return ABIArgInfo::getIndirect(0);
441
442 return classifyReturnType(QualType(SeltTy, 0), Context);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000443 }
444 }
445
Daniel Dunbar0e727132009-05-12 17:00:20 +0000446 // Small structures which are register sized are generally returned
447 // in a register.
448 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
449 uint64_t Size = Context.getTypeSize(RetTy);
450 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
Daniel Dunbar558e7fb2009-04-01 07:45:00 +0000451 }
Daniel Dunbar49b32d42009-04-01 07:08:38 +0000452
453 return ABIArgInfo::getIndirect(0);
Daniel Dunbare126ab12008-09-10 02:41:04 +0000454 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000455 return ABIArgInfo::getDirect();
Daniel Dunbare126ab12008-09-10 02:41:04 +0000456 }
457}
458
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000459ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000460 ASTContext &Context) const {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000461 // FIXME: Set alignment on indirect arguments.
Daniel Dunbar3158c592008-09-17 20:11:04 +0000462 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000463 // Structures with flexible arrays are always indirect.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000464 if (const RecordType *RT = Ty->getAsStructureType())
465 if (RT->getDecl()->hasFlexibleArrayMember())
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000466 return ABIArgInfo::getIndirect(0);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000467
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000468 // Ignore empty structs.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000469 uint64_t Size = Context.getTypeSize(Ty);
470 if (Ty->isStructureType() && Size == 0)
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000471 return ABIArgInfo::getIgnore();
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000472
473 // Expand structs with size <= 128-bits which consist only of
474 // basic types (int, long long, float, double, xxx*). This is
475 // non-recursive and does not ignore empty fields.
476 if (const RecordType *RT = Ty->getAsStructureType()) {
477 if (Context.getTypeSize(Ty) <= 4*32 &&
478 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
479 return ABIArgInfo::getExpand();
480 }
481
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000482 return ABIArgInfo::getIndirect(0);
Daniel Dunbar22e30052008-09-11 01:48:57 +0000483 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000484 return ABIArgInfo::getDirect();
Daniel Dunbar22e30052008-09-11 01:48:57 +0000485 }
486}
487
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000488llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
489 CodeGenFunction &CGF) const {
490 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
491 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
492
493 CGBuilderTy &Builder = CGF.Builder;
494 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
495 "ap");
496 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
497 llvm::Type *PTy =
498 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
499 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
500
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000501 uint64_t Offset =
502 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000503 llvm::Value *NextAddr =
504 Builder.CreateGEP(Addr,
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000505 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000506 "ap.next");
507 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
508
509 return AddrTyped;
510}
511
Daniel Dunbare09a9692009-01-24 08:32:22 +0000512namespace {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000513/// X86_64ABIInfo - The X86_64 ABI information.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000514class X86_64ABIInfo : public ABIInfo {
515 enum Class {
516 Integer = 0,
517 SSE,
518 SSEUp,
519 X87,
520 X87Up,
521 ComplexX87,
522 NoClass,
523 Memory
524 };
525
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000526 /// merge - Implement the X86_64 ABI merging algorithm.
527 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000528 /// Merge an accumulating classification \arg Accum with a field
529 /// classification \arg Field.
530 ///
531 /// \param Accum - The accumulating classification. This should
532 /// always be either NoClass or the result of a previous merge
533 /// call. In addition, this should never be Memory (the caller
534 /// should just return Memory for the aggregate).
535 Class merge(Class Accum, Class Field) const;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000536
Daniel Dunbare09a9692009-01-24 08:32:22 +0000537 /// classify - Determine the x86_64 register classes in which the
538 /// given type T should be passed.
539 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000540 /// \param Lo - The classification for the parts of the type
541 /// residing in the low word of the containing object.
542 ///
543 /// \param Hi - The classification for the parts of the type
544 /// residing in the high word of the containing object.
545 ///
546 /// \param OffsetBase - The bit offset of this type in the
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000547 /// containing object. Some parameters are classified different
548 /// depending on whether they straddle an eightbyte boundary.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000549 ///
550 /// If a word is unused its result will be NoClass; if a type should
551 /// be passed in Memory then at least the classification of \arg Lo
552 /// will be Memory.
553 ///
554 /// The \arg Lo class will be NoClass iff the argument is ignored.
555 ///
556 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
Daniel Dunbar92e88642009-02-17 07:55:55 +0000557 /// also be ComplexX87.
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000558 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000559 Class &Lo, Class &Hi) const;
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000560
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000561 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
562 /// to coerce to, chose the best way to pass Ty in the same place
563 /// that \arg CoerceTo would be passed, but while keeping the
564 /// emitted code as simple as possible.
565 ///
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000566 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
567 /// the ways we might want to pass things, instead of constructing an LLVM
568 /// type. This makes this code more explicit, and it makes it clearer that we
569 /// are also doing this for correctness in the case of passing scalar types.
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000570 ABIArgInfo getCoerceResult(QualType Ty,
571 const llvm::Type *CoerceTo,
572 ASTContext &Context) const;
573
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000574 ABIArgInfo classifyReturnType(QualType RetTy,
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000575 ASTContext &Context) const;
576
577 ABIArgInfo classifyArgumentType(QualType Ty,
578 ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000579 unsigned &neededInt,
580 unsigned &neededSSE) const;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000581
582public:
583 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000584
585 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
586 CodeGenFunction &CGF) const;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000587};
588}
589
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000590X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
591 Class Field) const {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000592 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
593 // classified recursively so that always two fields are
594 // considered. The resulting class is calculated according to
595 // the classes of the fields in the eightbyte:
596 //
597 // (a) If both classes are equal, this is the resulting class.
598 //
599 // (b) If one of the classes is NO_CLASS, the resulting class is
600 // the other class.
601 //
602 // (c) If one of the classes is MEMORY, the result is the MEMORY
603 // class.
604 //
605 // (d) If one of the classes is INTEGER, the result is the
606 // INTEGER.
607 //
608 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
609 // MEMORY is used as class.
610 //
611 // (f) Otherwise class SSE is used.
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000612
613 // Accum should never be memory (we should have returned) or
614 // ComplexX87 (because this cannot be passed in a structure).
615 assert((Accum != Memory && Accum != ComplexX87) &&
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000616 "Invalid accumulated classification during merge.");
617 if (Accum == Field || Field == NoClass)
618 return Accum;
619 else if (Field == Memory)
620 return Memory;
621 else if (Accum == NoClass)
622 return Field;
623 else if (Accum == Integer || Field == Integer)
624 return Integer;
Daniel Dunbar647e30f2009-05-12 15:22:40 +0000625 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
626 Accum == X87 || Accum == X87Up)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000627 return Memory;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000628 else
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000629 return SSE;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000630}
631
Daniel Dunbare09a9692009-01-24 08:32:22 +0000632void X86_64ABIInfo::classify(QualType Ty,
633 ASTContext &Context,
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000634 uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000635 Class &Lo, Class &Hi) const {
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000636 // FIXME: This code can be simplified by introducing a simple value class for
637 // Class pairs with appropriate constructor methods for the various
638 // situations.
Daniel Dunbar36b378e2009-02-02 18:06:39 +0000639
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000640 // FIXME: Some of the split computations are wrong; unaligned vectors
641 // shouldn't be passed in registers for example, so there is no chance they
642 // can straddle an eightbyte. Verify & simplify.
Daniel Dunbard97f5952009-02-22 04:48:22 +0000643
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000644 Lo = Hi = NoClass;
645
646 Class &Current = OffsetBase < 64 ? Lo : Hi;
647 Current = Memory;
648
Daniel Dunbare09a9692009-01-24 08:32:22 +0000649 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
650 BuiltinType::Kind k = BT->getKind();
651
Daniel Dunbar1358b202009-01-26 21:26:08 +0000652 if (k == BuiltinType::Void) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000653 Current = NoClass;
Chris Lattner6cc7e412009-04-30 02:43:43 +0000654 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
Chris Lattner3d8e0682009-04-30 06:22:07 +0000655 Lo = Integer;
656 Hi = Integer;
Daniel Dunbar1358b202009-01-26 21:26:08 +0000657 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000658 Current = Integer;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000659 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000660 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000661 } else if (k == BuiltinType::LongDouble) {
662 Lo = X87;
663 Hi = X87Up;
664 }
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000665 // FIXME: _Decimal32 and _Decimal64 are SSE.
666 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Anders Carlsson1d234462009-02-26 17:31:15 +0000667 } else if (const EnumType *ET = Ty->getAsEnumType()) {
668 // Classify the underlying integer type.
669 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
Daniel Dunbarfc096bf2009-02-26 20:52:22 +0000670 } else if (Ty->hasPointerRepresentation()) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000671 Current = Integer;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000672 } else if (const VectorType *VT = Ty->getAsVectorType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000673 uint64_t Size = Context.getTypeSize(VT);
Daniel Dunbard97f5952009-02-22 04:48:22 +0000674 if (Size == 32) {
675 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
676 // float> as integer.
677 Current = Integer;
678
679 // If this type crosses an eightbyte boundary, it should be
680 // split.
681 uint64_t EB_Real = (OffsetBase) / 64;
682 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
683 if (EB_Real != EB_Imag)
684 Hi = Lo;
685 } else if (Size == 64) {
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000686 // gcc passes <1 x double> in memory. :(
687 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
Daniel Dunbarcdf91e82009-01-30 19:38:39 +0000688 return;
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000689
690 // gcc passes <1 x long long> as INTEGER.
691 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
692 Current = Integer;
693 else
694 Current = SSE;
Daniel Dunbare413f532009-01-30 18:40:10 +0000695
696 // If this type crosses an eightbyte boundary, it should be
697 // split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000698 if (OffsetBase && OffsetBase != 64)
Daniel Dunbare413f532009-01-30 18:40:10 +0000699 Hi = Lo;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000700 } else if (Size == 128) {
701 Lo = SSE;
702 Hi = SSEUp;
703 }
Daniel Dunbare09a9692009-01-24 08:32:22 +0000704 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
Daniel Dunbare60d5332009-02-14 02:45:45 +0000705 QualType ET = Context.getCanonicalType(CT->getElementType());
Daniel Dunbare09a9692009-01-24 08:32:22 +0000706
Daniel Dunbare413f532009-01-30 18:40:10 +0000707 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000708 if (ET->isIntegralType()) {
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000709 if (Size <= 64)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000710 Current = Integer;
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000711 else if (Size <= 128)
712 Lo = Hi = Integer;
713 } else if (ET == Context.FloatTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000714 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000715 else if (ET == Context.DoubleTy)
716 Lo = Hi = SSE;
717 else if (ET == Context.LongDoubleTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000718 Current = ComplexX87;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000719
720 // If this complex type crosses an eightbyte boundary then it
721 // should be split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000722 uint64_t EB_Real = (OffsetBase) / 64;
723 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000724 if (Hi == NoClass && EB_Real != EB_Imag)
725 Hi = Lo;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000726 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
727 // Arrays are treated like structures.
728
729 uint64_t Size = Context.getTypeSize(Ty);
730
731 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
732 // than two eightbytes, ..., it has class MEMORY.
733 if (Size > 128)
734 return;
735
736 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
737 // fields, it has class MEMORY.
738 //
739 // Only need to check alignment of array base.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000740 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000741 return;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000742
743 // Otherwise implement simplified merge. We could be smarter about
744 // this, but it isn't worth it and would be harder to verify.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000745 Current = NoClass;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000746 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
747 uint64_t ArraySize = AT->getSize().getZExtValue();
748 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
749 Class FieldLo, FieldHi;
750 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000751 Lo = merge(Lo, FieldLo);
752 Hi = merge(Hi, FieldHi);
753 if (Lo == Memory || Hi == Memory)
754 break;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000755 }
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000756
757 // Do post merger cleanup (see below). Only case we worry about is Memory.
758 if (Hi == Memory)
759 Lo = Memory;
760 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000761 } else if (const RecordType *RT = Ty->getAsRecordType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000762 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000763
764 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
765 // than two eightbytes, ..., it has class MEMORY.
766 if (Size > 128)
767 return;
768
769 const RecordDecl *RD = RT->getDecl();
770
771 // Assume variable sized types are passed in memory.
772 if (RD->hasFlexibleArrayMember())
773 return;
774
775 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
776
777 // Reset Lo class, this will be recomputed.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000778 Current = NoClass;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000779 unsigned idx = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000780 for (RecordDecl::field_iterator i = RD->field_begin(Context),
781 e = RD->field_end(Context); i != e; ++i, ++idx) {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000782 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000783 bool BitField = i->isBitField();
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000784
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000785 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
786 // fields, it has class MEMORY.
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000787 //
Daniel Dunbaref495d42009-04-27 18:31:32 +0000788 // Note, skip this test for bit-fields, see below.
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000789 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000790 Lo = Memory;
791 return;
792 }
793
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000794 // Classify this field.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000795 //
796 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
797 // exceeds a single eightbyte, each is classified
798 // separately. Each eightbyte gets initialized to class
799 // NO_CLASS.
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000800 Class FieldLo, FieldHi;
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000801
Daniel Dunbaref495d42009-04-27 18:31:32 +0000802 // Bit-fields require special handling, they do not force the
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000803 // structure to be passed in memory even if unaligned, and
804 // therefore they can straddle an eightbyte.
805 if (BitField) {
Daniel Dunbar9bb29952009-05-08 22:26:44 +0000806 // Ignore padding bit-fields.
807 if (i->isUnnamedBitfield())
808 continue;
809
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000810 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Eli Friedman5255e7a2009-04-26 19:19:15 +0000811 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000812
813 uint64_t EB_Lo = Offset / 64;
814 uint64_t EB_Hi = (Offset + Size - 1) / 64;
815 FieldLo = FieldHi = NoClass;
816 if (EB_Lo) {
817 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
818 FieldLo = NoClass;
819 FieldHi = Integer;
820 } else {
821 FieldLo = Integer;
822 FieldHi = EB_Hi ? Integer : NoClass;
823 }
824 } else
825 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000826 Lo = merge(Lo, FieldLo);
827 Hi = merge(Hi, FieldHi);
828 if (Lo == Memory || Hi == Memory)
829 break;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000830 }
831
832 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
833 //
834 // (a) If one of the classes is MEMORY, the whole argument is
835 // passed in memory.
836 //
837 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
838
839 // The first of these conditions is guaranteed by how we implement
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000840 // the merge (just bail).
841 //
842 // The second condition occurs in the case of unions; for example
843 // union { _Complex double; unsigned; }.
844 if (Hi == Memory)
845 Lo = Memory;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000846 if (Hi == SSEUp && Lo != SSE)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000847 Hi = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000848 }
849}
850
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000851ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
852 const llvm::Type *CoerceTo,
853 ASTContext &Context) const {
854 if (CoerceTo == llvm::Type::Int64Ty) {
855 // Integer and pointer types will end up in a general purpose
856 // register.
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000857 if (Ty->isIntegralType() || Ty->isPointerType())
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000858 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000859
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000860 } else if (CoerceTo == llvm::Type::DoubleTy) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000861 // FIXME: It would probably be better to make CGFunctionInfo only map using
862 // canonical types than to canonize here.
Daniel Dunbare60d5332009-02-14 02:45:45 +0000863 QualType CTy = Context.getCanonicalType(Ty);
864
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000865 // Float and double end up in a single SSE reg.
Daniel Dunbare60d5332009-02-14 02:45:45 +0000866 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000867 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000868
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000869 }
870
871 return ABIArgInfo::getCoerce(CoerceTo);
872}
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000873
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000874ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
875 ASTContext &Context) const {
Daniel Dunbare09a9692009-01-24 08:32:22 +0000876 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
877 // classification algorithm.
878 X86_64ABIInfo::Class Lo, Hi;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000879 classify(RetTy, Context, 0, Lo, Hi);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000880
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000881 // Check some invariants.
882 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
883 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
884 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
885
Daniel Dunbare09a9692009-01-24 08:32:22 +0000886 const llvm::Type *ResType = 0;
887 switch (Lo) {
888 case NoClass:
Daniel Dunbar1358b202009-01-26 21:26:08 +0000889 return ABIArgInfo::getIgnore();
Daniel Dunbare09a9692009-01-24 08:32:22 +0000890
891 case SSEUp:
892 case X87Up:
893 assert(0 && "Invalid classification for lo word.");
894
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000895 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000896 // hidden argument.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000897 case Memory:
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000898 return ABIArgInfo::getIndirect(0);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000899
900 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
901 // available register of the sequence %rax, %rdx is used.
902 case Integer:
903 ResType = llvm::Type::Int64Ty; break;
904
905 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
906 // available SSE register of the sequence %xmm0, %xmm1 is used.
907 case SSE:
908 ResType = llvm::Type::DoubleTy; break;
909
910 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
911 // returned on the X87 stack in %st0 as 80-bit x87 number.
912 case X87:
913 ResType = llvm::Type::X86_FP80Ty; break;
914
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000915 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
916 // part of the value is returned in %st0 and the imaginary part in
917 // %st1.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000918 case ComplexX87:
Daniel Dunbar92e88642009-02-17 07:55:55 +0000919 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Daniel Dunbar4fc0d492009-02-18 03:44:19 +0000920 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
921 llvm::Type::X86_FP80Ty,
922 NULL);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000923 break;
924 }
925
926 switch (Hi) {
Daniel Dunbar92e88642009-02-17 07:55:55 +0000927 // Memory was handled previously and X87 should
928 // never occur as a hi class.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000929 case Memory:
930 case X87:
Daniel Dunbare09a9692009-01-24 08:32:22 +0000931 assert(0 && "Invalid classification for hi word.");
932
Daniel Dunbar92e88642009-02-17 07:55:55 +0000933 case ComplexX87: // Previously handled.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000934 case NoClass: break;
Daniel Dunbar92e88642009-02-17 07:55:55 +0000935
Daniel Dunbare09a9692009-01-24 08:32:22 +0000936 case Integer:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000937 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
938 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000939 case SSE:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000940 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
941 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000942
943 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
944 // is passed in the upper half of the last used SSE register.
945 //
946 // SSEUP should always be preceeded by SSE, just widen.
947 case SSEUp:
948 assert(Lo == SSE && "Unexpected SSEUp classification.");
949 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
950 break;
951
952 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000953 // returned together with the previous X87 value in %st0.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000954 case X87Up:
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000955 // If X87Up is preceeded by X87, we don't need to do
956 // anything. However, in some cases with unions it may not be
957 // preceeded by X87. In such situations we follow gcc and pass the
958 // extra bits in an SSE reg.
959 if (Lo != X87)
960 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000961 break;
962 }
963
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000964 return getCoerceResult(RetTy, ResType, Context);
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000965}
966
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000967ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000968 unsigned &neededInt,
969 unsigned &neededSSE) const {
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000970 X86_64ABIInfo::Class Lo, Hi;
971 classify(Ty, Context, 0, Lo, Hi);
972
973 // Check some invariants.
974 // FIXME: Enforce these by construction.
975 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
976 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
977 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
978
Daniel Dunbare978cb92009-02-10 17:06:09 +0000979 neededInt = 0;
980 neededSSE = 0;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000981 const llvm::Type *ResType = 0;
982 switch (Lo) {
983 case NoClass:
984 return ABIArgInfo::getIgnore();
985
986 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
987 // on the stack.
988 case Memory:
989
990 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
991 // COMPLEX_X87, it is passed in memory.
992 case X87:
993 case ComplexX87:
Daniel Dunbard0536ac2009-02-22 08:17:51 +0000994 return ABIArgInfo::getIndirect(0);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000995
996 case SSEUp:
997 case X87Up:
998 assert(0 && "Invalid classification for lo word.");
999
1000 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1001 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1002 // and %r9 is used.
1003 case Integer:
1004 ++neededInt;
1005 ResType = llvm::Type::Int64Ty;
1006 break;
1007
1008 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1009 // available SSE register is used, the registers are taken in the
1010 // order from %xmm0 to %xmm7.
1011 case SSE:
1012 ++neededSSE;
1013 ResType = llvm::Type::DoubleTy;
1014 break;
Daniel Dunbareec02622009-02-03 06:30:17 +00001015 }
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001016
1017 switch (Hi) {
1018 // Memory was handled previously, ComplexX87 and X87 should
1019 // never occur as hi classes, and X87Up must be preceed by X87,
1020 // which is passed in memory.
1021 case Memory:
1022 case X87:
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001023 case ComplexX87:
1024 assert(0 && "Invalid classification for hi word.");
Daniel Dunbar78d7d452009-03-06 17:50:25 +00001025 break;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001026
1027 case NoClass: break;
1028 case Integer:
1029 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
1030 ++neededInt;
1031 break;
Daniel Dunbar78d7d452009-03-06 17:50:25 +00001032
1033 // X87Up generally doesn't occur here (long double is passed in
1034 // memory), except in situations involving unions.
1035 case X87Up:
1036 case SSE:
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001037 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
1038 ++neededSSE;
1039 break;
1040
1041 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1042 // eightbyte is passed in the upper half of the last used SSE
1043 // register.
1044 case SSEUp:
1045 assert(Lo == SSE && "Unexpected SSEUp classification.");
1046 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
1047 break;
1048 }
1049
Daniel Dunbar87c4dc92009-02-14 02:09:24 +00001050 return getCoerceResult(Ty, ResType, Context);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001051}
1052
1053void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1054 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1055
1056 // Keep track of the number of assigned registers.
1057 unsigned freeIntRegs = 6, freeSSERegs = 8;
Daniel Dunbar1f84f592009-05-22 17:33:44 +00001058
1059 // If the return value is indirect, then the hidden argument is consuming one
1060 // integer register.
1061 if (FI.getReturnInfo().isIndirect())
1062 --freeIntRegs;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001063
1064 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1065 // get assigned (in left-to-right order) for passing as follows...
1066 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Daniel Dunbare978cb92009-02-10 17:06:09 +00001067 it != ie; ++it) {
1068 unsigned neededInt, neededSSE;
1069 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
1070
1071 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1072 // eightbyte of an argument, the whole argument is passed on the
1073 // stack. If registers have already been assigned for some
1074 // eightbytes of such an argument, the assignments get reverted.
1075 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1076 freeIntRegs -= neededInt;
1077 freeSSERegs -= neededSSE;
1078 } else {
Daniel Dunbard0536ac2009-02-22 08:17:51 +00001079 it->info = ABIArgInfo::getIndirect(0);
Daniel Dunbare978cb92009-02-10 17:06:09 +00001080 }
1081 }
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001082}
1083
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001084static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1085 QualType Ty,
1086 CodeGenFunction &CGF) {
1087 llvm::Value *overflow_arg_area_p =
1088 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1089 llvm::Value *overflow_arg_area =
1090 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1091
1092 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1093 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +00001094 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001095 if (Align > 8) {
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +00001096 // Note that we follow the ABI & gcc here, even though the type
1097 // could in theory have an alignment greater than 16. This case
1098 // shouldn't ever matter in practice.
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001099
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +00001100 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1101 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
1102 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1103 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1104 llvm::Type::Int64Ty);
1105 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
1106 overflow_arg_area =
1107 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1108 overflow_arg_area->getType(),
1109 "overflow_arg_area.align");
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001110 }
1111
1112 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1113 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1114 llvm::Value *Res =
1115 CGF.Builder.CreateBitCast(overflow_arg_area,
1116 llvm::PointerType::getUnqual(LTy));
1117
1118 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1119 // l->overflow_arg_area + sizeof(type).
1120 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1121 // an 8 byte boundary.
1122
1123 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1124 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1125 (SizeInBytes + 7) & ~7);
1126 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1127 "overflow_arg_area.next");
1128 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1129
1130 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1131 return Res;
1132}
1133
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001134llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1135 CodeGenFunction &CGF) const {
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001136 // Assume that va_list type is correct; should be pointer to LLVM type:
1137 // struct {
1138 // i32 gp_offset;
1139 // i32 fp_offset;
1140 // i8* overflow_arg_area;
1141 // i8* reg_save_area;
1142 // };
1143 unsigned neededInt, neededSSE;
1144 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1145 neededInt, neededSSE);
1146
1147 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1148 // in the registers. If not go to step 7.
1149 if (!neededInt && !neededSSE)
1150 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1151
1152 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1153 // general purpose registers needed to pass type and num_fp to hold
1154 // the number of floating point registers needed.
1155
1156 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1157 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1158 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1159 //
1160 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1161 // register save space).
1162
1163 llvm::Value *InRegs = 0;
1164 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1165 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1166 if (neededInt) {
1167 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1168 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1169 InRegs =
1170 CGF.Builder.CreateICmpULE(gp_offset,
1171 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1172 48 - neededInt * 8),
1173 "fits_in_gp");
1174 }
1175
1176 if (neededSSE) {
1177 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1178 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1179 llvm::Value *FitsInFP =
1180 CGF.Builder.CreateICmpULE(fp_offset,
1181 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar63118762009-02-18 22:19:44 +00001182 176 - neededSSE * 16),
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001183 "fits_in_fp");
Daniel Dunbar72198842009-02-18 22:05:01 +00001184 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001185 }
1186
1187 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1188 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1189 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1190 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1191
1192 // Emit code to load the value if it was passed in registers.
1193
1194 CGF.EmitBlock(InRegBlock);
1195
1196 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1197 // an offset of l->gp_offset and/or l->fp_offset. This may require
1198 // copying to a temporary location in case the parameter is passed
1199 // in different register classes or requires an alignment greater
1200 // than 8 for general purpose registers and 16 for XMM registers.
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001201 //
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001202 // FIXME: This really results in shameful code when we end up needing to
1203 // collect arguments from different places; often what should result in a
1204 // simple assembling of a structure from scattered addresses has many more
1205 // loads than necessary. Can we clean this up?
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001206 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1207 llvm::Value *RegAddr =
1208 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1209 "reg_save_area");
1210 if (neededInt && neededSSE) {
Daniel Dunbara96ec382009-02-13 17:46:31 +00001211 // FIXME: Cleanup.
1212 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1213 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1214 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1215 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1216 const llvm::Type *TyLo = ST->getElementType(0);
1217 const llvm::Type *TyHi = ST->getElementType(1);
1218 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1219 "Unexpected ABI info for mixed regs");
1220 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1221 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1222 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1223 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1224 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1225 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1226 llvm::Value *V =
1227 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1228 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1229 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1230 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1231
1232 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001233 } else if (neededInt) {
1234 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1235 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1236 llvm::PointerType::getUnqual(LTy));
1237 } else {
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001238 if (neededSSE == 1) {
1239 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1240 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1241 llvm::PointerType::getUnqual(LTy));
1242 } else {
1243 assert(neededSSE == 2 && "Invalid number of needed registers!");
1244 // SSE registers are spaced 16 bytes apart in the register save
1245 // area, we need to collect the two eightbytes together.
1246 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1247 llvm::Value *RegAddrHi =
1248 CGF.Builder.CreateGEP(RegAddrLo,
1249 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1250 const llvm::Type *DblPtrTy =
1251 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1252 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1253 llvm::Type::DoubleTy,
1254 NULL);
1255 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1256 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1257 DblPtrTy));
1258 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1259 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1260 DblPtrTy));
1261 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1262 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1263 llvm::PointerType::getUnqual(LTy));
1264 }
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001265 }
1266
1267 // AMD64-ABI 3.5.7p5: Step 5. Set:
1268 // l->gp_offset = l->gp_offset + num_gp * 8
1269 // l->fp_offset = l->fp_offset + num_fp * 16.
1270 if (neededInt) {
1271 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1272 neededInt * 8);
1273 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1274 gp_offset_p);
1275 }
1276 if (neededSSE) {
1277 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1278 neededSSE * 16);
1279 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1280 fp_offset_p);
1281 }
1282 CGF.EmitBranch(ContBlock);
1283
1284 // Emit code to load the value if it was passed in memory.
1285
1286 CGF.EmitBlock(InMemBlock);
1287 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1288
1289 // Return the appropriate result.
1290
1291 CGF.EmitBlock(ContBlock);
1292 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1293 "vaarg.addr");
1294 ResAddr->reserveOperandSpace(2);
1295 ResAddr->addIncoming(RegAddr, InRegBlock);
1296 ResAddr->addIncoming(MemAddr, InMemBlock);
1297
1298 return ResAddr;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001299}
1300
Sanjiv Gupta88b4e512009-04-21 06:01:16 +00001301// ABI Info for PIC16
1302class PIC16ABIInfo : public ABIInfo {
1303 ABIArgInfo classifyReturnType(QualType RetTy,
1304 ASTContext &Context) const;
1305
1306 ABIArgInfo classifyArgumentType(QualType RetTy,
1307 ASTContext &Context) const;
1308
1309 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1310 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1311 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1312 it != ie; ++it)
1313 it->info = classifyArgumentType(it->type, Context);
1314 }
1315
1316 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1317 CodeGenFunction &CGF) const;
1318
1319};
1320
1321ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1322 ASTContext &Context) const {
1323 if (RetTy->isVoidType()) {
1324 return ABIArgInfo::getIgnore();
1325 } else {
1326 return ABIArgInfo::getDirect();
1327 }
1328}
1329
1330ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1331 ASTContext &Context) const {
1332 return ABIArgInfo::getDirect();
1333}
1334
1335llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1336 CodeGenFunction &CGF) const {
1337 return 0;
1338}
1339
Eli Friedmanac90d8e2009-03-29 00:15:25 +00001340class ARMABIInfo : public ABIInfo {
1341 ABIArgInfo classifyReturnType(QualType RetTy,
1342 ASTContext &Context) const;
1343
1344 ABIArgInfo classifyArgumentType(QualType RetTy,
1345 ASTContext &Context) const;
1346
1347 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
1348
1349 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1350 CodeGenFunction &CGF) const;
1351};
1352
1353void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1354 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1355 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1356 it != ie; ++it) {
1357 it->info = classifyArgumentType(it->type, Context);
1358 }
1359}
1360
1361ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1362 ASTContext &Context) const {
1363 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1364 return ABIArgInfo::getDirect();
1365 }
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001366 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1367 // backend doesn't support byval.
Eli Friedmanac90d8e2009-03-29 00:15:25 +00001368 // FIXME: This doesn't handle alignment > 64 bits.
1369 const llvm::Type* ElemTy;
1370 unsigned SizeRegs;
1371 if (Context.getTypeAlign(Ty) > 32) {
1372 ElemTy = llvm::Type::Int64Ty;
1373 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1374 } else {
1375 ElemTy = llvm::Type::Int32Ty;
1376 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1377 }
1378 std::vector<const llvm::Type*> LLVMFields;
1379 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1380 const llvm::Type* STy = llvm::StructType::get(LLVMFields, true);
1381 return ABIArgInfo::getCoerce(STy);
1382}
1383
1384ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1385 ASTContext &Context) const {
1386 if (RetTy->isVoidType()) {
1387 return ABIArgInfo::getIgnore();
1388 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1389 // Aggregates <= 4 bytes are returned in r0; other aggregates
1390 // are returned indirectly.
1391 uint64_t Size = Context.getTypeSize(RetTy);
1392 if (Size <= 32)
1393 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
1394 return ABIArgInfo::getIndirect(0);
1395 } else {
1396 return ABIArgInfo::getDirect();
1397 }
1398}
1399
1400llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1401 CodeGenFunction &CGF) const {
1402 // FIXME: Need to handle alignment
1403 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1404 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1405
1406 CGBuilderTy &Builder = CGF.Builder;
1407 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1408 "ap");
1409 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1410 llvm::Type *PTy =
1411 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1412 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1413
1414 uint64_t Offset =
1415 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1416 llvm::Value *NextAddr =
1417 Builder.CreateGEP(Addr,
1418 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
1419 "ap.next");
1420 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1421
1422 return AddrTyped;
1423}
1424
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001425ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001426 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001427 if (RetTy->isVoidType()) {
1428 return ABIArgInfo::getIgnore();
1429 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001430 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001431 } else {
1432 return ABIArgInfo::getDirect();
1433 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001434}
1435
1436ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001437 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001438 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001439 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001440 } else {
1441 return ABIArgInfo::getDirect();
1442 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001443}
1444
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001445llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1446 CodeGenFunction &CGF) const {
1447 return 0;
1448}
1449
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001450const ABIInfo &CodeGenTypes::getABIInfo() const {
1451 if (TheABIInfo)
1452 return *TheABIInfo;
1453
1454 // For now we just cache this in the CodeGenTypes and don't bother
1455 // to free it.
1456 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1457 if (strcmp(TargetPrefix, "x86") == 0) {
Eli Friedman5e175802009-03-23 23:26:24 +00001458 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001459 switch (getContext().Target.getPointerWidth(0)) {
1460 case 32:
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001461 return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin));
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001462 case 64:
Daniel Dunbar56555952009-01-30 18:47:53 +00001463 return *(TheABIInfo = new X86_64ABIInfo());
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001464 }
Eli Friedmanac90d8e2009-03-29 00:15:25 +00001465 } else if (strcmp(TargetPrefix, "arm") == 0) {
1466 // FIXME: Support for OABI?
1467 return *(TheABIInfo = new ARMABIInfo());
Sanjiv Gupta88b4e512009-04-21 06:01:16 +00001468 } else if (strcmp(TargetPrefix, "pic16") == 0) {
1469 return *(TheABIInfo = new PIC16ABIInfo());
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001470 }
1471
1472 return *(TheABIInfo = new DefaultABIInfo);
1473}
1474
Daniel Dunbare126ab12008-09-10 02:41:04 +00001475/***/
1476
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001477CGFunctionInfo::CGFunctionInfo(QualType ResTy,
1478 const llvm::SmallVector<QualType, 16> &ArgTys) {
1479 NumArgs = ArgTys.size();
1480 Args = new ArgInfo[1 + NumArgs];
1481 Args[0].type = ResTy;
1482 for (unsigned i = 0; i < NumArgs; ++i)
1483 Args[1 + i].type = ArgTys[i];
1484}
1485
1486/***/
1487
Daniel Dunbar04d35782008-09-17 00:51:38 +00001488void CodeGenTypes::GetExpandedTypes(QualType Ty,
1489 std::vector<const llvm::Type*> &ArgTys) {
1490 const RecordType *RT = Ty->getAsStructureType();
1491 assert(RT && "Can only expand structure types.");
1492 const RecordDecl *RD = RT->getDecl();
1493 assert(!RD->hasFlexibleArrayMember() &&
1494 "Cannot expand structure with flexible array.");
1495
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001496 for (RecordDecl::field_iterator i = RD->field_begin(Context),
1497 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar04d35782008-09-17 00:51:38 +00001498 const FieldDecl *FD = *i;
1499 assert(!FD->isBitField() &&
1500 "Cannot expand structure with bit-field members.");
1501
1502 QualType FT = FD->getType();
1503 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1504 GetExpandedTypes(FT, ArgTys);
1505 } else {
1506 ArgTys.push_back(ConvertType(FT));
1507 }
1508 }
1509}
1510
1511llvm::Function::arg_iterator
1512CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1513 llvm::Function::arg_iterator AI) {
1514 const RecordType *RT = Ty->getAsStructureType();
1515 assert(RT && "Can only expand structure types.");
1516
1517 RecordDecl *RD = RT->getDecl();
1518 assert(LV.isSimple() &&
1519 "Unexpected non-simple lvalue during struct expansion.");
1520 llvm::Value *Addr = LV.getAddress();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001521 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1522 e = RD->field_end(getContext()); i != e; ++i) {
Daniel Dunbar04d35782008-09-17 00:51:38 +00001523 FieldDecl *FD = *i;
1524 QualType FT = FD->getType();
1525
1526 // FIXME: What are the right qualifiers here?
1527 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1528 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1529 AI = ExpandTypeFromArgs(FT, LV, AI);
1530 } else {
1531 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
1532 ++AI;
1533 }
1534 }
1535
1536 return AI;
1537}
1538
1539void
1540CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1541 llvm::SmallVector<llvm::Value*, 16> &Args) {
1542 const RecordType *RT = Ty->getAsStructureType();
1543 assert(RT && "Can only expand structure types.");
1544
1545 RecordDecl *RD = RT->getDecl();
1546 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1547 llvm::Value *Addr = RV.getAggregateAddr();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001548 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1549 e = RD->field_end(getContext()); i != e; ++i) {
Daniel Dunbar04d35782008-09-17 00:51:38 +00001550 FieldDecl *FD = *i;
1551 QualType FT = FD->getType();
1552
1553 // FIXME: What are the right qualifiers here?
1554 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1555 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1556 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
1557 } else {
1558 RValue RV = EmitLoadOfLValue(LV, FT);
1559 assert(RV.isScalar() &&
1560 "Unexpected non-scalar rvalue during struct expansion.");
1561 Args.push_back(RV.getScalarVal());
1562 }
1563 }
1564}
1565
Daniel Dunbar84379912009-02-02 19:06:38 +00001566/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1567/// a pointer to an object of type \arg Ty.
1568///
1569/// This safely handles the case when the src type is smaller than the
1570/// destination type; in this situation the values of bits which not
1571/// present in the src are undefined.
1572static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
1573 const llvm::Type *Ty,
1574 CodeGenFunction &CGF) {
1575 const llvm::Type *SrcTy =
1576 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Duncan Sandsee6f6f82009-05-09 07:08:47 +00001577 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1578 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Daniel Dunbar84379912009-02-02 19:06:38 +00001579
Daniel Dunbar77071992009-02-03 05:59:18 +00001580 // If load is legal, just bitcast the src pointer.
Daniel Dunbar93317922009-05-13 18:54:26 +00001581 if (SrcSize >= DstSize) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001582 // Generally SrcSize is never greater than DstSize, since this means we are
1583 // losing bits. However, this can happen in cases where the structure has
1584 // additional padding, for example due to a user specified alignment.
Daniel Dunbar93317922009-05-13 18:54:26 +00001585 //
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001586 // FIXME: Assert that we aren't truncating non-padding bits when have access
1587 // to that information.
Daniel Dunbar84379912009-02-02 19:06:38 +00001588 llvm::Value *Casted =
1589 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001590 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1591 // FIXME: Use better alignment / avoid requiring aligned load.
1592 Load->setAlignment(1);
1593 return Load;
Daniel Dunbar84379912009-02-02 19:06:38 +00001594 } else {
Daniel Dunbar84379912009-02-02 19:06:38 +00001595 // Otherwise do coercion through memory. This is stupid, but
1596 // simple.
1597 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
1598 llvm::Value *Casted =
1599 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001600 llvm::StoreInst *Store =
1601 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
1602 // FIXME: Use better alignment / avoid requiring aligned store.
1603 Store->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001604 return CGF.Builder.CreateLoad(Tmp);
1605 }
1606}
1607
1608/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1609/// where the source and destination may have different types.
1610///
1611/// This safely handles the case when the src type is larger than the
1612/// destination type; the upper bits of the src will be lost.
1613static void CreateCoercedStore(llvm::Value *Src,
1614 llvm::Value *DstPtr,
1615 CodeGenFunction &CGF) {
1616 const llvm::Type *SrcTy = Src->getType();
1617 const llvm::Type *DstTy =
1618 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1619
Duncan Sandsee6f6f82009-05-09 07:08:47 +00001620 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1621 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbar84379912009-02-02 19:06:38 +00001622
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001623 // If store is legal, just bitcast the src pointer.
Daniel Dunbar93317922009-05-13 18:54:26 +00001624 if (SrcSize >= DstSize) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001625 // Generally SrcSize is never greater than DstSize, since this means we are
1626 // losing bits. However, this can happen in cases where the structure has
1627 // additional padding, for example due to a user specified alignment.
Daniel Dunbar93317922009-05-13 18:54:26 +00001628 //
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001629 // FIXME: Assert that we aren't truncating non-padding bits when have access
1630 // to that information.
Daniel Dunbar84379912009-02-02 19:06:38 +00001631 llvm::Value *Casted =
1632 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001633 // FIXME: Use better alignment / avoid requiring aligned store.
1634 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001635 } else {
Daniel Dunbar84379912009-02-02 19:06:38 +00001636 // Otherwise do coercion through memory. This is stupid, but
1637 // simple.
1638 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1639 CGF.Builder.CreateStore(Src, Tmp);
1640 llvm::Value *Casted =
1641 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001642 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1643 // FIXME: Use better alignment / avoid requiring aligned load.
1644 Load->setAlignment(1);
1645 CGF.Builder.CreateStore(Load, DstPtr);
Daniel Dunbar84379912009-02-02 19:06:38 +00001646 }
1647}
1648
Daniel Dunbar04d35782008-09-17 00:51:38 +00001649/***/
1650
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001651bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001652 return FI.getReturnInfo().isIndirect();
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001653}
1654
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001655const llvm::FunctionType *
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001656CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001657 std::vector<const llvm::Type*> ArgTys;
1658
1659 const llvm::Type *ResultType = 0;
1660
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001661 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001662 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar22e30052008-09-11 01:48:57 +00001663 switch (RetAI.getKind()) {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001664 case ABIArgInfo::Expand:
1665 assert(0 && "Invalid ABI kind for return argument");
1666
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001667 case ABIArgInfo::Direct:
1668 ResultType = ConvertType(RetTy);
1669 break;
1670
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001671 case ABIArgInfo::Indirect: {
1672 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001673 ResultType = llvm::Type::VoidTy;
Daniel Dunbara9976a22008-09-10 07:00:50 +00001674 const llvm::Type *STy = ConvertType(RetTy);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001675 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
1676 break;
1677 }
1678
Daniel Dunbar1358b202009-01-26 21:26:08 +00001679 case ABIArgInfo::Ignore:
1680 ResultType = llvm::Type::VoidTy;
1681 break;
1682
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001683 case ABIArgInfo::Coerce:
Daniel Dunbar73d66602008-09-10 07:04:09 +00001684 ResultType = RetAI.getCoerceToType();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001685 break;
1686 }
1687
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001688 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1689 ie = FI.arg_end(); it != ie; ++it) {
1690 const ABIArgInfo &AI = it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001691
1692 switch (AI.getKind()) {
Daniel Dunbar1358b202009-01-26 21:26:08 +00001693 case ABIArgInfo::Ignore:
1694 break;
1695
Daniel Dunbar04d35782008-09-17 00:51:38 +00001696 case ABIArgInfo::Coerce:
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001697 ArgTys.push_back(AI.getCoerceToType());
1698 break;
1699
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001700 case ABIArgInfo::Indirect: {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001701 // indirect arguments are always on the stack, which is addr space #0.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001702 const llvm::Type *LTy = ConvertTypeForMem(it->type);
1703 ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001704 break;
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001705 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001706
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001707 case ABIArgInfo::Direct:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001708 ArgTys.push_back(ConvertType(it->type));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001709 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001710
1711 case ABIArgInfo::Expand:
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001712 GetExpandedTypes(it->type, ArgTys);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001713 break;
1714 }
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001715 }
1716
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001717 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +00001718}
1719
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001720void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001721 const Decl *TargetDecl,
Devang Patela85a9ef2008-09-25 21:02:23 +00001722 AttributeListType &PAL) {
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001723 unsigned FuncAttrs = 0;
Devang Patel2bb6eb82008-09-26 22:53:57 +00001724 unsigned RetAttrs = 0;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001725
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001726 // FIXME: handle sseregparm someday...
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001727 if (TargetDecl) {
Daniel Dunbar78582862009-04-13 21:08:27 +00001728 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001729 FuncAttrs |= llvm::Attribute::NoUnwind;
Daniel Dunbar78582862009-04-13 21:08:27 +00001730 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001731 FuncAttrs |= llvm::Attribute::NoReturn;
Daniel Dunbar78582862009-04-13 21:08:27 +00001732 if (TargetDecl->hasAttr<ConstAttr>())
Anders Carlssondd6791c2008-10-05 23:32:53 +00001733 FuncAttrs |= llvm::Attribute::ReadNone;
Daniel Dunbar78582862009-04-13 21:08:27 +00001734 else if (TargetDecl->hasAttr<PureAttr>())
Daniel Dunbar521c3a32009-04-10 22:14:52 +00001735 FuncAttrs |= llvm::Attribute::ReadOnly;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001736 }
1737
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001738 QualType RetTy = FI.getReturnType();
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001739 unsigned Index = 1;
Daniel Dunbar77071992009-02-03 05:59:18 +00001740 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001741 switch (RetAI.getKind()) {
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001742 case ABIArgInfo::Direct:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001743 if (RetTy->isPromotableIntegerType()) {
1744 if (RetTy->isSignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001745 RetAttrs |= llvm::Attribute::SExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001746 } else if (RetTy->isUnsignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001747 RetAttrs |= llvm::Attribute::ZExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001748 }
1749 }
1750 break;
1751
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001752 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001753 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00001754 llvm::Attribute::StructRet |
1755 llvm::Attribute::NoAlias));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001756 ++Index;
Daniel Dunbar39ea2c12009-03-18 19:51:01 +00001757 // sret disables readnone and readonly
1758 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1759 llvm::Attribute::ReadNone);
Daniel Dunbare126ab12008-09-10 02:41:04 +00001760 break;
1761
Daniel Dunbar1358b202009-01-26 21:26:08 +00001762 case ABIArgInfo::Ignore:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001763 case ABIArgInfo::Coerce:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001764 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001765
Daniel Dunbar22e30052008-09-11 01:48:57 +00001766 case ABIArgInfo::Expand:
1767 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001768 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001769
Devang Patel2bb6eb82008-09-26 22:53:57 +00001770 if (RetAttrs)
1771 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001772
1773 // FIXME: we need to honour command line settings also...
1774 // FIXME: RegParm should be reduced in case of nested functions and/or global
1775 // register variable.
1776 signed RegParm = 0;
1777 if (TargetDecl)
1778 if (const RegparmAttr *RegParmAttr = TargetDecl->getAttr<RegparmAttr>())
1779 RegParm = RegParmAttr->getNumParams();
1780
1781 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001782 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1783 ie = FI.arg_end(); it != ie; ++it) {
1784 QualType ParamType = it->type;
1785 const ABIArgInfo &AI = it->info;
Devang Patela85a9ef2008-09-25 21:02:23 +00001786 unsigned Attributes = 0;
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001787
Daniel Dunbar22e30052008-09-11 01:48:57 +00001788 switch (AI.getKind()) {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001789 case ABIArgInfo::Coerce:
1790 break;
1791
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001792 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001793 Attributes |= llvm::Attribute::ByVal;
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001794 Attributes |=
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001795 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar39ea2c12009-03-18 19:51:01 +00001796 // byval disables readnone and readonly.
1797 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1798 llvm::Attribute::ReadNone);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001799 break;
1800
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001801 case ABIArgInfo::Direct:
Daniel Dunbar22e30052008-09-11 01:48:57 +00001802 if (ParamType->isPromotableIntegerType()) {
1803 if (ParamType->isSignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001804 Attributes |= llvm::Attribute::SExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001805 } else if (ParamType->isUnsignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001806 Attributes |= llvm::Attribute::ZExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001807 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001808 }
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001809 if (RegParm > 0 &&
1810 (ParamType->isIntegerType() || ParamType->isPointerType())) {
1811 RegParm -=
1812 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
1813 if (RegParm >= 0)
1814 Attributes |= llvm::Attribute::InReg;
1815 }
1816 // FIXME: handle sseregparm someday...
Daniel Dunbar22e30052008-09-11 01:48:57 +00001817 break;
Anton Korobeynikov2431e602009-04-04 00:49:24 +00001818
Daniel Dunbar1358b202009-01-26 21:26:08 +00001819 case ABIArgInfo::Ignore:
1820 // Skip increment, no matching LLVM parameter.
1821 continue;
1822
Daniel Dunbar04d35782008-09-17 00:51:38 +00001823 case ABIArgInfo::Expand: {
1824 std::vector<const llvm::Type*> Tys;
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001825 // FIXME: This is rather inefficient. Do we ever actually need to do
1826 // anything here? The result should be just reconstructed on the other
1827 // side, so extension should be a non-issue.
Daniel Dunbar04d35782008-09-17 00:51:38 +00001828 getTypes().GetExpandedTypes(ParamType, Tys);
1829 Index += Tys.size();
1830 continue;
1831 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001832 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001833
Devang Patela85a9ef2008-09-25 21:02:23 +00001834 if (Attributes)
1835 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar04d35782008-09-17 00:51:38 +00001836 ++Index;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001837 }
Devang Patel2bb6eb82008-09-26 22:53:57 +00001838 if (FuncAttrs)
1839 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001840}
1841
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001842void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1843 llvm::Function *Fn,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001844 const FunctionArgList &Args) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001845 // FIXME: We no longer need the types from FunctionArgList; lift up and
1846 // simplify.
Daniel Dunbar5b7ac652009-02-03 06:02:10 +00001847
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001848 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1849 llvm::Function::arg_iterator AI = Fn->arg_begin();
1850
1851 // Name the struct return argument.
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001852 if (CGM.ReturnTypeUsesSret(FI)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001853 AI->setName("agg.result");
1854 ++AI;
1855 }
Daniel Dunbar77071992009-02-03 05:59:18 +00001856
Daniel Dunbar14c884a2009-02-04 21:17:21 +00001857 assert(FI.arg_size() == Args.size() &&
1858 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00001859 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001860 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00001861 i != e; ++i, ++info_it) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001862 const VarDecl *Arg = i->first;
Daniel Dunbar77071992009-02-03 05:59:18 +00001863 QualType Ty = info_it->type;
1864 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001865
1866 switch (ArgI.getKind()) {
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001867 case ABIArgInfo::Indirect: {
1868 llvm::Value* V = AI;
1869 if (hasAggregateLLVMType(Ty)) {
1870 // Do nothing, aggregates and complex variables are accessed by
1871 // reference.
1872 } else {
1873 // Load scalar value from indirect argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001874 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001875 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1876 // This must be a promotion, for something like
1877 // "void a(x) short x; {..."
1878 V = EmitScalarConversion(V, Ty, Arg->getType());
1879 }
1880 }
1881 EmitParmDecl(*Arg, V);
1882 break;
1883 }
1884
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001885 case ABIArgInfo::Direct: {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001886 assert(AI != Fn->arg_end() && "Argument mismatch!");
1887 llvm::Value* V = AI;
Daniel Dunbarcc811502009-02-05 11:13:54 +00001888 if (hasAggregateLLVMType(Ty)) {
1889 // Create a temporary alloca to hold the argument; the rest of
1890 // codegen expects to access aggregates & complex values by
1891 // reference.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001892 V = CreateTempAlloca(ConvertTypeForMem(Ty));
Daniel Dunbarcc811502009-02-05 11:13:54 +00001893 Builder.CreateStore(AI, V);
1894 } else {
1895 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1896 // This must be a promotion, for something like
1897 // "void a(x) short x; {..."
1898 V = EmitScalarConversion(V, Ty, Arg->getType());
1899 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001900 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001901 EmitParmDecl(*Arg, V);
1902 break;
1903 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001904
1905 case ABIArgInfo::Expand: {
Daniel Dunbar77071992009-02-03 05:59:18 +00001906 // If this structure was expanded into multiple arguments then
Daniel Dunbar04d35782008-09-17 00:51:38 +00001907 // we need to create a temporary and reconstruct it from the
1908 // arguments.
Chris Lattner6c5ec622008-11-24 04:00:27 +00001909 std::string Name = Arg->getNameAsString();
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001910 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
Daniel Dunbar04d35782008-09-17 00:51:38 +00001911 (Name + ".addr").c_str());
1912 // FIXME: What are the right qualifiers here?
1913 llvm::Function::arg_iterator End =
1914 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
1915 EmitParmDecl(*Arg, Temp);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001916
Daniel Dunbar04d35782008-09-17 00:51:38 +00001917 // Name the arguments used in expansion and increment AI.
1918 unsigned Index = 0;
1919 for (; AI != End; ++AI, ++Index)
1920 AI->setName(Name + "." + llvm::utostr(Index));
1921 continue;
1922 }
Daniel Dunbar1358b202009-01-26 21:26:08 +00001923
1924 case ABIArgInfo::Ignore:
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001925 // Initialize the local variable appropriately.
1926 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001927 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001928 } else {
1929 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
1930 }
1931
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001932 // Skip increment, no matching LLVM parameter.
1933 continue;
Daniel Dunbar1358b202009-01-26 21:26:08 +00001934
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001935 case ABIArgInfo::Coerce: {
1936 assert(AI != Fn->arg_end() && "Argument mismatch!");
Mike Stumpba2cb0e2009-05-16 07:57:57 +00001937 // FIXME: This is very wasteful; EmitParmDecl is just going to drop the
1938 // result in a new alloca anyway, so we could just store into that
1939 // directly if we broke the abstraction down more.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001940 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001941 CreateCoercedStore(AI, V, *this);
1942 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001943 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001944 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001945 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1946 // This must be a promotion, for something like
1947 // "void a(x) short x; {..."
1948 V = EmitScalarConversion(V, Ty, Arg->getType());
1949 }
1950 }
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001951 EmitParmDecl(*Arg, V);
1952 break;
1953 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001954 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001955
1956 ++AI;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001957 }
1958 assert(AI == Fn->arg_end() && "Argument mismatch!");
1959}
1960
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001961void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001962 llvm::Value *ReturnValue) {
Daniel Dunbare126ab12008-09-10 02:41:04 +00001963 llvm::Value *RV = 0;
1964
1965 // Functions with no result always return void.
1966 if (ReturnValue) {
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001967 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001968 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbare126ab12008-09-10 02:41:04 +00001969
1970 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001971 case ABIArgInfo::Indirect:
Daniel Dunbar17d35372008-12-18 04:52:14 +00001972 if (RetTy->isAnyComplexType()) {
Daniel Dunbar17d35372008-12-18 04:52:14 +00001973 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1974 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1975 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1976 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
1977 } else {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001978 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Anders Carlsson05dfa992009-05-19 18:50:41 +00001979 false, RetTy);
Daniel Dunbar17d35372008-12-18 04:52:14 +00001980 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001981 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001982
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001983 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00001984 // The internal return value temp always will have
1985 // pointer-to-return-type type.
Daniel Dunbare126ab12008-09-10 02:41:04 +00001986 RV = Builder.CreateLoad(ReturnValue);
1987 break;
1988
Daniel Dunbar1358b202009-01-26 21:26:08 +00001989 case ABIArgInfo::Ignore:
1990 break;
1991
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001992 case ABIArgInfo::Coerce:
Daniel Dunbar708d8a82009-01-27 01:36:03 +00001993 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001994 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001995
Daniel Dunbar22e30052008-09-11 01:48:57 +00001996 case ABIArgInfo::Expand:
1997 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001998 }
1999 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00002000
2001 if (RV) {
2002 Builder.CreateRet(RV);
2003 } else {
2004 Builder.CreateRetVoid();
2005 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002006}
2007
Anders Carlssond927fa72009-04-08 20:47:54 +00002008RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) {
Anders Carlssonde55abc2009-05-20 00:24:07 +00002009 if (ArgType->isReferenceType())
2010 return EmitReferenceBindingToExpr(E, ArgType);
2011
Anders Carlssond927fa72009-04-08 20:47:54 +00002012 return EmitAnyExprToTemp(E);
2013}
2014
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00002015RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
2016 llvm::Value *Callee,
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00002017 const CallArgList &CallArgs,
2018 const Decl *TargetDecl) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +00002019 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002020 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002021
2022 // Handle struct-return functions by passing a pointer to the
2023 // location that we would like to return into.
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00002024 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00002025 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Daniel Dunbar32cae462009-02-05 09:24:53 +00002026 if (CGM.ReturnTypeUsesSret(CallInfo)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002027 // Create a temporary alloca to hold the result of the call. :(
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00002028 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002029 }
2030
Daniel Dunbar14c884a2009-02-04 21:17:21 +00002031 assert(CallInfo.arg_size() == CallArgs.size() &&
2032 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00002033 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002034 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00002035 I != E; ++I, ++info_it) {
2036 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002037 RValue RV = I->first;
Daniel Dunbar04d35782008-09-17 00:51:38 +00002038
2039 switch (ArgInfo.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00002040 case ABIArgInfo::Indirect:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00002041 if (RV.isScalar() || RV.isComplex()) {
2042 // Make a temporary alloca to pass the argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00002043 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
Daniel Dunbar6f56e452009-02-05 09:16:39 +00002044 if (RV.isScalar())
Anders Carlsson05dfa992009-05-19 18:50:41 +00002045 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00002046 else
2047 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
2048 } else {
2049 Args.push_back(RV.getAggregateAddr());
2050 }
2051 break;
2052
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00002053 case ABIArgInfo::Direct:
Daniel Dunbar04d35782008-09-17 00:51:38 +00002054 if (RV.isScalar()) {
2055 Args.push_back(RV.getScalarVal());
2056 } else if (RV.isComplex()) {
Daniel Dunbarcc811502009-02-05 11:13:54 +00002057 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
2058 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
2059 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
2060 Args.push_back(Tmp);
Daniel Dunbar04d35782008-09-17 00:51:38 +00002061 } else {
Daniel Dunbarcc811502009-02-05 11:13:54 +00002062 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
Daniel Dunbar04d35782008-09-17 00:51:38 +00002063 }
2064 break;
2065
Daniel Dunbar1358b202009-01-26 21:26:08 +00002066 case ABIArgInfo::Ignore:
2067 break;
2068
Daniel Dunbar33fa5812009-02-03 19:12:28 +00002069 case ABIArgInfo::Coerce: {
2070 // FIXME: Avoid the conversion through memory if possible.
2071 llvm::Value *SrcPtr;
2072 if (RV.isScalar()) {
Daniel Dunbar4ce351b2009-02-03 23:04:57 +00002073 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Anders Carlsson05dfa992009-05-19 18:50:41 +00002074 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second);
Daniel Dunbar33fa5812009-02-03 19:12:28 +00002075 } else if (RV.isComplex()) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00002076 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00002077 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
2078 } else
2079 SrcPtr = RV.getAggregateAddr();
2080 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2081 *this));
2082 break;
2083 }
2084
Daniel Dunbar04d35782008-09-17 00:51:38 +00002085 case ABIArgInfo::Expand:
2086 ExpandTypeToArgs(I->second, RV, Args);
2087 break;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002088 }
2089 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002090
Daniel Dunbar0a067402009-02-23 17:26:39 +00002091 llvm::BasicBlock *InvokeDest = getInvokeDest();
Devang Patela85a9ef2008-09-25 21:02:23 +00002092 CodeGen::AttributeListType AttributeList;
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00002093 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList);
Daniel Dunbar0a067402009-02-23 17:26:39 +00002094 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
2095 AttributeList.end());
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00002096
Daniel Dunbar90e43452009-03-02 04:32:35 +00002097 llvm::CallSite CS;
2098 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) {
Jay Foad9e6bef42009-05-21 09:52:38 +00002099 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
Daniel Dunbar0a067402009-02-23 17:26:39 +00002100 } else {
2101 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Daniel Dunbar90e43452009-03-02 04:32:35 +00002102 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
Jay Foad9e6bef42009-05-21 09:52:38 +00002103 Args.data(), Args.data()+Args.size());
Daniel Dunbar0a067402009-02-23 17:26:39 +00002104 EmitBlock(Cont);
Daniel Dunbaraf438dc2009-02-20 18:54:31 +00002105 }
2106
Daniel Dunbar90e43452009-03-02 04:32:35 +00002107 CS.setAttributes(Attrs);
Edwin Törökafed9682009-05-22 07:25:06 +00002108 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
Daniel Dunbar90e43452009-03-02 04:32:35 +00002109 CS.setCallingConv(F->getCallingConv());
2110
2111 // If the call doesn't return, finish the basic block and clear the
2112 // insertion point; this allows the rest of IRgen to discard
2113 // unreachable code.
2114 if (CS.doesNotReturn()) {
2115 Builder.CreateUnreachable();
2116 Builder.ClearInsertionPoint();
2117
Mike Stumpba2cb0e2009-05-16 07:57:57 +00002118 // FIXME: For now, emit a dummy basic block because expr emitters in
2119 // generally are not ready to handle emitting expressions at unreachable
2120 // points.
Daniel Dunbar90e43452009-03-02 04:32:35 +00002121 EnsureInsertPoint();
2122
2123 // Return a reasonable RValue.
2124 return GetUndefRValue(RetTy);
2125 }
2126
2127 llvm::Instruction *CI = CS.getInstruction();
Chris Lattner28466632009-03-22 00:32:22 +00002128 if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy)
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002129 CI->setName("call");
Daniel Dunbare126ab12008-09-10 02:41:04 +00002130
2131 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00002132 case ABIArgInfo::Indirect:
Daniel Dunbare126ab12008-09-10 02:41:04 +00002133 if (RetTy->isAnyComplexType())
Daniel Dunbar04d35782008-09-17 00:51:38 +00002134 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner28466632009-03-22 00:32:22 +00002135 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar04d35782008-09-17 00:51:38 +00002136 return RValue::getAggregate(Args[0]);
Chris Lattner28466632009-03-22 00:32:22 +00002137 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00002138
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00002139 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00002140 if (RetTy->isAnyComplexType()) {
2141 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2142 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2143 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattner28466632009-03-22 00:32:22 +00002144 }
2145 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00002146 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
Daniel Dunbarcc811502009-02-05 11:13:54 +00002147 Builder.CreateStore(CI, V);
2148 return RValue::getAggregate(V);
Chris Lattner28466632009-03-22 00:32:22 +00002149 }
2150 return RValue::get(CI);
Daniel Dunbare126ab12008-09-10 02:41:04 +00002151
Daniel Dunbar1358b202009-01-26 21:26:08 +00002152 case ABIArgInfo::Ignore:
Daniel Dunbareec02622009-02-03 06:30:17 +00002153 // If we are ignoring an argument that had a result, make sure to
2154 // construct the appropriate return value for our caller.
Daniel Dunbar900c85a2009-02-05 07:09:07 +00002155 return GetUndefRValue(RetTy);
Daniel Dunbar1358b202009-01-26 21:26:08 +00002156
Daniel Dunbar73d66602008-09-10 07:04:09 +00002157 case ABIArgInfo::Coerce: {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00002158 // FIXME: Avoid the conversion through memory if possible.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00002159 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
Daniel Dunbar708d8a82009-01-27 01:36:03 +00002160 CreateCoercedStore(CI, V, *this);
Anders Carlssonfccf7472008-11-25 22:21:48 +00002161 if (RetTy->isAnyComplexType())
2162 return RValue::getComplex(LoadComplexFromAddr(V, false));
Chris Lattner28466632009-03-22 00:32:22 +00002163 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssonfccf7472008-11-25 22:21:48 +00002164 return RValue::getAggregate(V);
Chris Lattner28466632009-03-22 00:32:22 +00002165 return RValue::get(EmitLoadOfScalar(V, false, RetTy));
Daniel Dunbar73d66602008-09-10 07:04:09 +00002166 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00002167
Daniel Dunbar22e30052008-09-11 01:48:57 +00002168 case ABIArgInfo::Expand:
2169 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002170 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00002171
2172 assert(0 && "Unhandled ABIArgInfo::Kind");
2173 return RValue::get(0);
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00002174}
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00002175
2176/* VarArg handling */
2177
2178llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2179 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2180}