blob: 8c438c9bd8cd5a88b3600b698a4ffcd090bf62bb [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"
21#include "clang/AST/DeclObjC.h"
Daniel Dunbar51a2d192009-01-29 08:13:58 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbar04d35782008-09-17 00:51:38 +000023#include "llvm/ADT/StringExtras.h"
Devang Patel98bfe502008-09-24 01:01:36 +000024#include "llvm/Attributes.h"
Daniel Dunbar90e43452009-03-02 04:32:35 +000025#include "llvm/Support/CallSite.h"
Daniel Dunbare09a9692009-01-24 08:32:22 +000026#include "llvm/Support/CommandLine.h"
Daniel Dunbar3cfcec72009-02-12 09:04:14 +000027#include "llvm/Support/MathExtras.h"
Daniel Dunbar9f4874e2009-02-04 23:24:38 +000028#include "llvm/Support/raw_ostream.h"
Daniel Dunbar708d8a82009-01-27 01:36:03 +000029#include "llvm/Target/TargetData.h"
Daniel Dunbard283e632009-02-03 01:05:53 +000030
31#include "ABIInfo.h"
32
Daniel Dunbara8f02052008-09-08 21:33:45 +000033using namespace clang;
34using namespace CodeGen;
35
36/***/
37
Daniel Dunbara8f02052008-09-08 21:33:45 +000038// FIXME: Use iterator and sidestep silly type array creation.
39
Daniel Dunbar34bda882009-02-02 23:23:47 +000040const
Douglas Gregor4fa58902009-02-26 23:50:07 +000041CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) {
Daniel Dunbar34bda882009-02-02 23:23:47 +000042 return getFunctionInfo(FTNP->getResultType(),
43 llvm::SmallVector<QualType, 16>());
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000044}
45
Daniel Dunbar34bda882009-02-02 23:23:47 +000046const
Douglas Gregor4fa58902009-02-26 23:50:07 +000047CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) {
Daniel Dunbar34bda882009-02-02 23:23:47 +000048 llvm::SmallVector<QualType, 16> ArgTys;
49 // FIXME: Kill copy.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000050 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000051 ArgTys.push_back(FTP->getArgType(i));
52 return getFunctionInfo(FTP->getResultType(), ArgTys);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000053}
54
Daniel Dunbar34bda882009-02-02 23:23:47 +000055const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Daniel Dunbara8f02052008-09-08 21:33:45 +000056 const FunctionType *FTy = FD->getType()->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +000057 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy))
Daniel Dunbar34bda882009-02-02 23:23:47 +000058 return getFunctionInfo(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +000059 return getFunctionInfo(cast<FunctionNoProtoType>(FTy));
Daniel Dunbara8f02052008-09-08 21:33:45 +000060}
61
Daniel Dunbar34bda882009-02-02 23:23:47 +000062const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
63 llvm::SmallVector<QualType, 16> ArgTys;
64 ArgTys.push_back(MD->getSelfDecl()->getType());
65 ArgTys.push_back(Context.getObjCSelType());
66 // FIXME: Kill copy?
Chris Lattner9408eb12009-02-20 06:23:21 +000067 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
Daniel Dunbara8f02052008-09-08 21:33:45 +000068 e = MD->param_end(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000069 ArgTys.push_back((*i)->getType());
70 return getFunctionInfo(MD->getResultType(), ArgTys);
Daniel Dunbara8f02052008-09-08 21:33:45 +000071}
72
Daniel Dunbar34bda882009-02-02 23:23:47 +000073const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
74 const CallArgList &Args) {
75 // FIXME: Kill copy.
76 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000077 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
78 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000079 ArgTys.push_back(i->second);
80 return getFunctionInfo(ResTy, ArgTys);
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000081}
82
Daniel Dunbar34bda882009-02-02 23:23:47 +000083const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
84 const FunctionArgList &Args) {
85 // FIXME: Kill copy.
86 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbar9fc15a82009-02-02 21:43:58 +000087 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
88 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000089 ArgTys.push_back(i->second);
90 return getFunctionInfo(ResTy, ArgTys);
91}
92
93const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
94 const llvm::SmallVector<QualType, 16> &ArgTys) {
Daniel Dunbardcf19d12009-02-03 00:07:12 +000095 // Lookup or create unique function info.
96 llvm::FoldingSetNodeID ID;
97 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end());
98
99 void *InsertPos = 0;
100 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
101 if (FI)
102 return *FI;
103
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000104 // Construct the function info.
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000105 FI = new CGFunctionInfo(ResTy, ArgTys);
Daniel Dunbarb944cc92009-02-05 00:00:23 +0000106 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000107
108 // Compute ABI information.
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000109 getABIInfo().computeInfo(*FI, getContext());
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000110
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000111 return *FI;
Daniel Dunbar34bda882009-02-02 23:23:47 +0000112}
113
114/***/
115
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000116ABIInfo::~ABIInfo() {}
117
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000118void ABIArgInfo::dump() const {
119 fprintf(stderr, "(ABIArgInfo Kind=");
120 switch (TheKind) {
121 case Direct:
122 fprintf(stderr, "Direct");
123 break;
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000124 case Ignore:
125 fprintf(stderr, "Ignore");
126 break;
127 case Coerce:
128 fprintf(stderr, "Coerce Type=");
129 getCoerceToType()->print(llvm::errs());
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000130 break;
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000131 case Indirect:
132 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000133 break;
134 case Expand:
135 fprintf(stderr, "Expand");
136 break;
137 }
138 fprintf(stderr, ")\n");
139}
140
141/***/
142
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000143/// isEmptyStruct - Return true iff a structure has no non-empty
144/// members. Note that a structure with a flexible array member is not
145/// considered empty.
146static bool isEmptyStruct(QualType T) {
147 const RecordType *RT = T->getAsStructureType();
148 if (!RT)
149 return 0;
150 const RecordDecl *RD = RT->getDecl();
151 if (RD->hasFlexibleArrayMember())
152 return false;
Douglas Gregor5d764842009-01-09 17:18:27 +0000153 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000154 e = RD->field_end(); i != e; ++i) {
155 const FieldDecl *FD = *i;
156 if (!isEmptyStruct(FD->getType()))
157 return false;
158 }
159 return true;
160}
161
162/// isSingleElementStruct - Determine if a structure is a "single
163/// element struct", i.e. it has exactly one non-empty field or
164/// exactly one field which is itself a single element
165/// struct. Structures with flexible array members are never
166/// considered single element structs.
167///
168/// \return The field declaration for the single non-empty field, if
169/// it exists.
170static const FieldDecl *isSingleElementStruct(QualType T) {
171 const RecordType *RT = T->getAsStructureType();
172 if (!RT)
173 return 0;
174
175 const RecordDecl *RD = RT->getDecl();
176 if (RD->hasFlexibleArrayMember())
177 return 0;
178
179 const FieldDecl *Found = 0;
Douglas Gregor5d764842009-01-09 17:18:27 +0000180 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000181 e = RD->field_end(); i != e; ++i) {
182 const FieldDecl *FD = *i;
183 QualType FT = FD->getType();
184
185 if (isEmptyStruct(FT)) {
186 // Ignore
187 } else if (Found) {
188 return 0;
189 } else if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
190 Found = FD;
191 } else {
192 Found = isSingleElementStruct(FT);
193 if (!Found)
194 return 0;
195 }
196 }
197
198 return Found;
199}
200
201static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
202 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
203 return false;
204
205 uint64_t Size = Context.getTypeSize(Ty);
206 return Size == 32 || Size == 64;
207}
208
209static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
210 ASTContext &Context) {
Douglas Gregor5d764842009-01-09 17:18:27 +0000211 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000212 e = RD->field_end(); i != e; ++i) {
213 const FieldDecl *FD = *i;
214
215 if (!is32Or64BitBasicType(FD->getType(), Context))
216 return false;
217
Daniel Dunbar9f052cb2009-03-11 22:05:26 +0000218 // FIXME: Reject bitfields wholesale; there are two problems, we
219 // don't know how to expand them yet, and the predicate for
220 // telling if a bitfield still counts as "basic" is more
221 // complicated than what we were doing previously.
222 if (FD->isBitField())
223 return false;
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000224 }
Daniel Dunbar9f052cb2009-03-11 22:05:26 +0000225
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000226 return true;
227}
228
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000229namespace {
230/// DefaultABIInfo - The default implementation for ABI specific
231/// details. This implementation provides information which results in
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000232/// self-consistent and sensible LLVM IR generation, but does not
233/// conform to any particular ABI.
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000234class DefaultABIInfo : public ABIInfo {
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000235 ABIArgInfo classifyReturnType(QualType RetTy,
236 ASTContext &Context) const;
237
238 ABIArgInfo classifyArgumentType(QualType RetTy,
239 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000240
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000241 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
242 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
243 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
244 it != ie; ++it)
245 it->info = classifyArgumentType(it->type, Context);
246 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000247
248 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
249 CodeGenFunction &CGF) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000250};
251
252/// X86_32ABIInfo - The X86-32 ABI information.
253class X86_32ABIInfo : public ABIInfo {
Eli Friedman5e175802009-03-23 23:26:24 +0000254 bool IsDarwin;
255
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000256public:
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000257 ABIArgInfo classifyReturnType(QualType RetTy,
258 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000259
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000260 ABIArgInfo classifyArgumentType(QualType RetTy,
261 ASTContext &Context) const;
262
263 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
264 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
265 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
266 it != ie; ++it)
267 it->info = classifyArgumentType(it->type, Context);
268 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000269
270 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
271 CodeGenFunction &CGF) const;
Eli Friedman5e175802009-03-23 23:26:24 +0000272
273 X86_32ABIInfo(bool d) : ABIInfo(), IsDarwin(d) {}
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000274};
275}
276
277ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
278 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +0000279 if (RetTy->isVoidType()) {
280 return ABIArgInfo::getIgnore();
281 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Eli Friedman5e175802009-03-23 23:26:24 +0000282 // Outside of Darwin, structs and unions are always indirect.
283 if (!IsDarwin && !RetTy->isAnyComplexType())
284 return ABIArgInfo::getIndirect(0);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000285 // Classify "single element" structs as their element type.
286 const FieldDecl *SeltFD = isSingleElementStruct(RetTy);
287 if (SeltFD) {
288 QualType SeltTy = SeltFD->getType()->getDesugaredType();
289 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
290 // FIXME: This is gross, it would be nice if we could just
291 // pass back SeltTy and have clients deal with it. Is it worth
292 // supporting coerce to both LLVM and clang Types?
293 if (BT->isIntegerType()) {
294 uint64_t Size = Context.getTypeSize(SeltTy);
295 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
296 } else if (BT->getKind() == BuiltinType::Float) {
297 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
298 } else if (BT->getKind() == BuiltinType::Double) {
299 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
300 }
301 } else if (SeltTy->isPointerType()) {
302 // FIXME: It would be really nice if this could come out as
303 // the proper pointer type.
304 llvm::Type *PtrTy =
305 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
306 return ABIArgInfo::getCoerce(PtrTy);
307 }
308 }
309
Daniel Dunbar73d66602008-09-10 07:04:09 +0000310 uint64_t Size = Context.getTypeSize(RetTy);
311 if (Size == 8) {
312 return ABIArgInfo::getCoerce(llvm::Type::Int8Ty);
313 } else if (Size == 16) {
314 return ABIArgInfo::getCoerce(llvm::Type::Int16Ty);
315 } else if (Size == 32) {
316 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
317 } else if (Size == 64) {
318 return ABIArgInfo::getCoerce(llvm::Type::Int64Ty);
319 } else {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000320 return ABIArgInfo::getIndirect(0);
Daniel Dunbar73d66602008-09-10 07:04:09 +0000321 }
Daniel Dunbare126ab12008-09-10 02:41:04 +0000322 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000323 return ABIArgInfo::getDirect();
Daniel Dunbare126ab12008-09-10 02:41:04 +0000324 }
325}
326
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000327ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000328 ASTContext &Context) const {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000329 // FIXME: Set alignment on indirect arguments.
Daniel Dunbar3158c592008-09-17 20:11:04 +0000330 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000331 // Structures with flexible arrays are always indirect.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000332 if (const RecordType *RT = Ty->getAsStructureType())
333 if (RT->getDecl()->hasFlexibleArrayMember())
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000334 return ABIArgInfo::getIndirect(0);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000335
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000336 // Ignore empty structs.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000337 uint64_t Size = Context.getTypeSize(Ty);
338 if (Ty->isStructureType() && Size == 0)
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000339 return ABIArgInfo::getIgnore();
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000340
341 // Expand structs with size <= 128-bits which consist only of
342 // basic types (int, long long, float, double, xxx*). This is
343 // non-recursive and does not ignore empty fields.
344 if (const RecordType *RT = Ty->getAsStructureType()) {
345 if (Context.getTypeSize(Ty) <= 4*32 &&
346 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
347 return ABIArgInfo::getExpand();
348 }
349
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000350 return ABIArgInfo::getIndirect(0);
Daniel Dunbar22e30052008-09-11 01:48:57 +0000351 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000352 return ABIArgInfo::getDirect();
Daniel Dunbar22e30052008-09-11 01:48:57 +0000353 }
354}
355
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000356llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
357 CodeGenFunction &CGF) const {
358 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
359 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
360
361 CGBuilderTy &Builder = CGF.Builder;
362 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
363 "ap");
364 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
365 llvm::Type *PTy =
366 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
367 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
368
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000369 uint64_t Offset =
370 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000371 llvm::Value *NextAddr =
372 Builder.CreateGEP(Addr,
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000373 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000374 "ap.next");
375 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
376
377 return AddrTyped;
378}
379
Daniel Dunbare09a9692009-01-24 08:32:22 +0000380namespace {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000381/// X86_64ABIInfo - The X86_64 ABI information.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000382class X86_64ABIInfo : public ABIInfo {
383 enum Class {
384 Integer = 0,
385 SSE,
386 SSEUp,
387 X87,
388 X87Up,
389 ComplexX87,
390 NoClass,
391 Memory
392 };
393
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000394 /// merge - Implement the X86_64 ABI merging algorithm.
395 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000396 /// Merge an accumulating classification \arg Accum with a field
397 /// classification \arg Field.
398 ///
399 /// \param Accum - The accumulating classification. This should
400 /// always be either NoClass or the result of a previous merge
401 /// call. In addition, this should never be Memory (the caller
402 /// should just return Memory for the aggregate).
403 Class merge(Class Accum, Class Field) const;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000404
Daniel Dunbare09a9692009-01-24 08:32:22 +0000405 /// classify - Determine the x86_64 register classes in which the
406 /// given type T should be passed.
407 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000408 /// \param Lo - The classification for the parts of the type
409 /// residing in the low word of the containing object.
410 ///
411 /// \param Hi - The classification for the parts of the type
412 /// residing in the high word of the containing object.
413 ///
414 /// \param OffsetBase - The bit offset of this type in the
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000415 /// containing object. Some parameters are classified different
416 /// depending on whether they straddle an eightbyte boundary.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000417 ///
418 /// If a word is unused its result will be NoClass; if a type should
419 /// be passed in Memory then at least the classification of \arg Lo
420 /// will be Memory.
421 ///
422 /// The \arg Lo class will be NoClass iff the argument is ignored.
423 ///
424 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
Daniel Dunbar92e88642009-02-17 07:55:55 +0000425 /// also be ComplexX87.
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000426 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000427 Class &Lo, Class &Hi) const;
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000428
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000429 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
430 /// to coerce to, chose the best way to pass Ty in the same place
431 /// that \arg CoerceTo would be passed, but while keeping the
432 /// emitted code as simple as possible.
433 ///
434 /// FIXME: Note, this should be cleaned up to just take an
435 /// enumeration of all the ways we might want to pass things,
436 /// instead of constructing an LLVM type. This makes this code more
437 /// explicit, and it makes it clearer that we are also doing this
438 /// for correctness in the case of passing scalar types.
439 ABIArgInfo getCoerceResult(QualType Ty,
440 const llvm::Type *CoerceTo,
441 ASTContext &Context) const;
442
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000443 ABIArgInfo classifyReturnType(QualType RetTy,
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000444 ASTContext &Context) const;
445
446 ABIArgInfo classifyArgumentType(QualType Ty,
447 ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000448 unsigned &neededInt,
449 unsigned &neededSSE) const;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000450
451public:
452 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000453
454 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
455 CodeGenFunction &CGF) const;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000456};
457}
458
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000459X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
460 Class Field) const {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000461 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
462 // classified recursively so that always two fields are
463 // considered. The resulting class is calculated according to
464 // the classes of the fields in the eightbyte:
465 //
466 // (a) If both classes are equal, this is the resulting class.
467 //
468 // (b) If one of the classes is NO_CLASS, the resulting class is
469 // the other class.
470 //
471 // (c) If one of the classes is MEMORY, the result is the MEMORY
472 // class.
473 //
474 // (d) If one of the classes is INTEGER, the result is the
475 // INTEGER.
476 //
477 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
478 // MEMORY is used as class.
479 //
480 // (f) Otherwise class SSE is used.
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000481
482 // Accum should never be memory (we should have returned) or
483 // ComplexX87 (because this cannot be passed in a structure).
484 assert((Accum != Memory && Accum != ComplexX87) &&
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000485 "Invalid accumulated classification during merge.");
486 if (Accum == Field || Field == NoClass)
487 return Accum;
488 else if (Field == Memory)
489 return Memory;
490 else if (Accum == NoClass)
491 return Field;
492 else if (Accum == Integer || Field == Integer)
493 return Integer;
494 else if (Field == X87 || Field == X87Up || Field == ComplexX87)
495 return Memory;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000496 else
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000497 return SSE;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000498}
499
Daniel Dunbare09a9692009-01-24 08:32:22 +0000500void X86_64ABIInfo::classify(QualType Ty,
501 ASTContext &Context,
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000502 uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000503 Class &Lo, Class &Hi) const {
Daniel Dunbar36b378e2009-02-02 18:06:39 +0000504 // FIXME: This code can be simplified by introducing a simple value
505 // class for Class pairs with appropriate constructor methods for
506 // the various situations.
507
Daniel Dunbard97f5952009-02-22 04:48:22 +0000508 // FIXME: Some of the split computations are wrong; unaligned
509 // vectors shouldn't be passed in registers for example, so there is
510 // no chance they can straddle an eightbyte. Verify & simplify.
511
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000512 Lo = Hi = NoClass;
513
514 Class &Current = OffsetBase < 64 ? Lo : Hi;
515 Current = Memory;
516
Daniel Dunbare09a9692009-01-24 08:32:22 +0000517 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
518 BuiltinType::Kind k = BT->getKind();
519
Daniel Dunbar1358b202009-01-26 21:26:08 +0000520 if (k == BuiltinType::Void) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000521 Current = NoClass;
Daniel Dunbar1358b202009-01-26 21:26:08 +0000522 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000523 Current = Integer;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000524 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000525 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000526 } else if (k == BuiltinType::LongDouble) {
527 Lo = X87;
528 Hi = X87Up;
529 }
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000530 // FIXME: _Decimal32 and _Decimal64 are SSE.
531 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Daniel Dunbare09a9692009-01-24 08:32:22 +0000532 // FIXME: __int128 is (Integer, Integer).
Anders Carlsson1d234462009-02-26 17:31:15 +0000533 } else if (const EnumType *ET = Ty->getAsEnumType()) {
534 // Classify the underlying integer type.
535 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
Daniel Dunbarfc096bf2009-02-26 20:52:22 +0000536 } else if (Ty->hasPointerRepresentation()) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000537 Current = Integer;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000538 } else if (const VectorType *VT = Ty->getAsVectorType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000539 uint64_t Size = Context.getTypeSize(VT);
Daniel Dunbard97f5952009-02-22 04:48:22 +0000540 if (Size == 32) {
541 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
542 // float> as integer.
543 Current = Integer;
544
545 // If this type crosses an eightbyte boundary, it should be
546 // split.
547 uint64_t EB_Real = (OffsetBase) / 64;
548 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
549 if (EB_Real != EB_Imag)
550 Hi = Lo;
551 } else if (Size == 64) {
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000552 // gcc passes <1 x double> in memory. :(
553 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
Daniel Dunbarcdf91e82009-01-30 19:38:39 +0000554 return;
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000555
556 // gcc passes <1 x long long> as INTEGER.
557 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
558 Current = Integer;
559 else
560 Current = SSE;
Daniel Dunbare413f532009-01-30 18:40:10 +0000561
562 // If this type crosses an eightbyte boundary, it should be
563 // split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000564 if (OffsetBase && OffsetBase != 64)
Daniel Dunbare413f532009-01-30 18:40:10 +0000565 Hi = Lo;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000566 } else if (Size == 128) {
567 Lo = SSE;
568 Hi = SSEUp;
569 }
Daniel Dunbare09a9692009-01-24 08:32:22 +0000570 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
Daniel Dunbare60d5332009-02-14 02:45:45 +0000571 QualType ET = Context.getCanonicalType(CT->getElementType());
Daniel Dunbare09a9692009-01-24 08:32:22 +0000572
Daniel Dunbare413f532009-01-30 18:40:10 +0000573 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000574 if (ET->isIntegralType()) {
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000575 if (Size <= 64)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000576 Current = Integer;
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000577 else if (Size <= 128)
578 Lo = Hi = Integer;
579 } else if (ET == Context.FloatTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000580 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000581 else if (ET == Context.DoubleTy)
582 Lo = Hi = SSE;
583 else if (ET == Context.LongDoubleTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000584 Current = ComplexX87;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000585
586 // If this complex type crosses an eightbyte boundary then it
587 // should be split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000588 uint64_t EB_Real = (OffsetBase) / 64;
589 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000590 if (Hi == NoClass && EB_Real != EB_Imag)
591 Hi = Lo;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000592 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
593 // Arrays are treated like structures.
594
595 uint64_t Size = Context.getTypeSize(Ty);
596
597 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
598 // than two eightbytes, ..., it has class MEMORY.
599 if (Size > 128)
600 return;
601
602 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
603 // fields, it has class MEMORY.
604 //
605 // Only need to check alignment of array base.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000606 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000607 return;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000608
609 // Otherwise implement simplified merge. We could be smarter about
610 // this, but it isn't worth it and would be harder to verify.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000611 Current = NoClass;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000612 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
613 uint64_t ArraySize = AT->getSize().getZExtValue();
614 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
615 Class FieldLo, FieldHi;
616 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000617 Lo = merge(Lo, FieldLo);
618 Hi = merge(Hi, FieldHi);
619 if (Lo == Memory || Hi == Memory)
620 break;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000621 }
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000622
623 // Do post merger cleanup (see below). Only case we worry about is Memory.
624 if (Hi == Memory)
625 Lo = Memory;
626 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000627 } else if (const RecordType *RT = Ty->getAsRecordType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000628 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000629
630 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
631 // than two eightbytes, ..., it has class MEMORY.
632 if (Size > 128)
633 return;
634
635 const RecordDecl *RD = RT->getDecl();
636
637 // Assume variable sized types are passed in memory.
638 if (RD->hasFlexibleArrayMember())
639 return;
640
641 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
642
643 // Reset Lo class, this will be recomputed.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000644 Current = NoClass;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000645 unsigned idx = 0;
646 for (RecordDecl::field_iterator i = RD->field_begin(),
647 e = RD->field_end(); i != e; ++i, ++idx) {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000648 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000649 bool BitField = i->isBitField();
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000650
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000651 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
652 // fields, it has class MEMORY.
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000653 //
654 // Note, skip this test for bitfields, see below.
655 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000656 Lo = Memory;
657 return;
658 }
659
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000660 // Classify this field.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000661 //
662 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
663 // exceeds a single eightbyte, each is classified
664 // separately. Each eightbyte gets initialized to class
665 // NO_CLASS.
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000666 Class FieldLo, FieldHi;
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000667
668 // Bitfields require special handling, they do not force the
669 // structure to be passed in memory even if unaligned, and
670 // therefore they can straddle an eightbyte.
671 if (BitField) {
672 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
673 uint64_t Size =
674 i->getBitWidth()->getIntegerConstantExprValue(Context).getZExtValue();
675
676 uint64_t EB_Lo = Offset / 64;
677 uint64_t EB_Hi = (Offset + Size - 1) / 64;
678 FieldLo = FieldHi = NoClass;
679 if (EB_Lo) {
680 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
681 FieldLo = NoClass;
682 FieldHi = Integer;
683 } else {
684 FieldLo = Integer;
685 FieldHi = EB_Hi ? Integer : NoClass;
686 }
687 } else
688 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000689 Lo = merge(Lo, FieldLo);
690 Hi = merge(Hi, FieldHi);
691 if (Lo == Memory || Hi == Memory)
692 break;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000693 }
694
695 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
696 //
697 // (a) If one of the classes is MEMORY, the whole argument is
698 // passed in memory.
699 //
700 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
701
702 // The first of these conditions is guaranteed by how we implement
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000703 // the merge (just bail).
704 //
705 // The second condition occurs in the case of unions; for example
706 // union { _Complex double; unsigned; }.
707 if (Hi == Memory)
708 Lo = Memory;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000709 if (Hi == SSEUp && Lo != SSE)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000710 Hi = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000711 }
712}
713
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000714ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
715 const llvm::Type *CoerceTo,
716 ASTContext &Context) const {
717 if (CoerceTo == llvm::Type::Int64Ty) {
718 // Integer and pointer types will end up in a general purpose
719 // register.
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000720 if (Ty->isIntegralType() || Ty->isPointerType())
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000721 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000722
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000723 } else if (CoerceTo == llvm::Type::DoubleTy) {
Daniel Dunbare60d5332009-02-14 02:45:45 +0000724 // FIXME: It would probably be better to make CGFunctionInfo only
725 // map using canonical types than to canonize here.
726 QualType CTy = Context.getCanonicalType(Ty);
727
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000728 // Float and double end up in a single SSE reg.
Daniel Dunbare60d5332009-02-14 02:45:45 +0000729 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000730 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000731
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000732 }
733
734 return ABIArgInfo::getCoerce(CoerceTo);
735}
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000736
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000737ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
738 ASTContext &Context) const {
Daniel Dunbare09a9692009-01-24 08:32:22 +0000739 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
740 // classification algorithm.
741 X86_64ABIInfo::Class Lo, Hi;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000742 classify(RetTy, Context, 0, Lo, Hi);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000743
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000744 // Check some invariants.
745 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
746 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
747 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
748
Daniel Dunbare09a9692009-01-24 08:32:22 +0000749 const llvm::Type *ResType = 0;
750 switch (Lo) {
751 case NoClass:
Daniel Dunbar1358b202009-01-26 21:26:08 +0000752 return ABIArgInfo::getIgnore();
Daniel Dunbare09a9692009-01-24 08:32:22 +0000753
754 case SSEUp:
755 case X87Up:
756 assert(0 && "Invalid classification for lo word.");
757
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000758 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000759 // hidden argument.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000760 case Memory:
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000761 return ABIArgInfo::getIndirect(0);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000762
763 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
764 // available register of the sequence %rax, %rdx is used.
765 case Integer:
766 ResType = llvm::Type::Int64Ty; break;
767
768 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
769 // available SSE register of the sequence %xmm0, %xmm1 is used.
770 case SSE:
771 ResType = llvm::Type::DoubleTy; break;
772
773 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
774 // returned on the X87 stack in %st0 as 80-bit x87 number.
775 case X87:
776 ResType = llvm::Type::X86_FP80Ty; break;
777
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000778 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
779 // part of the value is returned in %st0 and the imaginary part in
780 // %st1.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000781 case ComplexX87:
Daniel Dunbar92e88642009-02-17 07:55:55 +0000782 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Daniel Dunbar4fc0d492009-02-18 03:44:19 +0000783 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
784 llvm::Type::X86_FP80Ty,
785 NULL);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000786 break;
787 }
788
789 switch (Hi) {
Daniel Dunbar92e88642009-02-17 07:55:55 +0000790 // Memory was handled previously and X87 should
791 // never occur as a hi class.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000792 case Memory:
793 case X87:
Daniel Dunbare09a9692009-01-24 08:32:22 +0000794 assert(0 && "Invalid classification for hi word.");
795
Daniel Dunbar92e88642009-02-17 07:55:55 +0000796 case ComplexX87: // Previously handled.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000797 case NoClass: break;
Daniel Dunbar92e88642009-02-17 07:55:55 +0000798
Daniel Dunbare09a9692009-01-24 08:32:22 +0000799 case Integer:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000800 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
801 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000802 case SSE:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000803 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
804 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000805
806 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
807 // is passed in the upper half of the last used SSE register.
808 //
809 // SSEUP should always be preceeded by SSE, just widen.
810 case SSEUp:
811 assert(Lo == SSE && "Unexpected SSEUp classification.");
812 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
813 break;
814
815 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000816 // returned together with the previous X87 value in %st0.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000817 case X87Up:
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000818 // If X87Up is preceeded by X87, we don't need to do
819 // anything. However, in some cases with unions it may not be
820 // preceeded by X87. In such situations we follow gcc and pass the
821 // extra bits in an SSE reg.
822 if (Lo != X87)
823 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000824 break;
825 }
826
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000827 return getCoerceResult(RetTy, ResType, Context);
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000828}
829
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000830ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000831 unsigned &neededInt,
832 unsigned &neededSSE) const {
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000833 X86_64ABIInfo::Class Lo, Hi;
834 classify(Ty, Context, 0, Lo, Hi);
835
836 // Check some invariants.
837 // FIXME: Enforce these by construction.
838 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
839 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
840 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
841
Daniel Dunbare978cb92009-02-10 17:06:09 +0000842 neededInt = 0;
843 neededSSE = 0;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000844 const llvm::Type *ResType = 0;
845 switch (Lo) {
846 case NoClass:
847 return ABIArgInfo::getIgnore();
848
849 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
850 // on the stack.
851 case Memory:
852
853 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
854 // COMPLEX_X87, it is passed in memory.
855 case X87:
856 case ComplexX87:
Daniel Dunbard0536ac2009-02-22 08:17:51 +0000857 return ABIArgInfo::getIndirect(0);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000858
859 case SSEUp:
860 case X87Up:
861 assert(0 && "Invalid classification for lo word.");
862
863 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
864 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
865 // and %r9 is used.
866 case Integer:
867 ++neededInt;
868 ResType = llvm::Type::Int64Ty;
869 break;
870
871 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
872 // available SSE register is used, the registers are taken in the
873 // order from %xmm0 to %xmm7.
874 case SSE:
875 ++neededSSE;
876 ResType = llvm::Type::DoubleTy;
877 break;
Daniel Dunbareec02622009-02-03 06:30:17 +0000878 }
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000879
880 switch (Hi) {
881 // Memory was handled previously, ComplexX87 and X87 should
882 // never occur as hi classes, and X87Up must be preceed by X87,
883 // which is passed in memory.
884 case Memory:
885 case X87:
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000886 case ComplexX87:
887 assert(0 && "Invalid classification for hi word.");
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000888 break;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000889
890 case NoClass: break;
891 case Integer:
892 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
893 ++neededInt;
894 break;
Daniel Dunbar78d7d452009-03-06 17:50:25 +0000895
896 // X87Up generally doesn't occur here (long double is passed in
897 // memory), except in situations involving unions.
898 case X87Up:
899 case SSE:
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000900 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
901 ++neededSSE;
902 break;
903
904 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
905 // eightbyte is passed in the upper half of the last used SSE
906 // register.
907 case SSEUp:
908 assert(Lo == SSE && "Unexpected SSEUp classification.");
909 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
910 break;
911 }
912
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000913 return getCoerceResult(Ty, ResType, Context);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000914}
915
916void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
917 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
918
919 // Keep track of the number of assigned registers.
920 unsigned freeIntRegs = 6, freeSSERegs = 8;
921
922 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
923 // get assigned (in left-to-right order) for passing as follows...
924 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Daniel Dunbare978cb92009-02-10 17:06:09 +0000925 it != ie; ++it) {
926 unsigned neededInt, neededSSE;
927 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
928
929 // AMD64-ABI 3.2.3p3: If there are no registers available for any
930 // eightbyte of an argument, the whole argument is passed on the
931 // stack. If registers have already been assigned for some
932 // eightbytes of such an argument, the assignments get reverted.
933 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
934 freeIntRegs -= neededInt;
935 freeSSERegs -= neededSSE;
936 } else {
Daniel Dunbard0536ac2009-02-22 08:17:51 +0000937 it->info = ABIArgInfo::getIndirect(0);
Daniel Dunbare978cb92009-02-10 17:06:09 +0000938 }
939 }
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000940}
941
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000942static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
943 QualType Ty,
944 CodeGenFunction &CGF) {
945 llvm::Value *overflow_arg_area_p =
946 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
947 llvm::Value *overflow_arg_area =
948 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
949
950 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
951 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000952 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000953 if (Align > 8) {
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000954 // Note that we follow the ABI & gcc here, even though the type
955 // could in theory have an alignment greater than 16. This case
956 // shouldn't ever matter in practice.
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000957
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000958 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
959 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
960 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
961 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
962 llvm::Type::Int64Ty);
963 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
964 overflow_arg_area =
965 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
966 overflow_arg_area->getType(),
967 "overflow_arg_area.align");
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000968 }
969
970 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
971 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
972 llvm::Value *Res =
973 CGF.Builder.CreateBitCast(overflow_arg_area,
974 llvm::PointerType::getUnqual(LTy));
975
976 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
977 // l->overflow_arg_area + sizeof(type).
978 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
979 // an 8 byte boundary.
980
981 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
982 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
983 (SizeInBytes + 7) & ~7);
984 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
985 "overflow_arg_area.next");
986 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
987
988 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
989 return Res;
990}
991
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000992llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
993 CodeGenFunction &CGF) const {
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000994 // Assume that va_list type is correct; should be pointer to LLVM type:
995 // struct {
996 // i32 gp_offset;
997 // i32 fp_offset;
998 // i8* overflow_arg_area;
999 // i8* reg_save_area;
1000 // };
1001 unsigned neededInt, neededSSE;
1002 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1003 neededInt, neededSSE);
1004
1005 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1006 // in the registers. If not go to step 7.
1007 if (!neededInt && !neededSSE)
1008 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1009
1010 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1011 // general purpose registers needed to pass type and num_fp to hold
1012 // the number of floating point registers needed.
1013
1014 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1015 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1016 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1017 //
1018 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1019 // register save space).
1020
1021 llvm::Value *InRegs = 0;
1022 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1023 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1024 if (neededInt) {
1025 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1026 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1027 InRegs =
1028 CGF.Builder.CreateICmpULE(gp_offset,
1029 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1030 48 - neededInt * 8),
1031 "fits_in_gp");
1032 }
1033
1034 if (neededSSE) {
1035 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1036 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1037 llvm::Value *FitsInFP =
1038 CGF.Builder.CreateICmpULE(fp_offset,
1039 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar63118762009-02-18 22:19:44 +00001040 176 - neededSSE * 16),
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001041 "fits_in_fp");
Daniel Dunbar72198842009-02-18 22:05:01 +00001042 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001043 }
1044
1045 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1046 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1047 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1048 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1049
1050 // Emit code to load the value if it was passed in registers.
1051
1052 CGF.EmitBlock(InRegBlock);
1053
1054 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1055 // an offset of l->gp_offset and/or l->fp_offset. This may require
1056 // copying to a temporary location in case the parameter is passed
1057 // in different register classes or requires an alignment greater
1058 // than 8 for general purpose registers and 16 for XMM registers.
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001059 //
1060 // FIXME: This really results in shameful code when we end up
1061 // needing to collect arguments from different places; often what
1062 // should result in a simple assembling of a structure from
1063 // scattered addresses has many more loads than necessary. Can we
1064 // clean this up?
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001065 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1066 llvm::Value *RegAddr =
1067 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1068 "reg_save_area");
1069 if (neededInt && neededSSE) {
Daniel Dunbara96ec382009-02-13 17:46:31 +00001070 // FIXME: Cleanup.
1071 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1072 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1073 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1074 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1075 const llvm::Type *TyLo = ST->getElementType(0);
1076 const llvm::Type *TyHi = ST->getElementType(1);
1077 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1078 "Unexpected ABI info for mixed regs");
1079 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1080 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1081 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1082 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1083 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1084 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1085 llvm::Value *V =
1086 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1087 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1088 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1089 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1090
1091 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001092 } else if (neededInt) {
1093 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1094 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1095 llvm::PointerType::getUnqual(LTy));
1096 } else {
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001097 if (neededSSE == 1) {
1098 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1099 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1100 llvm::PointerType::getUnqual(LTy));
1101 } else {
1102 assert(neededSSE == 2 && "Invalid number of needed registers!");
1103 // SSE registers are spaced 16 bytes apart in the register save
1104 // area, we need to collect the two eightbytes together.
1105 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1106 llvm::Value *RegAddrHi =
1107 CGF.Builder.CreateGEP(RegAddrLo,
1108 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1109 const llvm::Type *DblPtrTy =
1110 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1111 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1112 llvm::Type::DoubleTy,
1113 NULL);
1114 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1115 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1116 DblPtrTy));
1117 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1118 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1119 DblPtrTy));
1120 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1121 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1122 llvm::PointerType::getUnqual(LTy));
1123 }
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001124 }
1125
1126 // AMD64-ABI 3.5.7p5: Step 5. Set:
1127 // l->gp_offset = l->gp_offset + num_gp * 8
1128 // l->fp_offset = l->fp_offset + num_fp * 16.
1129 if (neededInt) {
1130 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1131 neededInt * 8);
1132 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1133 gp_offset_p);
1134 }
1135 if (neededSSE) {
1136 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1137 neededSSE * 16);
1138 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1139 fp_offset_p);
1140 }
1141 CGF.EmitBranch(ContBlock);
1142
1143 // Emit code to load the value if it was passed in memory.
1144
1145 CGF.EmitBlock(InMemBlock);
1146 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1147
1148 // Return the appropriate result.
1149
1150 CGF.EmitBlock(ContBlock);
1151 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1152 "vaarg.addr");
1153 ResAddr->reserveOperandSpace(2);
1154 ResAddr->addIncoming(RegAddr, InRegBlock);
1155 ResAddr->addIncoming(MemAddr, InMemBlock);
1156
1157 return ResAddr;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001158}
1159
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001160ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001161 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001162 if (RetTy->isVoidType()) {
1163 return ABIArgInfo::getIgnore();
1164 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001165 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001166 } else {
1167 return ABIArgInfo::getDirect();
1168 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001169}
1170
1171ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001172 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001173 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001174 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001175 } else {
1176 return ABIArgInfo::getDirect();
1177 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001178}
1179
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001180llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1181 CodeGenFunction &CGF) const {
1182 return 0;
1183}
1184
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001185const ABIInfo &CodeGenTypes::getABIInfo() const {
1186 if (TheABIInfo)
1187 return *TheABIInfo;
1188
1189 // For now we just cache this in the CodeGenTypes and don't bother
1190 // to free it.
1191 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1192 if (strcmp(TargetPrefix, "x86") == 0) {
Eli Friedman5e175802009-03-23 23:26:24 +00001193 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001194 switch (getContext().Target.getPointerWidth(0)) {
1195 case 32:
Eli Friedman5e175802009-03-23 23:26:24 +00001196 return *(TheABIInfo = new X86_32ABIInfo(IsDarwin));
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001197 case 64:
Daniel Dunbar56555952009-01-30 18:47:53 +00001198 return *(TheABIInfo = new X86_64ABIInfo());
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001199 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001200 }
1201
1202 return *(TheABIInfo = new DefaultABIInfo);
1203}
1204
Daniel Dunbare126ab12008-09-10 02:41:04 +00001205/***/
1206
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001207CGFunctionInfo::CGFunctionInfo(QualType ResTy,
1208 const llvm::SmallVector<QualType, 16> &ArgTys) {
1209 NumArgs = ArgTys.size();
1210 Args = new ArgInfo[1 + NumArgs];
1211 Args[0].type = ResTy;
1212 for (unsigned i = 0; i < NumArgs; ++i)
1213 Args[1 + i].type = ArgTys[i];
1214}
1215
1216/***/
1217
Daniel Dunbar04d35782008-09-17 00:51:38 +00001218void CodeGenTypes::GetExpandedTypes(QualType Ty,
1219 std::vector<const llvm::Type*> &ArgTys) {
1220 const RecordType *RT = Ty->getAsStructureType();
1221 assert(RT && "Can only expand structure types.");
1222 const RecordDecl *RD = RT->getDecl();
1223 assert(!RD->hasFlexibleArrayMember() &&
1224 "Cannot expand structure with flexible array.");
1225
Douglas Gregor5d764842009-01-09 17:18:27 +00001226 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar04d35782008-09-17 00:51:38 +00001227 e = RD->field_end(); i != e; ++i) {
1228 const FieldDecl *FD = *i;
1229 assert(!FD->isBitField() &&
1230 "Cannot expand structure with bit-field members.");
1231
1232 QualType FT = FD->getType();
1233 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1234 GetExpandedTypes(FT, ArgTys);
1235 } else {
1236 ArgTys.push_back(ConvertType(FT));
1237 }
1238 }
1239}
1240
1241llvm::Function::arg_iterator
1242CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1243 llvm::Function::arg_iterator AI) {
1244 const RecordType *RT = Ty->getAsStructureType();
1245 assert(RT && "Can only expand structure types.");
1246
1247 RecordDecl *RD = RT->getDecl();
1248 assert(LV.isSimple() &&
1249 "Unexpected non-simple lvalue during struct expansion.");
1250 llvm::Value *Addr = LV.getAddress();
1251 for (RecordDecl::field_iterator i = RD->field_begin(),
1252 e = RD->field_end(); i != e; ++i) {
1253 FieldDecl *FD = *i;
1254 QualType FT = FD->getType();
1255
1256 // FIXME: What are the right qualifiers here?
1257 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1258 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1259 AI = ExpandTypeFromArgs(FT, LV, AI);
1260 } else {
1261 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
1262 ++AI;
1263 }
1264 }
1265
1266 return AI;
1267}
1268
1269void
1270CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1271 llvm::SmallVector<llvm::Value*, 16> &Args) {
1272 const RecordType *RT = Ty->getAsStructureType();
1273 assert(RT && "Can only expand structure types.");
1274
1275 RecordDecl *RD = RT->getDecl();
1276 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1277 llvm::Value *Addr = RV.getAggregateAddr();
1278 for (RecordDecl::field_iterator i = RD->field_begin(),
1279 e = RD->field_end(); i != e; ++i) {
1280 FieldDecl *FD = *i;
1281 QualType FT = FD->getType();
1282
1283 // FIXME: What are the right qualifiers here?
1284 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1285 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1286 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
1287 } else {
1288 RValue RV = EmitLoadOfLValue(LV, FT);
1289 assert(RV.isScalar() &&
1290 "Unexpected non-scalar rvalue during struct expansion.");
1291 Args.push_back(RV.getScalarVal());
1292 }
1293 }
1294}
1295
Daniel Dunbar84379912009-02-02 19:06:38 +00001296/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1297/// a pointer to an object of type \arg Ty.
1298///
1299/// This safely handles the case when the src type is smaller than the
1300/// destination type; in this situation the values of bits which not
1301/// present in the src are undefined.
1302static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
1303 const llvm::Type *Ty,
1304 CodeGenFunction &CGF) {
1305 const llvm::Type *SrcTy =
1306 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
1307 uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy);
1308 uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(Ty);
1309
Daniel Dunbar77071992009-02-03 05:59:18 +00001310 // If load is legal, just bitcast the src pointer.
Daniel Dunbar84379912009-02-02 19:06:38 +00001311 if (SrcSize == DstSize) {
1312 llvm::Value *Casted =
1313 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001314 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1315 // FIXME: Use better alignment / avoid requiring aligned load.
1316 Load->setAlignment(1);
1317 return Load;
Daniel Dunbar84379912009-02-02 19:06:38 +00001318 } else {
1319 assert(SrcSize < DstSize && "Coercion is losing source bits!");
1320
1321 // Otherwise do coercion through memory. This is stupid, but
1322 // simple.
1323 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
1324 llvm::Value *Casted =
1325 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001326 llvm::StoreInst *Store =
1327 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
1328 // FIXME: Use better alignment / avoid requiring aligned store.
1329 Store->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001330 return CGF.Builder.CreateLoad(Tmp);
1331 }
1332}
1333
1334/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1335/// where the source and destination may have different types.
1336///
1337/// This safely handles the case when the src type is larger than the
1338/// destination type; the upper bits of the src will be lost.
1339static void CreateCoercedStore(llvm::Value *Src,
1340 llvm::Value *DstPtr,
1341 CodeGenFunction &CGF) {
1342 const llvm::Type *SrcTy = Src->getType();
1343 const llvm::Type *DstTy =
1344 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1345
1346 uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy);
1347 uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(DstTy);
1348
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001349 // If store is legal, just bitcast the src pointer.
Daniel Dunbar84379912009-02-02 19:06:38 +00001350 if (SrcSize == DstSize) {
1351 llvm::Value *Casted =
1352 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001353 // FIXME: Use better alignment / avoid requiring aligned store.
1354 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001355 } else {
1356 assert(SrcSize > DstSize && "Coercion is missing bits!");
1357
1358 // Otherwise do coercion through memory. This is stupid, but
1359 // simple.
1360 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1361 CGF.Builder.CreateStore(Src, Tmp);
1362 llvm::Value *Casted =
1363 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001364 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1365 // FIXME: Use better alignment / avoid requiring aligned load.
1366 Load->setAlignment(1);
1367 CGF.Builder.CreateStore(Load, DstPtr);
Daniel Dunbar84379912009-02-02 19:06:38 +00001368 }
1369}
1370
Daniel Dunbar04d35782008-09-17 00:51:38 +00001371/***/
1372
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001373bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001374 return FI.getReturnInfo().isIndirect();
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001375}
1376
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001377const llvm::FunctionType *
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001378CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001379 std::vector<const llvm::Type*> ArgTys;
1380
1381 const llvm::Type *ResultType = 0;
1382
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001383 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001384 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar22e30052008-09-11 01:48:57 +00001385 switch (RetAI.getKind()) {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001386 case ABIArgInfo::Expand:
1387 assert(0 && "Invalid ABI kind for return argument");
1388
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001389 case ABIArgInfo::Direct:
1390 ResultType = ConvertType(RetTy);
1391 break;
1392
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001393 case ABIArgInfo::Indirect: {
1394 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001395 ResultType = llvm::Type::VoidTy;
Daniel Dunbara9976a22008-09-10 07:00:50 +00001396 const llvm::Type *STy = ConvertType(RetTy);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001397 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
1398 break;
1399 }
1400
Daniel Dunbar1358b202009-01-26 21:26:08 +00001401 case ABIArgInfo::Ignore:
1402 ResultType = llvm::Type::VoidTy;
1403 break;
1404
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001405 case ABIArgInfo::Coerce:
Daniel Dunbar73d66602008-09-10 07:04:09 +00001406 ResultType = RetAI.getCoerceToType();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001407 break;
1408 }
1409
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001410 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1411 ie = FI.arg_end(); it != ie; ++it) {
1412 const ABIArgInfo &AI = it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001413
1414 switch (AI.getKind()) {
Daniel Dunbar1358b202009-01-26 21:26:08 +00001415 case ABIArgInfo::Ignore:
1416 break;
1417
Daniel Dunbar04d35782008-09-17 00:51:38 +00001418 case ABIArgInfo::Coerce:
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001419 ArgTys.push_back(AI.getCoerceToType());
1420 break;
1421
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001422 case ABIArgInfo::Indirect: {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001423 // indirect arguments are always on the stack, which is addr space #0.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001424 const llvm::Type *LTy = ConvertTypeForMem(it->type);
1425 ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001426 break;
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001427 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001428
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001429 case ABIArgInfo::Direct:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001430 ArgTys.push_back(ConvertType(it->type));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001431 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001432
1433 case ABIArgInfo::Expand:
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001434 GetExpandedTypes(it->type, ArgTys);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001435 break;
1436 }
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001437 }
1438
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001439 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +00001440}
1441
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001442void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001443 const Decl *TargetDecl,
Devang Patela85a9ef2008-09-25 21:02:23 +00001444 AttributeListType &PAL) {
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001445 unsigned FuncAttrs = 0;
Devang Patel2bb6eb82008-09-26 22:53:57 +00001446 unsigned RetAttrs = 0;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001447
1448 if (TargetDecl) {
1449 if (TargetDecl->getAttr<NoThrowAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001450 FuncAttrs |= llvm::Attribute::NoUnwind;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001451 if (TargetDecl->getAttr<NoReturnAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001452 FuncAttrs |= llvm::Attribute::NoReturn;
Anders Carlssondd6791c2008-10-05 23:32:53 +00001453 if (TargetDecl->getAttr<PureAttr>())
1454 FuncAttrs |= llvm::Attribute::ReadOnly;
1455 if (TargetDecl->getAttr<ConstAttr>())
1456 FuncAttrs |= llvm::Attribute::ReadNone;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001457 }
1458
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001459 QualType RetTy = FI.getReturnType();
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001460 unsigned Index = 1;
Daniel Dunbar77071992009-02-03 05:59:18 +00001461 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001462 switch (RetAI.getKind()) {
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001463 case ABIArgInfo::Direct:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001464 if (RetTy->isPromotableIntegerType()) {
1465 if (RetTy->isSignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001466 RetAttrs |= llvm::Attribute::SExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001467 } else if (RetTy->isUnsignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001468 RetAttrs |= llvm::Attribute::ZExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001469 }
1470 }
1471 break;
1472
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001473 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001474 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00001475 llvm::Attribute::StructRet |
1476 llvm::Attribute::NoAlias));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001477 ++Index;
Daniel Dunbar39ea2c12009-03-18 19:51:01 +00001478 // sret disables readnone and readonly
1479 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1480 llvm::Attribute::ReadNone);
Daniel Dunbare126ab12008-09-10 02:41:04 +00001481 break;
1482
Daniel Dunbar1358b202009-01-26 21:26:08 +00001483 case ABIArgInfo::Ignore:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001484 case ABIArgInfo::Coerce:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001485 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001486
Daniel Dunbar22e30052008-09-11 01:48:57 +00001487 case ABIArgInfo::Expand:
1488 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001489 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001490
Devang Patel2bb6eb82008-09-26 22:53:57 +00001491 if (RetAttrs)
1492 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001493 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1494 ie = FI.arg_end(); it != ie; ++it) {
1495 QualType ParamType = it->type;
1496 const ABIArgInfo &AI = it->info;
Devang Patela85a9ef2008-09-25 21:02:23 +00001497 unsigned Attributes = 0;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001498
1499 switch (AI.getKind()) {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001500 case ABIArgInfo::Coerce:
1501 break;
1502
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001503 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001504 Attributes |= llvm::Attribute::ByVal;
Daniel Dunbarb3f651a2009-02-05 01:31:19 +00001505 Attributes |=
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001506 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar39ea2c12009-03-18 19:51:01 +00001507 // byval disables readnone and readonly.
1508 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1509 llvm::Attribute::ReadNone);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001510 break;
1511
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001512 case ABIArgInfo::Direct:
Daniel Dunbar22e30052008-09-11 01:48:57 +00001513 if (ParamType->isPromotableIntegerType()) {
1514 if (ParamType->isSignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001515 Attributes |= llvm::Attribute::SExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001516 } else if (ParamType->isUnsignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001517 Attributes |= llvm::Attribute::ZExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001518 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001519 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001520 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001521
Daniel Dunbar1358b202009-01-26 21:26:08 +00001522 case ABIArgInfo::Ignore:
1523 // Skip increment, no matching LLVM parameter.
1524 continue;
1525
Daniel Dunbar04d35782008-09-17 00:51:38 +00001526 case ABIArgInfo::Expand: {
1527 std::vector<const llvm::Type*> Tys;
1528 // FIXME: This is rather inefficient. Do we ever actually need
1529 // to do anything here? The result should be just reconstructed
1530 // on the other side, so extension should be a non-issue.
1531 getTypes().GetExpandedTypes(ParamType, Tys);
1532 Index += Tys.size();
1533 continue;
1534 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001535 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001536
Devang Patela85a9ef2008-09-25 21:02:23 +00001537 if (Attributes)
1538 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar04d35782008-09-17 00:51:38 +00001539 ++Index;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001540 }
Devang Patel2bb6eb82008-09-26 22:53:57 +00001541 if (FuncAttrs)
1542 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001543}
1544
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001545void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1546 llvm::Function *Fn,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001547 const FunctionArgList &Args) {
Daniel Dunbar5b7ac652009-02-03 06:02:10 +00001548 // FIXME: We no longer need the types from FunctionArgList; lift up
1549 // and simplify.
1550
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001551 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1552 llvm::Function::arg_iterator AI = Fn->arg_begin();
1553
1554 // Name the struct return argument.
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001555 if (CGM.ReturnTypeUsesSret(FI)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001556 AI->setName("agg.result");
1557 ++AI;
1558 }
Daniel Dunbar77071992009-02-03 05:59:18 +00001559
Daniel Dunbar14c884a2009-02-04 21:17:21 +00001560 assert(FI.arg_size() == Args.size() &&
1561 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00001562 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001563 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00001564 i != e; ++i, ++info_it) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001565 const VarDecl *Arg = i->first;
Daniel Dunbar77071992009-02-03 05:59:18 +00001566 QualType Ty = info_it->type;
1567 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001568
1569 switch (ArgI.getKind()) {
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001570 case ABIArgInfo::Indirect: {
1571 llvm::Value* V = AI;
1572 if (hasAggregateLLVMType(Ty)) {
1573 // Do nothing, aggregates and complex variables are accessed by
1574 // reference.
1575 } else {
1576 // Load scalar value from indirect argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001577 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001578 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1579 // This must be a promotion, for something like
1580 // "void a(x) short x; {..."
1581 V = EmitScalarConversion(V, Ty, Arg->getType());
1582 }
1583 }
1584 EmitParmDecl(*Arg, V);
1585 break;
1586 }
1587
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001588 case ABIArgInfo::Direct: {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001589 assert(AI != Fn->arg_end() && "Argument mismatch!");
1590 llvm::Value* V = AI;
Daniel Dunbarcc811502009-02-05 11:13:54 +00001591 if (hasAggregateLLVMType(Ty)) {
1592 // Create a temporary alloca to hold the argument; the rest of
1593 // codegen expects to access aggregates & complex values by
1594 // reference.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001595 V = CreateTempAlloca(ConvertTypeForMem(Ty));
Daniel Dunbarcc811502009-02-05 11:13:54 +00001596 Builder.CreateStore(AI, V);
1597 } else {
1598 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1599 // This must be a promotion, for something like
1600 // "void a(x) short x; {..."
1601 V = EmitScalarConversion(V, Ty, Arg->getType());
1602 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001603 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001604 EmitParmDecl(*Arg, V);
1605 break;
1606 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001607
1608 case ABIArgInfo::Expand: {
Daniel Dunbar77071992009-02-03 05:59:18 +00001609 // If this structure was expanded into multiple arguments then
Daniel Dunbar04d35782008-09-17 00:51:38 +00001610 // we need to create a temporary and reconstruct it from the
1611 // arguments.
Chris Lattner6c5ec622008-11-24 04:00:27 +00001612 std::string Name = Arg->getNameAsString();
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001613 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
Daniel Dunbar04d35782008-09-17 00:51:38 +00001614 (Name + ".addr").c_str());
1615 // FIXME: What are the right qualifiers here?
1616 llvm::Function::arg_iterator End =
1617 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
1618 EmitParmDecl(*Arg, Temp);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001619
Daniel Dunbar04d35782008-09-17 00:51:38 +00001620 // Name the arguments used in expansion and increment AI.
1621 unsigned Index = 0;
1622 for (; AI != End; ++AI, ++Index)
1623 AI->setName(Name + "." + llvm::utostr(Index));
1624 continue;
1625 }
Daniel Dunbar1358b202009-01-26 21:26:08 +00001626
1627 case ABIArgInfo::Ignore:
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001628 // Initialize the local variable appropriately.
1629 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001630 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001631 } else {
1632 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
1633 }
1634
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001635 // Skip increment, no matching LLVM parameter.
1636 continue;
Daniel Dunbar1358b202009-01-26 21:26:08 +00001637
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001638 case ABIArgInfo::Coerce: {
1639 assert(AI != Fn->arg_end() && "Argument mismatch!");
1640 // FIXME: This is very wasteful; EmitParmDecl is just going to
1641 // drop the result in a new alloca anyway, so we could just
1642 // store into that directly if we broke the abstraction down
1643 // more.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001644 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001645 CreateCoercedStore(AI, V, *this);
1646 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001647 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001648 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001649 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1650 // This must be a promotion, for something like
1651 // "void a(x) short x; {..."
1652 V = EmitScalarConversion(V, Ty, Arg->getType());
1653 }
1654 }
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001655 EmitParmDecl(*Arg, V);
1656 break;
1657 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001658 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001659
1660 ++AI;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001661 }
1662 assert(AI == Fn->arg_end() && "Argument mismatch!");
1663}
1664
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001665void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001666 llvm::Value *ReturnValue) {
Daniel Dunbare126ab12008-09-10 02:41:04 +00001667 llvm::Value *RV = 0;
1668
1669 // Functions with no result always return void.
1670 if (ReturnValue) {
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001671 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001672 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbare126ab12008-09-10 02:41:04 +00001673
1674 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001675 case ABIArgInfo::Indirect:
Daniel Dunbar17d35372008-12-18 04:52:14 +00001676 if (RetTy->isAnyComplexType()) {
Daniel Dunbar17d35372008-12-18 04:52:14 +00001677 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1678 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1679 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1680 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
1681 } else {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001682 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
1683 false);
Daniel Dunbar17d35372008-12-18 04:52:14 +00001684 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001685 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001686
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001687 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00001688 // The internal return value temp always will have
1689 // pointer-to-return-type type.
Daniel Dunbare126ab12008-09-10 02:41:04 +00001690 RV = Builder.CreateLoad(ReturnValue);
1691 break;
1692
Daniel Dunbar1358b202009-01-26 21:26:08 +00001693 case ABIArgInfo::Ignore:
1694 break;
1695
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001696 case ABIArgInfo::Coerce:
Daniel Dunbar708d8a82009-01-27 01:36:03 +00001697 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001698 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001699
Daniel Dunbar22e30052008-09-11 01:48:57 +00001700 case ABIArgInfo::Expand:
1701 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001702 }
1703 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001704
1705 if (RV) {
1706 Builder.CreateRet(RV);
1707 } else {
1708 Builder.CreateRetVoid();
1709 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001710}
1711
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001712RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
1713 llvm::Value *Callee,
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00001714 const CallArgList &CallArgs,
1715 const Decl *TargetDecl) {
Daniel Dunbar5b7ac652009-02-03 06:02:10 +00001716 // FIXME: We no longer need the types from CallArgs; lift up and
1717 // simplify.
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001718 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001719
1720 // Handle struct-return functions by passing a pointer to the
1721 // location that we would like to return into.
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001722 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001723 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Daniel Dunbar32cae462009-02-05 09:24:53 +00001724 if (CGM.ReturnTypeUsesSret(CallInfo)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001725 // Create a temporary alloca to hold the result of the call. :(
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001726 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001727 }
1728
Daniel Dunbar14c884a2009-02-04 21:17:21 +00001729 assert(CallInfo.arg_size() == CallArgs.size() &&
1730 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00001731 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001732 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00001733 I != E; ++I, ++info_it) {
1734 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001735 RValue RV = I->first;
Daniel Dunbar04d35782008-09-17 00:51:38 +00001736
1737 switch (ArgInfo.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001738 case ABIArgInfo::Indirect:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001739 if (RV.isScalar() || RV.isComplex()) {
1740 // Make a temporary alloca to pass the argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001741 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001742 if (RV.isScalar())
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001743 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001744 else
1745 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
1746 } else {
1747 Args.push_back(RV.getAggregateAddr());
1748 }
1749 break;
1750
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001751 case ABIArgInfo::Direct:
Daniel Dunbar04d35782008-09-17 00:51:38 +00001752 if (RV.isScalar()) {
1753 Args.push_back(RV.getScalarVal());
1754 } else if (RV.isComplex()) {
Daniel Dunbarcc811502009-02-05 11:13:54 +00001755 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
1756 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
1757 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
1758 Args.push_back(Tmp);
Daniel Dunbar04d35782008-09-17 00:51:38 +00001759 } else {
Daniel Dunbarcc811502009-02-05 11:13:54 +00001760 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
Daniel Dunbar04d35782008-09-17 00:51:38 +00001761 }
1762 break;
1763
Daniel Dunbar1358b202009-01-26 21:26:08 +00001764 case ABIArgInfo::Ignore:
1765 break;
1766
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001767 case ABIArgInfo::Coerce: {
1768 // FIXME: Avoid the conversion through memory if possible.
1769 llvm::Value *SrcPtr;
1770 if (RV.isScalar()) {
Daniel Dunbar4ce351b2009-02-03 23:04:57 +00001771 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001772 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false);
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001773 } else if (RV.isComplex()) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001774 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001775 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
1776 } else
1777 SrcPtr = RV.getAggregateAddr();
1778 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1779 *this));
1780 break;
1781 }
1782
Daniel Dunbar04d35782008-09-17 00:51:38 +00001783 case ABIArgInfo::Expand:
1784 ExpandTypeToArgs(I->second, RV, Args);
1785 break;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001786 }
1787 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001788
Daniel Dunbar0a067402009-02-23 17:26:39 +00001789 llvm::BasicBlock *InvokeDest = getInvokeDest();
Devang Patela85a9ef2008-09-25 21:02:23 +00001790 CodeGen::AttributeListType AttributeList;
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00001791 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList);
Daniel Dunbar0a067402009-02-23 17:26:39 +00001792 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1793 AttributeList.end());
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00001794
Daniel Dunbar90e43452009-03-02 04:32:35 +00001795 llvm::CallSite CS;
1796 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) {
1797 CS = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Daniel Dunbar0a067402009-02-23 17:26:39 +00001798 } else {
1799 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Daniel Dunbar90e43452009-03-02 04:32:35 +00001800 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
1801 &Args[0], &Args[0]+Args.size());
Daniel Dunbar0a067402009-02-23 17:26:39 +00001802 EmitBlock(Cont);
Daniel Dunbaraf438dc2009-02-20 18:54:31 +00001803 }
1804
Daniel Dunbar90e43452009-03-02 04:32:35 +00001805 CS.setAttributes(Attrs);
1806 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
1807 CS.setCallingConv(F->getCallingConv());
1808
1809 // If the call doesn't return, finish the basic block and clear the
1810 // insertion point; this allows the rest of IRgen to discard
1811 // unreachable code.
1812 if (CS.doesNotReturn()) {
1813 Builder.CreateUnreachable();
1814 Builder.ClearInsertionPoint();
1815
1816 // FIXME: For now, emit a dummy basic block because expr
1817 // emitters in generally are not ready to handle emitting
1818 // expressions at unreachable points.
1819 EnsureInsertPoint();
1820
1821 // Return a reasonable RValue.
1822 return GetUndefRValue(RetTy);
1823 }
1824
1825 llvm::Instruction *CI = CS.getInstruction();
Chris Lattner28466632009-03-22 00:32:22 +00001826 if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy)
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001827 CI->setName("call");
Daniel Dunbare126ab12008-09-10 02:41:04 +00001828
1829 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001830 case ABIArgInfo::Indirect:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001831 if (RetTy->isAnyComplexType())
Daniel Dunbar04d35782008-09-17 00:51:38 +00001832 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner28466632009-03-22 00:32:22 +00001833 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar04d35782008-09-17 00:51:38 +00001834 return RValue::getAggregate(Args[0]);
Chris Lattner28466632009-03-22 00:32:22 +00001835 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001836
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001837 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00001838 if (RetTy->isAnyComplexType()) {
1839 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1840 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1841 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattner28466632009-03-22 00:32:22 +00001842 }
1843 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001844 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
Daniel Dunbarcc811502009-02-05 11:13:54 +00001845 Builder.CreateStore(CI, V);
1846 return RValue::getAggregate(V);
Chris Lattner28466632009-03-22 00:32:22 +00001847 }
1848 return RValue::get(CI);
Daniel Dunbare126ab12008-09-10 02:41:04 +00001849
Daniel Dunbar1358b202009-01-26 21:26:08 +00001850 case ABIArgInfo::Ignore:
Daniel Dunbareec02622009-02-03 06:30:17 +00001851 // If we are ignoring an argument that had a result, make sure to
1852 // construct the appropriate return value for our caller.
Daniel Dunbar900c85a2009-02-05 07:09:07 +00001853 return GetUndefRValue(RetTy);
Daniel Dunbar1358b202009-01-26 21:26:08 +00001854
Daniel Dunbar73d66602008-09-10 07:04:09 +00001855 case ABIArgInfo::Coerce: {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001856 // FIXME: Avoid the conversion through memory if possible.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001857 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
Daniel Dunbar708d8a82009-01-27 01:36:03 +00001858 CreateCoercedStore(CI, V, *this);
Anders Carlssonfccf7472008-11-25 22:21:48 +00001859 if (RetTy->isAnyComplexType())
1860 return RValue::getComplex(LoadComplexFromAddr(V, false));
Chris Lattner28466632009-03-22 00:32:22 +00001861 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssonfccf7472008-11-25 22:21:48 +00001862 return RValue::getAggregate(V);
Chris Lattner28466632009-03-22 00:32:22 +00001863 return RValue::get(EmitLoadOfScalar(V, false, RetTy));
Daniel Dunbar73d66602008-09-10 07:04:09 +00001864 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001865
Daniel Dunbar22e30052008-09-11 01:48:57 +00001866 case ABIArgInfo::Expand:
1867 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001868 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001869
1870 assert(0 && "Unhandled ABIArgInfo::Kind");
1871 return RValue::get(0);
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001872}
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001873
1874/* VarArg handling */
1875
1876llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1877 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1878}