blob: ee0e26e0da4e2f6105e5270be4dd383867e83091 [file] [log] [blame]
Chris Lattnera5f58b02011-07-09 17:41:47 +00001//===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
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"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000017#include "ABIInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
Daniel Dunbard9eff3d2008-10-13 17:02:26 +000020#include "clang/Basic/TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Devang Patel3e1f51b2008-09-24 01:01:36 +000025#include "llvm/Attributes.h"
Daniel Dunbarb960b7b2009-03-02 04:32:35 +000026#include "llvm/Support/CallSite.h"
Daniel Dunbar0f4aa3c2009-01-27 01:36:03 +000027#include "llvm/Target/TargetData.h"
John McCall31168b02011-06-15 23:02:42 +000028#include "llvm/InlineAsm.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000029#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000030using namespace clang;
31using namespace CodeGen;
32
33/***/
34
John McCallab26cfa2010-02-05 21:31:56 +000035static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
36 switch (CC) {
37 default: return llvm::CallingConv::C;
38 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
39 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000040 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000041 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
42 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Dawn Perchik335e16b2010-09-03 01:29:35 +000043 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000044 }
45}
46
John McCall8ee376f2010-02-24 07:14:12 +000047/// Derives the 'this' type for codegen purposes, i.e. ignoring method
48/// qualification.
49/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000050static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
51 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
52 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000053}
54
John McCall8ee376f2010-02-24 07:14:12 +000055/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000056static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
57 return MD->getType()->getCanonicalTypeUnqualified()
58 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000059}
60
61/// Returns the "extra-canonicalized" return type, which discards
62/// qualifiers on the return type. Codegen doesn't care about them,
63/// and it makes ABI code a little easier to be able to assume that
64/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000065static CanQualType GetReturnType(QualType RetTy) {
66 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000067}
68
69const CGFunctionInfo &
Chris Lattnera5f58b02011-07-09 17:41:47 +000070CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP) {
John McCall2da83a32010-02-26 00:48:12 +000071 return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
72 llvm::SmallVector<CanQualType, 16>(),
Chris Lattnera5f58b02011-07-09 17:41:47 +000073 FTNP->getExtInfo());
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
76/// \param Args - contains any initial parameters besides those
77/// in the formal type
78static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
John McCall2da83a32010-02-26 00:48:12 +000079 llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattnera5f58b02011-07-09 17:41:47 +000080 CanQual<FunctionProtoType> FTP) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000081 // FIXME: Kill copy.
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000082 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000083 ArgTys.push_back(FTP->getArgType(i));
John McCall2da83a32010-02-26 00:48:12 +000084 CanQualType ResTy = FTP->getResultType().getUnqualifiedType();
Chris Lattnera5f58b02011-07-09 17:41:47 +000085 return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
John McCall8ee376f2010-02-24 07:14:12 +000086}
87
88const CGFunctionInfo &
Chris Lattnera5f58b02011-07-09 17:41:47 +000089CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP) {
John McCall2da83a32010-02-26 00:48:12 +000090 llvm::SmallVector<CanQualType, 16> ArgTys;
Chris Lattnera5f58b02011-07-09 17:41:47 +000091 return ::getFunctionInfo(*this, ArgTys, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +000092}
93
John McCallab26cfa2010-02-05 21:31:56 +000094static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +000095 // Set the appropriate calling convention for the Function.
96 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +000097 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +000098
99 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000100 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000101
Douglas Gregora941dca2010-05-18 16:57:00 +0000102 if (D->hasAttr<ThisCallAttr>())
103 return CC_X86ThisCall;
104
Dawn Perchik335e16b2010-09-03 01:29:35 +0000105 if (D->hasAttr<PascalAttr>())
106 return CC_X86Pascal;
107
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000108 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
109 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
110
John McCallab26cfa2010-02-05 21:31:56 +0000111 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000112}
113
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000114const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD,
115 const FunctionProtoType *FTP) {
John McCall2da83a32010-02-26 00:48:12 +0000116 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall8ee376f2010-02-24 07:14:12 +0000117
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000118 // Add the 'this' pointer.
John McCall8ee376f2010-02-24 07:14:12 +0000119 ArgTys.push_back(GetThisType(Context, RD));
120
121 return ::getFunctionInfo(*this, ArgTys,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000122 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000123}
124
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000125const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
John McCall2da83a32010-02-26 00:48:12 +0000126 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall8ee376f2010-02-24 07:14:12 +0000127
John McCall0d635f52010-09-03 01:26:39 +0000128 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
129 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
130
Chris Lattnerbea5b622009-05-12 20:27:19 +0000131 // Add the 'this' pointer unless this is a static method.
132 if (MD->isInstance())
John McCall8ee376f2010-02-24 07:14:12 +0000133 ArgTys.push_back(GetThisType(Context, MD->getParent()));
Mike Stump11289f42009-09-09 15:08:12 +0000134
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000135 return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000136}
137
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000138const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D,
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000139 CXXCtorType Type) {
John McCall2da83a32010-02-26 00:48:12 +0000140 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall8ee376f2010-02-24 07:14:12 +0000141 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall5d865c322010-08-31 07:33:07 +0000142 CanQualType ResTy = Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000143
John McCall5d865c322010-08-31 07:33:07 +0000144 TheCXXABI.BuildConstructorSignature(D, Type, ResTy, ArgTys);
John McCall8ee376f2010-02-24 07:14:12 +0000145
John McCall5d865c322010-08-31 07:33:07 +0000146 CanQual<FunctionProtoType> FTP = GetFormalType(D);
147
148 // Add the formal parameters.
149 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
150 ArgTys.push_back(FTP->getArgType(i));
151
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000152 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000153}
154
155const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D,
156 CXXDtorType Type) {
John McCall5d865c322010-08-31 07:33:07 +0000157 llvm::SmallVector<CanQualType, 2> ArgTys;
John McCall2da83a32010-02-26 00:48:12 +0000158 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall5d865c322010-08-31 07:33:07 +0000159 CanQualType ResTy = Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000160
John McCall5d865c322010-08-31 07:33:07 +0000161 TheCXXABI.BuildDestructorSignature(D, Type, ResTy, ArgTys);
162
163 CanQual<FunctionProtoType> FTP = GetFormalType(D);
164 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
165
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000166 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000167}
168
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000169const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000170 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000171 if (MD->isInstance())
172 return getFunctionInfo(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000173
John McCall2da83a32010-02-26 00:48:12 +0000174 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
175 assert(isa<FunctionType>(FTy));
John McCall8ee376f2010-02-24 07:14:12 +0000176 if (isa<FunctionNoProtoType>(FTy))
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000177 return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
John McCall2da83a32010-02-26 00:48:12 +0000178 assert(isa<FunctionProtoType>(FTy));
179 return getFunctionInfo(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000180}
181
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000182const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
John McCall2da83a32010-02-26 00:48:12 +0000183 llvm::SmallVector<CanQualType, 16> ArgTys;
184 ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType()));
185 ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000186 // FIXME: Kill copy?
Chris Lattner90669d02009-02-20 06:23:21 +0000187 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
John McCall8ee376f2010-02-24 07:14:12 +0000188 e = MD->param_end(); i != e; ++i) {
189 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
190 }
John McCall31168b02011-06-15 23:02:42 +0000191
192 FunctionType::ExtInfo einfo;
193 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
194
195 if (getContext().getLangOptions().ObjCAutoRefCount &&
196 MD->hasAttr<NSReturnsRetainedAttr>())
197 einfo = einfo.withProducesResult(true);
198
199 return getFunctionInfo(GetReturnType(MD->getResultType()), ArgTys, einfo);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000200}
201
Anders Carlsson6710c532010-02-06 02:44:09 +0000202const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
203 // FIXME: Do we need to handle ObjCMethodDecl?
204 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000205
Anders Carlsson6710c532010-02-06 02:44:09 +0000206 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
207 return getFunctionInfo(CD, GD.getCtorType());
208
209 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
210 return getFunctionInfo(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000211
Anders Carlsson6710c532010-02-06 02:44:09 +0000212 return getFunctionInfo(FD);
213}
214
Mike Stump11289f42009-09-09 15:08:12 +0000215const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000216 const CallArgList &Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000217 const FunctionType::ExtInfo &Info) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000218 // FIXME: Kill copy.
John McCall2da83a32010-02-26 00:48:12 +0000219 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump11289f42009-09-09 15:08:12 +0000220 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000221 i != e; ++i)
Eli Friedmanf4258eb2011-05-02 18:05:27 +0000222 ArgTys.push_back(Context.getCanonicalParamType(i->Ty));
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000223 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000224}
225
Mike Stump11289f42009-09-09 15:08:12 +0000226const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000227 const FunctionArgList &Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000228 const FunctionType::ExtInfo &Info) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000229 // FIXME: Kill copy.
John McCall2da83a32010-02-26 00:48:12 +0000230 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump11289f42009-09-09 15:08:12 +0000231 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000232 i != e; ++i)
John McCalla738c252011-03-09 04:27:21 +0000233 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000234 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000235}
236
John McCalla738c252011-03-09 04:27:21 +0000237const CGFunctionInfo &CodeGenTypes::getNullaryFunctionInfo() {
238 llvm::SmallVector<CanQualType, 1> args;
239 return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo());
240}
241
John McCall2da83a32010-02-26 00:48:12 +0000242const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
243 const llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattnera5f58b02011-07-09 17:41:47 +0000244 const FunctionType::ExtInfo &Info) {
John McCall2da83a32010-02-26 00:48:12 +0000245#ifndef NDEBUG
246 for (llvm::SmallVectorImpl<CanQualType>::const_iterator
247 I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I)
248 assert(I->isCanonicalAsParam());
249#endif
250
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000251 unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000252
Daniel Dunbare0be8292009-02-03 00:07:12 +0000253 // Lookup or create unique function info.
254 llvm::FoldingSetNodeID ID;
Chris Lattner35bd5be22011-07-10 01:10:18 +0000255 CGFunctionInfo::Profile(ID, Info, ResTy, ArgTys.begin(), ArgTys.end());
Daniel Dunbare0be8292009-02-03 00:07:12 +0000256
257 void *InsertPos = 0;
258 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
259 if (FI)
260 return *FI;
261
Daniel Dunbar313321e2009-02-03 05:31:23 +0000262 // Construct the function info.
John McCall31168b02011-06-15 23:02:42 +0000263 FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult(),
264 Info.getHasRegParm(), Info.getRegParm(), ResTy,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000265 ArgTys.data(), ArgTys.size());
Daniel Dunbarfff09f32009-02-05 00:00:23 +0000266 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000267
268 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000269 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000270
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000271 // Loop over all of the computed argument and return value info. If any of
272 // them are direct or extend without a specified coerce type, specify the
273 // default now.
274 ABIArgInfo &RetInfo = FI->getReturnInfo();
275 if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000276 RetInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000277
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000278 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
279 I != E; ++I)
280 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000281 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000282
Daniel Dunbare0be8292009-02-03 00:07:12 +0000283 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000284}
285
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000286CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
John McCall31168b02011-06-15 23:02:42 +0000287 bool _NoReturn, bool returnsRetained,
288 bool _HasRegParm, unsigned _RegParm,
John McCall2da83a32010-02-26 00:48:12 +0000289 CanQualType ResTy,
Chris Lattner34d62812010-06-29 18:13:52 +0000290 const CanQualType *ArgTys,
291 unsigned NumArgTys)
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000292 : CallingConvention(_CallingConvention),
John McCallab26cfa2010-02-05 21:31:56 +0000293 EffectiveCallingConvention(_CallingConvention),
John McCall31168b02011-06-15 23:02:42 +0000294 NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
295 HasRegParm(_HasRegParm), RegParm(_RegParm)
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000296{
Chris Lattner34d62812010-06-29 18:13:52 +0000297 NumArgs = NumArgTys;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000298
Chris Lattner3dd716c2010-06-28 23:44:11 +0000299 // FIXME: Coallocate with the CGFunctionInfo object.
Chris Lattner34d62812010-06-29 18:13:52 +0000300 Args = new ArgInfo[1 + NumArgTys];
Daniel Dunbar313321e2009-02-03 05:31:23 +0000301 Args[0].type = ResTy;
Chris Lattner34d62812010-06-29 18:13:52 +0000302 for (unsigned i = 0; i != NumArgTys; ++i)
Daniel Dunbar313321e2009-02-03 05:31:23 +0000303 Args[1 + i].type = ArgTys[i];
304}
305
306/***/
307
John McCall85dd2c52011-05-15 02:19:42 +0000308void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattnera5f58b02011-07-09 17:41:47 +0000309 llvm::SmallVectorImpl<llvm::Type*> &expandedTypes) {
John McCall85dd2c52011-05-15 02:19:42 +0000310 const RecordType *RT = type->getAsStructureType();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000311 assert(RT && "Can only expand structure types.");
312 const RecordDecl *RD = RT->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000313 assert(!RD->hasFlexibleArrayMember() &&
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000314 "Cannot expand structure with flexible array.");
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000316 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
317 i != e; ++i) {
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000318 const FieldDecl *FD = *i;
Mike Stump11289f42009-09-09 15:08:12 +0000319 assert(!FD->isBitField() &&
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000320 "Cannot expand structure with bit-field members.");
Mike Stump11289f42009-09-09 15:08:12 +0000321
John McCall85dd2c52011-05-15 02:19:42 +0000322 QualType fieldType = FD->getType();
323 if (fieldType->isRecordType())
Chris Lattnera5f58b02011-07-09 17:41:47 +0000324 GetExpandedTypes(fieldType, expandedTypes);
Chris Lattnerff941a62010-07-28 18:24:28 +0000325 else
Chris Lattnera5f58b02011-07-09 17:41:47 +0000326 expandedTypes.push_back(ConvertType(fieldType));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000327 }
328}
329
Mike Stump11289f42009-09-09 15:08:12 +0000330llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000331CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
332 llvm::Function::arg_iterator AI) {
333 const RecordType *RT = Ty->getAsStructureType();
334 assert(RT && "Can only expand structure types.");
335
336 RecordDecl *RD = RT->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000337 assert(LV.isSimple() &&
338 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000339 llvm::Value *Addr = LV.getAddress();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000340 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
341 i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000342 FieldDecl *FD = *i;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000343 QualType FT = FD->getType();
344
345 // FIXME: What are the right qualifiers here?
Anders Carlsson5d8645b2010-01-29 05:05:36 +0000346 LValue LV = EmitLValueForField(Addr, FD, 0);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000347 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
348 AI = ExpandTypeFromArgs(FT, LV, AI);
349 } else {
John McCall55e1fbc2011-06-25 02:11:03 +0000350 EmitStoreThroughLValue(RValue::get(AI), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000351 ++AI;
352 }
353 }
354
355 return AI;
356}
357
Chris Lattner895c52b2010-06-27 06:04:18 +0000358/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000359/// accessing some number of bytes out of it, try to gep into the struct to get
360/// at its inner goodness. Dive as deep as possible without entering an element
361/// with an in-memory size smaller than DstSize.
362static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000363EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
364 const llvm::StructType *SrcSTy,
365 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000366 // We can't dive into a zero-element struct.
367 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000368
Chris Lattner1cd66982010-06-27 05:56:15 +0000369 const llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000370
Chris Lattner1cd66982010-06-27 05:56:15 +0000371 // If the first elt is at least as large as what we're looking for, or if the
372 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000373 uint64_t FirstEltSize =
Chris Lattner1cd66982010-06-27 05:56:15 +0000374 CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000375 if (FirstEltSize < DstSize &&
Chris Lattner1cd66982010-06-27 05:56:15 +0000376 FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
377 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000378
Chris Lattner1cd66982010-06-27 05:56:15 +0000379 // GEP into the first element.
380 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000381
Chris Lattner1cd66982010-06-27 05:56:15 +0000382 // If the first element is a struct, recurse.
383 const llvm::Type *SrcTy =
384 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
385 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000386 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000387
388 return SrcPtr;
389}
390
Chris Lattner055097f2010-06-27 06:26:04 +0000391/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
392/// are either integers or pointers. This does a truncation of the value if it
393/// is too large or a zero extension if it is too small.
394static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
395 const llvm::Type *Ty,
396 CodeGenFunction &CGF) {
397 if (Val->getType() == Ty)
398 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000399
Chris Lattner055097f2010-06-27 06:26:04 +0000400 if (isa<llvm::PointerType>(Val->getType())) {
401 // If this is Pointer->Pointer avoid conversion to and from int.
402 if (isa<llvm::PointerType>(Ty))
403 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000404
Chris Lattner055097f2010-06-27 06:26:04 +0000405 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000406 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000407 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000408
Chris Lattner055097f2010-06-27 06:26:04 +0000409 const llvm::Type *DestIntTy = Ty;
410 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000411 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000412
Chris Lattner055097f2010-06-27 06:26:04 +0000413 if (Val->getType() != DestIntTy)
414 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000415
Chris Lattner055097f2010-06-27 06:26:04 +0000416 if (isa<llvm::PointerType>(Ty))
417 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
418 return Val;
419}
420
Chris Lattner1cd66982010-06-27 05:56:15 +0000421
422
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000423/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
424/// a pointer to an object of type \arg Ty.
425///
426/// This safely handles the case when the src type is smaller than the
427/// destination type; in this situation the values of bits which not
428/// present in the src are undefined.
429static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
430 const llvm::Type *Ty,
431 CodeGenFunction &CGF) {
Mike Stump11289f42009-09-09 15:08:12 +0000432 const llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000433 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000434
Chris Lattnerd200eda2010-06-28 22:51:39 +0000435 // If SrcTy and Ty are the same, just do a load.
436 if (SrcTy == Ty)
437 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000438
Duncan Sandsc76fe8b2009-05-09 07:08:47 +0000439 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000440
Chris Lattner1cd66982010-06-27 05:56:15 +0000441 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000442 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000443 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
444 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000445
Chris Lattner1cd66982010-06-27 05:56:15 +0000446 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000447
Chris Lattner055097f2010-06-27 06:26:04 +0000448 // If the source and destination are integer or pointer types, just do an
449 // extension or truncation to the desired type.
450 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
451 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
452 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
453 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
454 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000455
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000456 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000457 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000458 // Generally SrcSize is never greater than DstSize, since this means we are
459 // losing bits. However, this can happen in cases where the structure has
460 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000461 //
Mike Stump18bb9282009-05-16 07:57:57 +0000462 // FIXME: Assert that we aren't truncating non-padding bits when have access
463 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000464 llvm::Value *Casted =
465 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000466 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
467 // FIXME: Use better alignment / avoid requiring aligned load.
468 Load->setAlignment(1);
469 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000470 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000471
Chris Lattner3fcc7902010-06-27 01:06:27 +0000472 // Otherwise do coercion through memory. This is stupid, but
473 // simple.
474 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
475 llvm::Value *Casted =
476 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
477 llvm::StoreInst *Store =
478 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
479 // FIXME: Use better alignment / avoid requiring aligned store.
480 Store->setAlignment(1);
481 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000482}
483
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000484// Function to store a first-class aggregate into memory. We prefer to
485// store the elements rather than the aggregate to be more friendly to
486// fast-isel.
487// FIXME: Do we need to recurse here?
488static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
489 llvm::Value *DestPtr, bool DestIsVolatile,
490 bool LowAlignment) {
491 // Prefer scalar stores to first-class aggregate stores.
492 if (const llvm::StructType *STy =
493 dyn_cast<llvm::StructType>(Val->getType())) {
494 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
496 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
497 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
498 DestIsVolatile);
499 if (LowAlignment)
500 SI->setAlignment(1);
501 }
502 } else {
503 CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
504 }
505}
506
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000507/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
508/// where the source and destination may have different types.
509///
510/// This safely handles the case when the src type is larger than the
511/// destination type; the upper bits of the src will be lost.
512static void CreateCoercedStore(llvm::Value *Src,
513 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000514 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000515 CodeGenFunction &CGF) {
516 const llvm::Type *SrcTy = Src->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000517 const llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000518 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000519 if (SrcTy == DstTy) {
520 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
521 return;
522 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000523
Chris Lattnerd200eda2010-06-28 22:51:39 +0000524 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000525
Chris Lattner895c52b2010-06-27 06:04:18 +0000526 if (const llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
527 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
528 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
529 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000530
Chris Lattner055097f2010-06-27 06:26:04 +0000531 // If the source and destination are integer or pointer types, just do an
532 // extension or truncation to the desired type.
533 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
534 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
535 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
536 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
537 return;
538 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000539
Duncan Sandsc76fe8b2009-05-09 07:08:47 +0000540 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000541
Daniel Dunbar313321e2009-02-03 05:31:23 +0000542 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000543 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000544 llvm::Value *Casted =
545 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000546 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000547 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000548 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000549 // Otherwise do coercion through memory. This is stupid, but
550 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000551
552 // Generally SrcSize is never greater than DstSize, since this means we are
553 // losing bits. However, this can happen in cases where the structure has
554 // additional padding, for example due to a user specified alignment.
555 //
556 // FIXME: Assert that we aren't truncating non-padding bits when have access
557 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000558 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
559 CGF.Builder.CreateStore(Src, Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000560 llvm::Value *Casted =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000561 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000562 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
563 // FIXME: Use better alignment / avoid requiring aligned load.
564 Load->setAlignment(1);
Anders Carlsson17490832009-12-24 20:40:36 +0000565 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000566 }
567}
568
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000569/***/
570
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000571bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000572 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000573}
574
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000575bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
576 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
577 switch (BT->getKind()) {
578 default:
579 return false;
580 case BuiltinType::Float:
581 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Float);
582 case BuiltinType::Double:
583 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Double);
584 case BuiltinType::LongDouble:
585 return getContext().Target.useObjCFPRetForRealType(
586 TargetInfo::LongDouble);
587 }
588 }
589
590 return false;
591}
592
Chris Lattnera5f58b02011-07-09 17:41:47 +0000593llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallf8ff7b92010-02-23 00:48:20 +0000594 const CGFunctionInfo &FI = getFunctionInfo(GD);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000595
John McCallf8ff7b92010-02-23 00:48:20 +0000596 // For definition purposes, don't consider a K&R function variadic.
597 bool Variadic = false;
598 if (const FunctionProtoType *FPT =
599 cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
600 Variadic = FPT->isVariadic();
601
Chris Lattnera5f58b02011-07-09 17:41:47 +0000602 return GetFunctionType(FI, Variadic);
John McCallf8ff7b92010-02-23 00:48:20 +0000603}
604
Chris Lattnera5f58b02011-07-09 17:41:47 +0000605llvm::FunctionType *
606CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic) {
607 llvm::SmallVector<llvm::Type*, 8> argTypes;
John McCall85dd2c52011-05-15 02:19:42 +0000608 const llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000609
John McCall85dd2c52011-05-15 02:19:42 +0000610 const ABIArgInfo &retAI = FI.getReturnInfo();
611 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000612 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000613 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000614
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000615 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000616 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000617 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000618 break;
619
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000620 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000621 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
622 resultType = llvm::Type::getVoidTy(getLLVMContext());
623
624 QualType ret = FI.getReturnType();
Chris Lattnera5f58b02011-07-09 17:41:47 +0000625 const llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000626 unsigned addressSpace = Context.getTargetAddressSpace(ret);
627 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000628 break;
629 }
630
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000631 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000632 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000633 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000634 }
Mike Stump11289f42009-09-09 15:08:12 +0000635
636 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +0000637 ie = FI.arg_end(); it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000638 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000639
John McCall85dd2c52011-05-15 02:19:42 +0000640 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000641 case ABIArgInfo::Ignore:
642 break;
643
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000644 case ABIArgInfo::Indirect: {
645 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000646 const llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000647 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000648 break;
649 }
650
651 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000652 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000653 // If the coerce-to type is a first class aggregate, flatten it. Either
654 // way is semantically identical, but fast-isel and the optimizer
655 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000656 llvm::Type *argType = argAI.getCoerceToType();
John McCall85dd2c52011-05-15 02:19:42 +0000657 if (const llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
658 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
659 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000660 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000661 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000662 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000663 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000664 }
Mike Stump11289f42009-09-09 15:08:12 +0000665
Daniel Dunbard3674e62008-09-11 01:48:57 +0000666 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000667 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000668 break;
669 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000670 }
671
John McCall85dd2c52011-05-15 02:19:42 +0000672 return llvm::FunctionType::get(resultType, argTypes, isVariadic);
Daniel Dunbar81cf67f2008-09-09 23:48:28 +0000673}
674
John McCall5d865c322010-08-31 07:33:07 +0000675const llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
676 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +0000677 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000678
Chris Lattner8806e322011-07-10 00:18:59 +0000679 if (!isFuncTypeConvertible(FPT))
680 return llvm::StructType::get(getLLVMContext());
681
682 const CGFunctionInfo *Info;
683 if (isa<CXXDestructorDecl>(MD))
684 Info = &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType());
685 else
686 Info = &getFunctionInfo(MD);
687 return GetFunctionType(*Info, FPT->isVariadic());
Anders Carlsson64457732009-11-24 05:08:52 +0000688}
689
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000690void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +0000691 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000692 AttributeListType &PAL,
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000693 unsigned &CallingConv) {
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000694 unsigned FuncAttrs = 0;
Devang Patel597e7082008-09-26 22:53:57 +0000695 unsigned RetAttrs = 0;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000696
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000697 CallingConv = FI.getEffectiveCallingConvention();
698
John McCallab26cfa2010-02-05 21:31:56 +0000699 if (FI.isNoReturn())
700 FuncAttrs |= llvm::Attribute::NoReturn;
701
Anton Korobeynikovc8478242009-04-04 00:49:24 +0000702 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000703 if (TargetDecl) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000704 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patel322300d2008-09-25 21:02:23 +0000705 FuncAttrs |= llvm::Attribute::NoUnwind;
John McCallbe349de2010-07-08 06:48:12 +0000706 else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
707 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +0000708 if (FPT && FPT->isNothrow(getContext()))
John McCallbe349de2010-07-08 06:48:12 +0000709 FuncAttrs |= llvm::Attribute::NoUnwind;
710 }
711
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000712 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patel322300d2008-09-25 21:02:23 +0000713 FuncAttrs |= llvm::Attribute::NoReturn;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000714 if (TargetDecl->hasAttr<ConstAttr>())
Anders Carlssonb8316282008-10-05 23:32:53 +0000715 FuncAttrs |= llvm::Attribute::ReadNone;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000716 else if (TargetDecl->hasAttr<PureAttr>())
Daniel Dunbar8c920c92009-04-10 22:14:52 +0000717 FuncAttrs |= llvm::Attribute::ReadOnly;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +0000718 if (TargetDecl->hasAttr<MallocAttr>())
719 RetAttrs |= llvm::Attribute::NoAlias;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000720 }
721
Chandler Carruthbc55fe22009-11-12 17:24:48 +0000722 if (CodeGenOpts.OptimizeSize)
Daniel Dunbarc369d732009-10-27 19:48:08 +0000723 FuncAttrs |= llvm::Attribute::OptimizeForSize;
Chandler Carruthbc55fe22009-11-12 17:24:48 +0000724 if (CodeGenOpts.DisableRedZone)
Devang Patel6e467b12009-06-04 23:32:02 +0000725 FuncAttrs |= llvm::Attribute::NoRedZone;
Chandler Carruthbc55fe22009-11-12 17:24:48 +0000726 if (CodeGenOpts.NoImplicitFloat)
Devang Patel9e243862009-06-05 22:05:48 +0000727 FuncAttrs |= llvm::Attribute::NoImplicitFloat;
Devang Patel6e467b12009-06-04 23:32:02 +0000728
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000729 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000730 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000731 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000732 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000733 case ABIArgInfo::Extend:
Chris Lattner4b8585e2010-07-28 23:46:15 +0000734 if (RetTy->hasSignedIntegerRepresentation())
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000735 RetAttrs |= llvm::Attribute::SExt;
Chris Lattner4b8585e2010-07-28 23:46:15 +0000736 else if (RetTy->hasUnsignedIntegerRepresentation())
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000737 RetAttrs |= llvm::Attribute::ZExt;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000738 break;
Daniel Dunbar67dace892009-02-03 06:17:37 +0000739 case ABIArgInfo::Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000740 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +0000741 break;
742
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000743 case ABIArgInfo::Indirect:
Mike Stump11289f42009-09-09 15:08:12 +0000744 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Chris Lattner9cffdf12010-04-20 05:44:43 +0000745 llvm::Attribute::StructRet));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000746 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +0000747 // sret disables readnone and readonly
748 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
749 llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +0000750 break;
751
Daniel Dunbard3674e62008-09-11 01:48:57 +0000752 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +0000753 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000754 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +0000755
Devang Patel597e7082008-09-26 22:53:57 +0000756 if (RetAttrs)
757 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +0000758
Daniel Dunbar0bb03312011-02-09 17:54:19 +0000759 // FIXME: RegParm should be reduced in case of global register variable.
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000760 signed RegParm;
761 if (FI.getHasRegParm())
762 RegParm = FI.getRegParm();
763 else
Daniel Dunbar0bb03312011-02-09 17:54:19 +0000764 RegParm = CodeGenOpts.NumRegisterParameters;
Anton Korobeynikovc8478242009-04-04 00:49:24 +0000765
766 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
Mike Stump11289f42009-09-09 15:08:12 +0000767 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +0000768 ie = FI.arg_end(); it != ie; ++it) {
769 QualType ParamType = it->type;
770 const ABIArgInfo &AI = it->info;
Devang Patel322300d2008-09-25 21:02:23 +0000771 unsigned Attributes = 0;
Anton Korobeynikovc8478242009-04-04 00:49:24 +0000772
John McCall39ec71f2010-03-27 00:47:27 +0000773 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
774 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +0000775 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +0000776 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000777 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000778 if (ParamType->isSignedIntegerOrEnumerationType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000779 Attributes |= llvm::Attribute::SExt;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000780 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000781 Attributes |= llvm::Attribute::ZExt;
782 // FALL THROUGH
783 case ABIArgInfo::Direct:
784 if (RegParm > 0 &&
785 (ParamType->isIntegerType() || ParamType->isPointerType())) {
786 RegParm -=
787 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
788 if (RegParm >= 0)
789 Attributes |= llvm::Attribute::InReg;
790 }
791 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000792
Chris Lattner3dd716c2010-06-28 23:44:11 +0000793 if (const llvm::StructType *STy =
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000794 dyn_cast<llvm::StructType>(AI.getCoerceToType()))
795 Index += STy->getNumElements()-1; // 1 will be added below.
796 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000797
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000798 case ABIArgInfo::Indirect:
Anders Carlsson20759ad2009-09-16 15:53:40 +0000799 if (AI.getIndirectByVal())
800 Attributes |= llvm::Attribute::ByVal;
801
Anton Korobeynikovc8478242009-04-04 00:49:24 +0000802 Attributes |=
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000803 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbarc2304432009-03-18 19:51:01 +0000804 // byval disables readnone and readonly.
805 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
806 llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000807 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000808
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000809 case ABIArgInfo::Ignore:
810 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +0000811 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000812
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000813 case ABIArgInfo::Expand: {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000814 llvm::SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +0000815 // FIXME: This is rather inefficient. Do we ever actually need to do
816 // anything here? The result should be just reconstructed on the other
817 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000818 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +0000819 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000820 continue;
821 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000822 }
Mike Stump11289f42009-09-09 15:08:12 +0000823
Devang Patel322300d2008-09-25 21:02:23 +0000824 if (Attributes)
825 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000826 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000827 }
Devang Patel597e7082008-09-26 22:53:57 +0000828 if (FuncAttrs)
829 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000830}
831
John McCalla738c252011-03-09 04:27:21 +0000832/// An argument came in as a promoted argument; demote it back to its
833/// declared type.
834static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
835 const VarDecl *var,
836 llvm::Value *value) {
837 const llvm::Type *varType = CGF.ConvertType(var->getType());
838
839 // This can happen with promotions that actually don't change the
840 // underlying type, like the enum promotions.
841 if (value->getType() == varType) return value;
842
843 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
844 && "unexpected promotion type");
845
846 if (isa<llvm::IntegerType>(varType))
847 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
848
849 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
850}
851
Daniel Dunbard931a872009-02-02 22:03:45 +0000852void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
853 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +0000854 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +0000855 // If this is an implicit-return-zero function, go ahead and
856 // initialize the return value. TODO: it might be nice to have
857 // a more general mechanism for this that didn't require synthesized
858 // return statements.
Chris Lattnerc401de92010-07-05 20:21:00 +0000859 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
John McCallcaa19452009-07-28 01:00:58 +0000860 if (FD->hasImplicitReturnZero()) {
861 QualType RetTy = FD->getResultType().getUnqualifiedType();
862 const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +0000863 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +0000864 Builder.CreateStore(Zero, ReturnValue);
865 }
866 }
867
Mike Stump18bb9282009-05-16 07:57:57 +0000868 // FIXME: We no longer need the types from FunctionArgList; lift up and
869 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +0000870
Daniel Dunbar613855c2008-09-09 23:27:19 +0000871 // Emit allocs for param decls. Give the LLVM Argument nodes names.
872 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +0000873
Daniel Dunbar613855c2008-09-09 23:27:19 +0000874 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000875 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +0000876 AI->setName("agg.result");
877 ++AI;
878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
Daniel Dunbara45bdbb2009-02-04 21:17:21 +0000880 assert(FI.arg_size() == Args.size() &&
881 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +0000882 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000883 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +0000884 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
885 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +0000886 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000887 QualType Ty = info_it->type;
888 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +0000889
John McCalla738c252011-03-09 04:27:21 +0000890 bool isPromoted =
891 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
892
Daniel Dunbard3674e62008-09-11 01:48:57 +0000893 switch (ArgI.getKind()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +0000894 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000895 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000896
Daniel Dunbar747865a2009-02-05 09:16:39 +0000897 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000898 // Aggregates and complex variables are accessed by reference. All we
899 // need to do is realign the value, if requested
900 if (ArgI.getIndirectRealign()) {
901 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
902
903 // Copy from the incoming argument pointer to the temporary with the
904 // appropriate alignment.
905 //
906 // FIXME: We should have a common utility for generating an aggregate
907 // copy.
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000908 const llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +0000909 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +0000910 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
911 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
912 Builder.CreateMemCpy(Dst,
913 Src,
Ken Dyck705ba072011-01-19 01:58:38 +0000914 llvm::ConstantInt::get(IntPtrTy,
915 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000916 ArgI.getIndirectAlign(),
917 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000918 V = AlignedTemp;
919 }
Daniel Dunbar747865a2009-02-05 09:16:39 +0000920 } else {
921 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +0000922 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
923 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalla738c252011-03-09 04:27:21 +0000924
925 if (isPromoted)
926 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar747865a2009-02-05 09:16:39 +0000927 }
Devang Patel68a15252011-03-03 20:13:15 +0000928 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar747865a2009-02-05 09:16:39 +0000929 break;
930 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000931
932 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000933 case ABIArgInfo::Direct: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000934 // If we have the trivial case, handle it with no muss and fuss.
935 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +0000936 ArgI.getCoerceToType() == ConvertType(Ty) &&
937 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000938 assert(AI != Fn->arg_end() && "Argument mismatch!");
939 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000940
John McCall39ec71f2010-03-27 00:47:27 +0000941 if (Arg->getType().isRestrictQualified())
942 AI->addAttr(llvm::Attribute::NoAlias);
943
John McCalla738c252011-03-09 04:27:21 +0000944 if (isPromoted)
945 V = emitArgumentDemotion(*this, Arg, V);
946
Devang Patel68a15252011-03-03 20:13:15 +0000947 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000948 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +0000949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattnerc401de92010-07-05 20:21:00 +0000951 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000952
Chris Lattnerff941a62010-07-28 18:24:28 +0000953 // The alignment we need to use is the max of the requested alignment for
954 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000955 unsigned AlignmentToUse =
John McCallad7c5c12011-02-08 08:22:06 +0000956 CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +0000957 AlignmentToUse = std::max(AlignmentToUse,
958 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000959
Chris Lattnerff941a62010-07-28 18:24:28 +0000960 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +0000961 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +0000962 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000963
Chris Lattner8a2f3c72010-07-30 04:02:24 +0000964 // If the value is offset in memory, apply the offset now.
965 if (unsigned Offs = ArgI.getDirectOffset()) {
966 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
967 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000968 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +0000969 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
970 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000971
Chris Lattner15ec3612010-06-29 00:06:42 +0000972 // If the coerce-to type is a first class aggregate, we flatten it and
973 // pass the elements. Either way is semantically identical, but fast-isel
974 // and the optimizer generally likes scalar values better than FCAs.
975 if (const llvm::StructType *STy =
976 dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
Chris Lattnerceddafb2010-07-05 20:41:41 +0000977 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000978
Chris Lattnerceddafb2010-07-05 20:41:41 +0000979 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
980 assert(AI != Fn->arg_end() && "Argument mismatch!");
981 AI->setName(Arg->getName() + ".coerce" + llvm::Twine(i));
982 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
983 Builder.CreateStore(AI++, EltPtr);
Chris Lattner15ec3612010-06-29 00:06:42 +0000984 }
985 } else {
986 // Simple case, just do a coerced store of the argument into the alloca.
987 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +0000988 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +0000989 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +0000990 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000991
992
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000993 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +0000994 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000995 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalla738c252011-03-09 04:27:21 +0000996 if (isPromoted)
997 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +0000998 }
Devang Patel68a15252011-03-03 20:13:15 +0000999 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001000 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001001 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001002
1003 case ABIArgInfo::Expand: {
1004 // If this structure was expanded into multiple arguments then
1005 // we need to create a temporary and reconstruct it from the
1006 // arguments.
1007 llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001008 llvm::Function::arg_iterator End =
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001009 ExpandTypeFromArgs(Ty, MakeAddrLValue(Temp, Ty), AI);
Devang Patel68a15252011-03-03 20:13:15 +00001010 EmitParmDecl(*Arg, Temp, ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001011
1012 // Name the arguments used in expansion and increment AI.
1013 unsigned Index = 0;
1014 for (; AI != End; ++AI, ++Index)
1015 AI->setName(Arg->getName() + "." + llvm::Twine(Index));
1016 continue;
1017 }
1018
1019 case ABIArgInfo::Ignore:
1020 // Initialize the local variable appropriately.
1021 if (hasAggregateLLVMType(Ty))
Devang Patel68a15252011-03-03 20:13:15 +00001022 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001023 else
Devang Patel68a15252011-03-03 20:13:15 +00001024 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1025 ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001026
1027 // Skip increment, no matching LLVM parameter.
1028 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001029 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001030
1031 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001032 }
1033 assert(AI == Fn->arg_end() && "Argument mismatch!");
1034}
1035
John McCall31168b02011-06-15 23:02:42 +00001036/// Try to emit a fused autorelease of a return result.
1037static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1038 llvm::Value *result) {
1039 // We must be immediately followed the cast.
1040 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1041 if (BB->empty()) return 0;
1042 if (&BB->back() != result) return 0;
1043
1044 const llvm::Type *resultType = result->getType();
1045
1046 // result is in a BasicBlock and is therefore an Instruction.
1047 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1048
1049 llvm::SmallVector<llvm::Instruction*,4> insnsToKill;
1050
1051 // Look for:
1052 // %generator = bitcast %type1* %generator2 to %type2*
1053 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1054 // We would have emitted this as a constant if the operand weren't
1055 // an Instruction.
1056 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1057
1058 // Require the generator to be immediately followed by the cast.
1059 if (generator->getNextNode() != bitcast)
1060 return 0;
1061
1062 insnsToKill.push_back(bitcast);
1063 }
1064
1065 // Look for:
1066 // %generator = call i8* @objc_retain(i8* %originalResult)
1067 // or
1068 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1069 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1070 if (!call) return 0;
1071
1072 bool doRetainAutorelease;
1073
1074 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1075 doRetainAutorelease = true;
1076 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1077 .objc_retainAutoreleasedReturnValue) {
1078 doRetainAutorelease = false;
1079
1080 // Look for an inline asm immediately preceding the call and kill it, too.
1081 llvm::Instruction *prev = call->getPrevNode();
1082 if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev))
1083 if (asmCall->getCalledValue()
1084 == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker)
1085 insnsToKill.push_back(prev);
1086 } else {
1087 return 0;
1088 }
1089
1090 result = call->getArgOperand(0);
1091 insnsToKill.push_back(call);
1092
1093 // Keep killing bitcasts, for sanity. Note that we no longer care
1094 // about precise ordering as long as there's exactly one use.
1095 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1096 if (!bitcast->hasOneUse()) break;
1097 insnsToKill.push_back(bitcast);
1098 result = bitcast->getOperand(0);
1099 }
1100
1101 // Delete all the unnecessary instructions, from latest to earliest.
1102 for (llvm::SmallVectorImpl<llvm::Instruction*>::iterator
1103 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1104 (*i)->eraseFromParent();
1105
1106 // Do the fused retain/autorelease if we were asked to.
1107 if (doRetainAutorelease)
1108 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1109
1110 // Cast back to the result type.
1111 return CGF.Builder.CreateBitCast(result, resultType);
1112}
1113
1114/// Emit an ARC autorelease of the result of a function.
1115static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1116 llvm::Value *result) {
1117 // At -O0, try to emit a fused retain/autorelease.
1118 if (CGF.shouldUseFusedARCCalls())
1119 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1120 return fused;
1121
1122 return CGF.EmitARCAutoreleaseReturnValue(result);
1123}
1124
Chris Lattner3fcc7902010-06-27 01:06:27 +00001125void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001126 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001127 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001128 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001129 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001130 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001131
Dan Gohman481e40c2010-07-20 20:13:52 +00001132 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001133 llvm::Value *RV = 0;
1134 QualType RetTy = FI.getReturnType();
1135 const ABIArgInfo &RetAI = FI.getReturnInfo();
1136
1137 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001138 case ABIArgInfo::Indirect: {
1139 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Chris Lattner726b3d02010-06-26 23:13:19 +00001140 if (RetTy->isAnyComplexType()) {
1141 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1142 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1143 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1144 // Do nothing; aggregrates get evaluated directly into the destination.
1145 } else {
1146 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Daniel Dunbar03816342010-08-21 02:24:36 +00001147 false, Alignment, RetTy);
Chris Lattner726b3d02010-06-26 23:13:19 +00001148 }
1149 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001150 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001151
1152 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001153 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001154 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1155 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001156 // The internal return value temp always will have pointer-to-return-type
1157 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001158
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001159 // If the instruction right before the insertion point is a store to the
1160 // return value, we can elide the load, zap the store, and usually zap the
1161 // alloca.
1162 llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1163 llvm::StoreInst *SI = 0;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001164 if (InsertBB->empty() ||
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001165 !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1166 SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1167 RV = Builder.CreateLoad(ReturnValue);
1168 } else {
1169 // Get the stored value and nuke the now-dead store.
1170 RetDbgLoc = SI->getDebugLoc();
1171 RV = SI->getValueOperand();
1172 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001173
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001174 // If that was the only use of the return value, nuke it as well now.
1175 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1176 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1177 ReturnValue = 0;
1178 }
Chris Lattner3fcc7902010-06-27 01:06:27 +00001179 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001180 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001181 llvm::Value *V = ReturnValue;
1182 // If the value is offset in memory, apply the offset now.
1183 if (unsigned Offs = RetAI.getDirectOffset()) {
1184 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1185 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001186 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001187 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1188 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001189
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001190 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001191 }
John McCall31168b02011-06-15 23:02:42 +00001192
1193 // In ARC, end functions that return a retainable type with a call
1194 // to objc_autoreleaseReturnValue.
1195 if (AutoreleaseResult) {
1196 assert(getLangOptions().ObjCAutoRefCount &&
1197 !FI.isReturnsRetained() &&
1198 RetTy->isObjCRetainableType());
1199 RV = emitAutoreleaseOfResult(*this, RV);
1200 }
1201
Chris Lattner726b3d02010-06-26 23:13:19 +00001202 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001203
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001204 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001205 break;
1206
1207 case ABIArgInfo::Expand:
1208 assert(0 && "Invalid ABI kind for return argument");
1209 }
1210
Daniel Dunbar6696e222010-06-30 21:27:58 +00001211 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001212 if (!RetDbgLoc.isUnknown())
1213 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001214}
1215
John McCall32ea9692011-03-11 20:59:21 +00001216void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1217 const VarDecl *param) {
John McCall23f66262010-05-26 22:34:26 +00001218 // StartFunction converted the ABI-lowered parameter(s) into a
1219 // local alloca. We need to turn that into an r-value suitable
1220 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001221 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001222
John McCall32ea9692011-03-11 20:59:21 +00001223 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001224
John McCall23f66262010-05-26 22:34:26 +00001225 // For the most part, we just need to load the alloca, except:
1226 // 1) aggregate r-values are actually pointers to temporaries, and
1227 // 2) references to aggregates are pointers directly to the aggregate.
1228 // I don't know why references to non-aggregates are different here.
John McCall32ea9692011-03-11 20:59:21 +00001229 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1230 if (hasAggregateLLVMType(ref->getPointeeType()))
1231 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001232
1233 // Locals which are references to scalars are represented
1234 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001235 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001236 }
1237
John McCall32ea9692011-03-11 20:59:21 +00001238 if (type->isAnyComplexType()) {
1239 ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false);
1240 return args.add(RValue::getComplex(complex), type);
1241 }
John McCall23f66262010-05-26 22:34:26 +00001242
John McCall32ea9692011-03-11 20:59:21 +00001243 if (hasAggregateLLVMType(type))
1244 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001245
John McCall32ea9692011-03-11 20:59:21 +00001246 unsigned alignment = getContext().getDeclAlign(param).getQuantity();
1247 llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type);
1248 return args.add(RValue::get(value), type);
John McCall23f66262010-05-26 22:34:26 +00001249}
1250
John McCall31168b02011-06-15 23:02:42 +00001251static bool isProvablyNull(llvm::Value *addr) {
1252 return isa<llvm::ConstantPointerNull>(addr);
1253}
1254
1255static bool isProvablyNonNull(llvm::Value *addr) {
1256 return isa<llvm::AllocaInst>(addr);
1257}
1258
1259/// Emit the actual writing-back of a writeback.
1260static void emitWriteback(CodeGenFunction &CGF,
1261 const CallArgList::Writeback &writeback) {
1262 llvm::Value *srcAddr = writeback.Address;
1263 assert(!isProvablyNull(srcAddr) &&
1264 "shouldn't have writeback for provably null argument");
1265
1266 llvm::BasicBlock *contBB = 0;
1267
1268 // If the argument wasn't provably non-null, we need to null check
1269 // before doing the store.
1270 bool provablyNonNull = isProvablyNonNull(srcAddr);
1271 if (!provablyNonNull) {
1272 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1273 contBB = CGF.createBasicBlock("icr.done");
1274
1275 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1276 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1277 CGF.EmitBlock(writebackBB);
1278 }
1279
1280 // Load the value to writeback.
1281 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1282
1283 // Cast it back, in case we're writing an id to a Foo* or something.
1284 value = CGF.Builder.CreateBitCast(value,
1285 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1286 "icr.writeback-cast");
1287
1288 // Perform the writeback.
1289 QualType srcAddrType = writeback.AddressType;
1290 CGF.EmitStoreThroughLValue(RValue::get(value),
John McCall55e1fbc2011-06-25 02:11:03 +00001291 CGF.MakeAddrLValue(srcAddr, srcAddrType));
John McCall31168b02011-06-15 23:02:42 +00001292
1293 // Jump to the continuation block.
1294 if (!provablyNonNull)
1295 CGF.EmitBlock(contBB);
1296}
1297
1298static void emitWritebacks(CodeGenFunction &CGF,
1299 const CallArgList &args) {
1300 for (CallArgList::writeback_iterator
1301 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1302 emitWriteback(CGF, *i);
1303}
1304
1305/// Emit an argument that's being passed call-by-writeback. That is,
1306/// we are passing the address of
1307static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1308 const ObjCIndirectCopyRestoreExpr *CRE) {
1309 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1310
1311 // The dest and src types don't necessarily match in LLVM terms
1312 // because of the crazy ObjC compatibility rules.
1313
1314 const llvm::PointerType *destType =
1315 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1316
1317 // If the address is a constant null, just pass the appropriate null.
1318 if (isProvablyNull(srcAddr)) {
1319 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1320 CRE->getType());
1321 return;
1322 }
1323
1324 QualType srcAddrType =
1325 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1326
1327 // Create the temporary.
1328 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1329 "icr.temp");
1330
1331 // Zero-initialize it if we're not doing a copy-initialization.
1332 bool shouldCopy = CRE->shouldCopy();
1333 if (!shouldCopy) {
1334 llvm::Value *null =
1335 llvm::ConstantPointerNull::get(
1336 cast<llvm::PointerType>(destType->getElementType()));
1337 CGF.Builder.CreateStore(null, temp);
1338 }
1339
1340 llvm::BasicBlock *contBB = 0;
1341
1342 // If the address is *not* known to be non-null, we need to switch.
1343 llvm::Value *finalArgument;
1344
1345 bool provablyNonNull = isProvablyNonNull(srcAddr);
1346 if (provablyNonNull) {
1347 finalArgument = temp;
1348 } else {
1349 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1350
1351 finalArgument = CGF.Builder.CreateSelect(isNull,
1352 llvm::ConstantPointerNull::get(destType),
1353 temp, "icr.argument");
1354
1355 // If we need to copy, then the load has to be conditional, which
1356 // means we need control flow.
1357 if (shouldCopy) {
1358 contBB = CGF.createBasicBlock("icr.cont");
1359 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1360 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1361 CGF.EmitBlock(copyBB);
1362 }
1363 }
1364
1365 // Perform a copy if necessary.
1366 if (shouldCopy) {
1367 LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCall55e1fbc2011-06-25 02:11:03 +00001368 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCall31168b02011-06-15 23:02:42 +00001369 assert(srcRV.isScalar());
1370
1371 llvm::Value *src = srcRV.getScalarVal();
1372 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1373 "icr.cast");
1374
1375 // Use an ordinary store, not a store-to-lvalue.
1376 CGF.Builder.CreateStore(src, temp);
1377 }
1378
1379 // Finish the control flow if we needed it.
1380 if (shouldCopy && !provablyNonNull)
1381 CGF.EmitBlock(contBB);
1382
1383 args.addWriteback(srcAddr, srcAddrType, temp);
1384 args.add(RValue::get(finalArgument), CRE->getType());
1385}
1386
John McCall32ea9692011-03-11 20:59:21 +00001387void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1388 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00001389 if (const ObjCIndirectCopyRestoreExpr *CRE
1390 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
1391 assert(getContext().getLangOptions().ObjCAutoRefCount);
1392 assert(getContext().hasSameType(E->getType(), type));
1393 return emitWritebackArg(*this, args, CRE);
1394 }
1395
John McCall32ea9692011-03-11 20:59:21 +00001396 if (type->isReferenceType())
1397 return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0),
1398 type);
Mike Stump11289f42009-09-09 15:08:12 +00001399
Eli Friedman7e68c882011-06-15 18:26:32 +00001400 if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() &&
1401 isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00001402 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
1403 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
1404 assert(L.isSimple());
1405 args.add(RValue::getAggregate(L.getAddress(), L.isVolatileQualified()),
1406 type, /*NeedsCopy*/true);
1407 return;
1408 }
1409
John McCall32ea9692011-03-11 20:59:21 +00001410 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00001411}
1412
John McCallbd309292010-07-06 01:34:17 +00001413/// Emits a call or invoke instruction to the given function, depending
1414/// on the current state of the EH stack.
1415llvm::CallSite
1416CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1417 llvm::Value * const *ArgBegin,
1418 llvm::Value * const *ArgEnd,
1419 const llvm::Twine &Name) {
1420 llvm::BasicBlock *InvokeDest = getInvokeDest();
1421 if (!InvokeDest)
1422 return Builder.CreateCall(Callee, ArgBegin, ArgEnd, Name);
1423
1424 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1425 llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
1426 ArgBegin, ArgEnd, Name);
1427 EmitBlock(ContBB);
1428 return Invoke;
1429}
1430
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001431static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
1432 llvm::FunctionType *FTy) {
1433 if (ArgNo < FTy->getNumParams())
1434 assert(Elt->getType() == FTy->getParamType(ArgNo));
1435 else
1436 assert(FTy->isVarArg());
1437 ++ArgNo;
1438}
1439
Chris Lattnerd59d8672011-07-12 06:29:11 +00001440void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1441 llvm::SmallVector<llvm::Value*,16> &Args,
1442 llvm::FunctionType *IRFuncTy) {
1443 const RecordType *RT = Ty->getAsStructureType();
1444 assert(RT && "Can only expand structure types.");
1445
1446 RecordDecl *RD = RT->getDecl();
1447 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1448 llvm::Value *Addr = RV.getAggregateAddr();
1449 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1450 i != e; ++i) {
1451 FieldDecl *FD = *i;
1452 QualType FT = FD->getType();
1453
1454 // FIXME: What are the right qualifiers here?
1455 LValue LV = EmitLValueForField(Addr, FD, 0);
1456 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1457 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()),
1458 Args, IRFuncTy);
1459 continue;
1460 }
1461
1462 RValue RV = EmitLoadOfLValue(LV);
1463 assert(RV.isScalar() &&
1464 "Unexpected non-scalar rvalue during struct expansion.");
1465
1466 // Insert a bitcast as needed.
1467 llvm::Value *V = RV.getScalarVal();
1468 if (Args.size() < IRFuncTy->getNumParams() &&
1469 V->getType() != IRFuncTy->getParamType(Args.size()))
1470 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
1471
1472 Args.push_back(V);
1473 }
1474}
1475
1476
Daniel Dunbard931a872009-02-02 22:03:45 +00001477RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001478 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00001479 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00001480 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00001481 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00001482 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00001483 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00001484 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001485
1486 // Handle struct-return functions by passing a pointer to the
1487 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001488 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001489 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001490
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001491 // IRArgNo - Keep track of the argument number in the callee we're looking at.
1492 unsigned IRArgNo = 0;
1493 llvm::FunctionType *IRFuncTy =
1494 cast<llvm::FunctionType>(
1495 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattner4ca97c32009-06-13 00:26:38 +00001497 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00001498 // alloca to hold the result, unless one is given to us.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001499 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlsson17490832009-12-24 20:40:36 +00001500 llvm::Value *Value = ReturnValue.getValue();
1501 if (!Value)
Daniel Dunbara7566f12010-02-09 02:48:28 +00001502 Value = CreateMemTemp(RetTy);
Anders Carlsson17490832009-12-24 20:40:36 +00001503 Args.push_back(Value);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001504 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlsson17490832009-12-24 20:40:36 +00001505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001507 assert(CallInfo.arg_size() == CallArgs.size() &&
1508 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001509 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001510 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001511 I != E; ++I, ++info_it) {
1512 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001513 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001514
Eli Friedmanf7456192011-06-15 22:09:18 +00001515 unsigned TypeAlign =
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001516 getContext().getTypeAlignInChars(I->Ty).getQuantity();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001517 switch (ArgInfo.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001518 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00001519 if (RV.isScalar() || RV.isComplex()) {
1520 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00001521 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1522 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
1523 AI->setAlignment(ArgInfo.getIndirectAlign());
1524 Args.push_back(AI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001525
Daniel Dunbar747865a2009-02-05 09:16:39 +00001526 if (RV.isScalar())
Daniel Dunbar03816342010-08-21 02:24:36 +00001527 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false,
Eli Friedmanf7456192011-06-15 22:09:18 +00001528 TypeAlign, I->Ty);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001529 else
Mike Stump11289f42009-09-09 15:08:12 +00001530 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001531
1532 // Validate argument match.
1533 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001534 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00001535 // We want to avoid creating an unnecessary temporary+copy here;
1536 // however, we need one in two cases:
1537 // 1. If the argument is not byval, and we are required to copy the
1538 // source. (This case doesn't occur on any common architecture.)
1539 // 2. If the argument is byval, RV is not sufficiently aligned, and
1540 // we cannot force it to be sufficiently aligned.
Eli Friedmanf7456192011-06-15 22:09:18 +00001541 llvm::Value *Addr = RV.getAggregateAddr();
1542 unsigned Align = ArgInfo.getIndirectAlign();
1543 const llvm::TargetData *TD = &CGM.getTargetData();
1544 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
1545 (ArgInfo.getIndirectByVal() && TypeAlign < Align &&
1546 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00001547 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00001548 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1549 if (Align > AI->getAlignment())
1550 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00001551 Args.push_back(AI);
Eli Friedmanf7456192011-06-15 22:09:18 +00001552 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001553
1554 // Validate argument match.
1555 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00001556 } else {
1557 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00001558 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001559
1560 // Validate argument match.
1561 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00001562 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001563 }
1564 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001565 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001566
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001567 case ABIArgInfo::Ignore:
1568 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001569
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001570 case ABIArgInfo::Extend:
1571 case ABIArgInfo::Direct: {
1572 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001573 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
1574 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001575 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001576 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001577 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001578 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001579 V = Builder.CreateLoad(RV.getAggregateAddr());
1580
Chris Lattner3ce86682011-07-12 04:53:39 +00001581 // If the argument doesn't match, perform a bitcast to coerce it. This
1582 // can happen due to trivial type mismatches.
1583 if (IRArgNo < IRFuncTy->getNumParams() &&
1584 V->getType() != IRFuncTy->getParamType(IRArgNo))
1585 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001586 Args.push_back(V);
1587
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001588 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001589 break;
1590 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001591
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001592 // FIXME: Avoid the conversion through memory if possible.
1593 llvm::Value *SrcPtr;
1594 if (RV.isScalar()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001595 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Eli Friedmanf7456192011-06-15 22:09:18 +00001596 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty);
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001597 } else if (RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001598 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001599 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
Mike Stump11289f42009-09-09 15:08:12 +00001600 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001601 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001602
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001603 // If the value is offset in memory, apply the offset now.
1604 if (unsigned Offs = ArgInfo.getDirectOffset()) {
1605 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
1606 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001607 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001608 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
1609
1610 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001611
Chris Lattner3dd716c2010-06-28 23:44:11 +00001612 // If the coerce-to type is a first class aggregate, we flatten it and
1613 // pass the elements. Either way is semantically identical, but fast-isel
1614 // and the optimizer generally likes scalar values better than FCAs.
1615 if (const llvm::StructType *STy =
Chris Lattner15ec3612010-06-29 00:06:42 +00001616 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chris Lattnerceddafb2010-07-05 20:41:41 +00001617 SrcPtr = Builder.CreateBitCast(SrcPtr,
1618 llvm::PointerType::getUnqual(STy));
1619 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1620 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00001621 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
1622 // We don't know what we're loading from.
1623 LI->setAlignment(1);
1624 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001625
1626 // Validate argument match.
1627 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00001628 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00001629 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00001630 // In the simple case, just pass the coerced loaded value.
1631 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1632 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001633
1634 // Validate argument match.
1635 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001636 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001637
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001638 break;
1639 }
1640
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001641 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00001642 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00001643 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001644 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001645 }
1646 }
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattner4ca97c32009-06-13 00:26:38 +00001648 // If the callee is a bitcast of a function to a varargs pointer to function
1649 // type, check to see if we can remove the bitcast. This handles some cases
1650 // with unprototyped functions.
1651 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1652 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
1653 const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1654 const llvm::FunctionType *CurFT =
1655 cast<llvm::FunctionType>(CurPT->getElementType());
1656 const llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00001657
Chris Lattner4ca97c32009-06-13 00:26:38 +00001658 if (CE->getOpcode() == llvm::Instruction::BitCast &&
1659 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00001660 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00001661 ActualFT->getNumParams() == Args.size() &&
1662 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00001663 bool ArgsMatch = true;
1664 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1665 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1666 ArgsMatch = false;
1667 break;
1668 }
Mike Stump11289f42009-09-09 15:08:12 +00001669
Chris Lattner4ca97c32009-06-13 00:26:38 +00001670 // Strip the cast if we can get away with it. This is a nice cleanup,
1671 // but also allows us to inline the function at -O0 if it is marked
1672 // always_inline.
1673 if (ArgsMatch)
1674 Callee = CalleeF;
1675 }
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001678 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00001679 CodeGen::AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001680 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
Daniel Dunbar12347492009-02-23 17:26:39 +00001681 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1682 AttributeList.end());
Mike Stump11289f42009-09-09 15:08:12 +00001683
John McCallbd309292010-07-06 01:34:17 +00001684 llvm::BasicBlock *InvokeDest = 0;
1685 if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1686 InvokeDest = getInvokeDest();
1687
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001688 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00001689 if (!InvokeDest) {
Jay Foad7d0479f2009-05-21 09:52:38 +00001690 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
Daniel Dunbar12347492009-02-23 17:26:39 +00001691 } else {
1692 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Mike Stump11289f42009-09-09 15:08:12 +00001693 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
Jay Foad7d0479f2009-05-21 09:52:38 +00001694 Args.data(), Args.data()+Args.size());
Daniel Dunbar12347492009-02-23 17:26:39 +00001695 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00001696 }
Chris Lattnere70a0072010-06-29 16:40:28 +00001697 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00001698 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00001699
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001700 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001701 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001702
1703 // If the call doesn't return, finish the basic block and clear the
1704 // insertion point; this allows the rest of IRgen to discard
1705 // unreachable code.
1706 if (CS.doesNotReturn()) {
1707 Builder.CreateUnreachable();
1708 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00001709
Mike Stump18bb9282009-05-16 07:57:57 +00001710 // FIXME: For now, emit a dummy basic block because expr emitters in
1711 // generally are not ready to handle emitting expressions at unreachable
1712 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001713 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00001714
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001715 // Return a reasonable RValue.
1716 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001717 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00001718
1719 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001720 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00001721 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001722
John McCall31168b02011-06-15 23:02:42 +00001723 // Emit any writebacks immediately. Arguably this should happen
1724 // after any return-value munging.
1725 if (CallArgs.hasWritebacks())
1726 emitWritebacks(*this, CallArgs);
1727
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001728 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001729 case ABIArgInfo::Indirect: {
1730 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001731 if (RetTy->isAnyComplexType())
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001732 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattnere09ad902009-03-22 00:32:22 +00001733 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001734 return RValue::getAggregate(Args[0]);
Daniel Dunbar03816342010-08-21 02:24:36 +00001735 return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy));
1736 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00001737
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001738 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00001739 // If we are ignoring an argument that had a result, make sure to
1740 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001741 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001742
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001743 case ABIArgInfo::Extend:
1744 case ABIArgInfo::Direct: {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001745 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1746 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001747 if (RetTy->isAnyComplexType()) {
1748 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1749 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1750 return RValue::getComplex(std::make_pair(Real, Imag));
1751 }
1752 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1753 llvm::Value *DestPtr = ReturnValue.getValue();
1754 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001755
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001756 if (!DestPtr) {
1757 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1758 DestIsVolatile = false;
1759 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001760 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001761 return RValue::getAggregate(DestPtr);
1762 }
1763 return RValue::get(CI);
1764 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001765
Anders Carlsson17490832009-12-24 20:40:36 +00001766 llvm::Value *DestPtr = ReturnValue.getValue();
1767 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001768
Anders Carlsson17490832009-12-24 20:40:36 +00001769 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00001770 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00001771 DestIsVolatile = false;
1772 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001773
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001774 // If the value is offset in memory, apply the offset now.
1775 llvm::Value *StorePtr = DestPtr;
1776 if (unsigned Offs = RetAI.getDirectOffset()) {
1777 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
1778 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001779 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001780 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1781 }
1782 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001783
Daniel Dunbar03816342010-08-21 02:24:36 +00001784 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Anders Carlsson32ef8ce2008-11-25 22:21:48 +00001785 if (RetTy->isAnyComplexType())
Anders Carlsson17490832009-12-24 20:40:36 +00001786 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
Chris Lattnere09ad902009-03-22 00:32:22 +00001787 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlsson17490832009-12-24 20:40:36 +00001788 return RValue::getAggregate(DestPtr);
Daniel Dunbar03816342010-08-21 02:24:36 +00001789 return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy));
Daniel Dunbar573884e2008-09-10 07:04:09 +00001790 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00001791
Daniel Dunbard3674e62008-09-11 01:48:57 +00001792 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001793 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00001794 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001795
1796 assert(0 && "Unhandled ABIArgInfo::Kind");
1797 return RValue::get(0);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001798}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00001799
1800/* VarArg handling */
1801
1802llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1803 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1804}