blob: 712ec62bd4032ea9d90bc644a1fc326c22b4e25c [file] [log] [blame]
Daniel Dunbar0dbe2272008-09-08 21:33:45 +00001//===----- CGCall.h - Encapsulate calling convention details ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chris Lattnerce933992010-06-29 16:40:28 +000017#include "ABIInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +000020#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Devang Pateld0646bd2008-09-24 01:01:36 +000025#include "llvm/Attributes.h"
Daniel Dunbard14151d2009-03-02 04:32:35 +000026#include "llvm/Support/CallSite.h"
Daniel Dunbar54d1ccb2009-01-27 01:36:03 +000027#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000028#include "llvm/InlineAsm.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000029#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000030using namespace clang;
31using namespace CodeGen;
32
33/***/
34
John McCall04a67a62010-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 Gregorf813a2c2010-05-18 16:57:00 +000040 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov414d8962011-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 Perchik52fc3142010-09-03 01:29:35 +000043 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000044 }
45}
46
John McCall0b0ef0a2010-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 McCallead608a2010-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 Dunbar45c25ba2008-09-10 04:01:49 +000053}
54
John McCall0b0ef0a2010-02-24 07:14:12 +000055/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000056static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
57 return MD->getType()->getCanonicalTypeUnqualified()
58 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-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 McCallead608a2010-02-26 00:48:12 +000065static CanQualType GetReturnType(QualType RetTy) {
66 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000067}
68
69const CGFunctionInfo &
Chris Lattnerbcaedae2010-06-30 19:14:05 +000070CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP,
71 bool IsRecursive) {
John McCallead608a2010-02-26 00:48:12 +000072 return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
73 llvm::SmallVector<CanQualType, 16>(),
Chris Lattnerbcaedae2010-06-30 19:14:05 +000074 FTNP->getExtInfo(), IsRecursive);
John McCall0b0ef0a2010-02-24 07:14:12 +000075}
76
77/// \param Args - contains any initial parameters besides those
78/// in the formal type
79static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
John McCallead608a2010-02-26 00:48:12 +000080 llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattnerbcaedae2010-06-30 19:14:05 +000081 CanQual<FunctionProtoType> FTP,
82 bool IsRecursive = false) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +000083 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000084 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +000085 ArgTys.push_back(FTP->getArgType(i));
John McCallead608a2010-02-26 00:48:12 +000086 CanQualType ResTy = FTP->getResultType().getUnqualifiedType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000087 return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo(), IsRecursive);
John McCall0b0ef0a2010-02-24 07:14:12 +000088}
89
90const CGFunctionInfo &
Chris Lattnerbcaedae2010-06-30 19:14:05 +000091CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP,
92 bool IsRecursive) {
John McCallead608a2010-02-26 00:48:12 +000093 llvm::SmallVector<CanQualType, 16> ArgTys;
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000094 return ::getFunctionInfo(*this, ArgTys, FTP, IsRecursive);
Daniel Dunbarbac7c252009-09-11 22:24:53 +000095}
96
John McCall04a67a62010-02-05 21:31:56 +000097static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +000098 // Set the appropriate calling convention for the Function.
99 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000100 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000101
102 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000103 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000104
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000105 if (D->hasAttr<ThisCallAttr>())
106 return CC_X86ThisCall;
107
Dawn Perchik52fc3142010-09-03 01:29:35 +0000108 if (D->hasAttr<PascalAttr>())
109 return CC_X86Pascal;
110
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000111 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
112 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
113
John McCall04a67a62010-02-05 21:31:56 +0000114 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000115}
116
Anders Carlsson375c31c2009-10-03 19:43:08 +0000117const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD,
118 const FunctionProtoType *FTP) {
John McCallead608a2010-02-26 00:48:12 +0000119 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000120
Anders Carlsson375c31c2009-10-03 19:43:08 +0000121 // Add the 'this' pointer.
John McCall0b0ef0a2010-02-24 07:14:12 +0000122 ArgTys.push_back(GetThisType(Context, RD));
123
124 return ::getFunctionInfo(*this, ArgTys,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000125 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000126}
127
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000128const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
John McCallead608a2010-02-26 00:48:12 +0000129 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000130
John McCallfc400282010-09-03 01:26:39 +0000131 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
132 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
133
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000134 // Add the 'this' pointer unless this is a static method.
135 if (MD->isInstance())
John McCall0b0ef0a2010-02-24 07:14:12 +0000136 ArgTys.push_back(GetThisType(Context, MD->getParent()));
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000138 return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000139}
140
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000141const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D,
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000142 CXXCtorType Type) {
John McCallead608a2010-02-26 00:48:12 +0000143 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000144 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall4c40d982010-08-31 07:33:07 +0000145 CanQualType ResTy = Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000146
John McCall4c40d982010-08-31 07:33:07 +0000147 TheCXXABI.BuildConstructorSignature(D, Type, ResTy, ArgTys);
John McCall0b0ef0a2010-02-24 07:14:12 +0000148
John McCall4c40d982010-08-31 07:33:07 +0000149 CanQual<FunctionProtoType> FTP = GetFormalType(D);
150
151 // Add the formal parameters.
152 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
153 ArgTys.push_back(FTP->getArgType(i));
154
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000155 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000156}
157
158const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D,
159 CXXDtorType Type) {
John McCall4c40d982010-08-31 07:33:07 +0000160 llvm::SmallVector<CanQualType, 2> ArgTys;
John McCallead608a2010-02-26 00:48:12 +0000161 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall4c40d982010-08-31 07:33:07 +0000162 CanQualType ResTy = Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000163
John McCall4c40d982010-08-31 07:33:07 +0000164 TheCXXABI.BuildDestructorSignature(D, Type, ResTy, ArgTys);
165
166 CanQual<FunctionProtoType> FTP = GetFormalType(D);
167 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
168
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000169 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000170}
171
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000172const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000173 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000174 if (MD->isInstance())
175 return getFunctionInfo(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
John McCallead608a2010-02-26 00:48:12 +0000177 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
178 assert(isa<FunctionType>(FTy));
John McCall0b0ef0a2010-02-24 07:14:12 +0000179 if (isa<FunctionNoProtoType>(FTy))
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000180 return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
John McCallead608a2010-02-26 00:48:12 +0000181 assert(isa<FunctionProtoType>(FTy));
182 return getFunctionInfo(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000183}
184
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000185const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
John McCallead608a2010-02-26 00:48:12 +0000186 llvm::SmallVector<CanQualType, 16> ArgTys;
187 ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType()));
188 ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000189 // FIXME: Kill copy?
Chris Lattner20732162009-02-20 06:23:21 +0000190 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
John McCall0b0ef0a2010-02-24 07:14:12 +0000191 e = MD->param_end(); i != e; ++i) {
192 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
193 }
John McCallf85e1932011-06-15 23:02:42 +0000194
195 FunctionType::ExtInfo einfo;
196 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
197
198 if (getContext().getLangOptions().ObjCAutoRefCount &&
199 MD->hasAttr<NSReturnsRetainedAttr>())
200 einfo = einfo.withProducesResult(true);
201
202 return getFunctionInfo(GetReturnType(MD->getResultType()), ArgTys, einfo);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000203}
204
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000205const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
206 // FIXME: Do we need to handle ObjCMethodDecl?
207 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000208
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000209 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
210 return getFunctionInfo(CD, GD.getCtorType());
211
212 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
213 return getFunctionInfo(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000214
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000215 return getFunctionInfo(FD);
216}
217
Mike Stump1eb44332009-09-09 15:08:12 +0000218const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000219 const CallArgList &Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000220 const FunctionType::ExtInfo &Info) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000221 // FIXME: Kill copy.
John McCallead608a2010-02-26 00:48:12 +0000222 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump1eb44332009-09-09 15:08:12 +0000223 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000224 i != e; ++i)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000225 ArgTys.push_back(Context.getCanonicalParamType(i->Ty));
Rafael Espindola264ba482010-03-30 20:24:48 +0000226 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000227}
228
Mike Stump1eb44332009-09-09 15:08:12 +0000229const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000230 const FunctionArgList &Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000231 const FunctionType::ExtInfo &Info) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000232 // FIXME: Kill copy.
John McCallead608a2010-02-26 00:48:12 +0000233 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump1eb44332009-09-09 15:08:12 +0000234 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000235 i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000236 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
Rafael Espindola264ba482010-03-30 20:24:48 +0000237 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000238}
239
John McCalld26bc762011-03-09 04:27:21 +0000240const CGFunctionInfo &CodeGenTypes::getNullaryFunctionInfo() {
241 llvm::SmallVector<CanQualType, 1> args;
242 return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo());
243}
244
John McCallead608a2010-02-26 00:48:12 +0000245const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
246 const llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000247 const FunctionType::ExtInfo &Info,
248 bool IsRecursive) {
John McCallead608a2010-02-26 00:48:12 +0000249#ifndef NDEBUG
250 for (llvm::SmallVectorImpl<CanQualType>::const_iterator
251 I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I)
252 assert(I->isCanonicalAsParam());
253#endif
254
Rafael Espindola425ef722010-03-30 22:15:11 +0000255 unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000256
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000257 // Lookup or create unique function info.
258 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +0000259 CGFunctionInfo::Profile(ID, Info, ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000260 ArgTys.begin(), ArgTys.end());
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000261
262 void *InsertPos = 0;
263 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
264 if (FI)
265 return *FI;
266
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000267 // Construct the function info.
John McCallf85e1932011-06-15 23:02:42 +0000268 FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult(),
269 Info.getHasRegParm(), Info.getRegParm(), ResTy,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000270 ArgTys.data(), ArgTys.size());
Daniel Dunbar35e67d42009-02-05 00:00:23 +0000271 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000272
273 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000274 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000275
Chris Lattner800588f2010-07-29 06:26:06 +0000276 // Loop over all of the computed argument and return value info. If any of
277 // them are direct or extend without a specified coerce type, specify the
278 // default now.
279 ABIArgInfo &RetInfo = FI->getReturnInfo();
280 if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() == 0)
281 RetInfo.setCoerceToType(ConvertTypeRecursive(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000282
Chris Lattner800588f2010-07-29 06:26:06 +0000283 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
284 I != E; ++I)
285 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
286 I->info.setCoerceToType(ConvertTypeRecursive(I->type));
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000287
Chris Lattnera9fa8582010-07-01 06:20:47 +0000288 // If this is a top-level call and ConvertTypeRecursive hit unresolved pointer
289 // types, resolve them now. These pointers may point to this function, which
290 // we *just* filled in the FunctionInfo for.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000291 if (!IsRecursive && !PointersToResolve.empty())
Chris Lattnera9fa8582010-07-01 06:20:47 +0000292 HandleLateResolvedPointers();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000293
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000294 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000295}
296
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000297CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
John McCallf85e1932011-06-15 23:02:42 +0000298 bool _NoReturn, bool returnsRetained,
299 bool _HasRegParm, unsigned _RegParm,
John McCallead608a2010-02-26 00:48:12 +0000300 CanQualType ResTy,
Chris Lattnerbb521142010-06-29 18:13:52 +0000301 const CanQualType *ArgTys,
302 unsigned NumArgTys)
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000303 : CallingConvention(_CallingConvention),
John McCall04a67a62010-02-05 21:31:56 +0000304 EffectiveCallingConvention(_CallingConvention),
John McCallf85e1932011-06-15 23:02:42 +0000305 NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
306 HasRegParm(_HasRegParm), RegParm(_RegParm)
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000307{
Chris Lattnerbb521142010-06-29 18:13:52 +0000308 NumArgs = NumArgTys;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000309
Chris Lattnerce700162010-06-28 23:44:11 +0000310 // FIXME: Coallocate with the CGFunctionInfo object.
Chris Lattnerbb521142010-06-29 18:13:52 +0000311 Args = new ArgInfo[1 + NumArgTys];
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000312 Args[0].type = ResTy;
Chris Lattnerbb521142010-06-29 18:13:52 +0000313 for (unsigned i = 0; i != NumArgTys; ++i)
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000314 Args[1 + i].type = ArgTys[i];
315}
316
317/***/
318
John McCall42e06112011-05-15 02:19:42 +0000319void CodeGenTypes::GetExpandedTypes(QualType type,
320 llvm::SmallVectorImpl<const llvm::Type*> &expandedTypes,
321 bool isRecursive) {
322 const RecordType *RT = type->getAsStructureType();
Daniel Dunbar56273772008-09-17 00:51:38 +0000323 assert(RT && "Can only expand structure types.");
324 const RecordDecl *RD = RT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000325 assert(!RD->hasFlexibleArrayMember() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000326 "Cannot expand structure with flexible array.");
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000328 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
329 i != e; ++i) {
Daniel Dunbar56273772008-09-17 00:51:38 +0000330 const FieldDecl *FD = *i;
Mike Stump1eb44332009-09-09 15:08:12 +0000331 assert(!FD->isBitField() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000332 "Cannot expand structure with bit-field members.");
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCall42e06112011-05-15 02:19:42 +0000334 QualType fieldType = FD->getType();
335 if (fieldType->isRecordType())
336 GetExpandedTypes(fieldType, expandedTypes, isRecursive);
Chris Lattnerdeabde22010-07-28 18:24:28 +0000337 else
John McCall42e06112011-05-15 02:19:42 +0000338 expandedTypes.push_back(ConvertType(fieldType, isRecursive));
Daniel Dunbar56273772008-09-17 00:51:38 +0000339 }
340}
341
Mike Stump1eb44332009-09-09 15:08:12 +0000342llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000343CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
344 llvm::Function::arg_iterator AI) {
345 const RecordType *RT = Ty->getAsStructureType();
346 assert(RT && "Can only expand structure types.");
347
348 RecordDecl *RD = RT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000349 assert(LV.isSimple() &&
350 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000351 llvm::Value *Addr = LV.getAddress();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000352 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
353 i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 FieldDecl *FD = *i;
Daniel Dunbar56273772008-09-17 00:51:38 +0000355 QualType FT = FD->getType();
356
357 // FIXME: What are the right qualifiers here?
Anders Carlssone6d2a532010-01-29 05:05:36 +0000358 LValue LV = EmitLValueForField(Addr, FD, 0);
Daniel Dunbar56273772008-09-17 00:51:38 +0000359 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
360 AI = ExpandTypeFromArgs(FT, LV, AI);
361 } else {
362 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
363 ++AI;
364 }
365 }
366
367 return AI;
368}
369
Mike Stump1eb44332009-09-09 15:08:12 +0000370void
371CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Daniel Dunbar56273772008-09-17 00:51:38 +0000372 llvm::SmallVector<llvm::Value*, 16> &Args) {
373 const RecordType *RT = Ty->getAsStructureType();
374 assert(RT && "Can only expand structure types.");
375
376 RecordDecl *RD = RT->getDecl();
377 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
378 llvm::Value *Addr = RV.getAggregateAddr();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000379 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
380 i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000381 FieldDecl *FD = *i;
Daniel Dunbar56273772008-09-17 00:51:38 +0000382 QualType FT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Daniel Dunbar56273772008-09-17 00:51:38 +0000384 // FIXME: What are the right qualifiers here?
Anders Carlssone6d2a532010-01-29 05:05:36 +0000385 LValue LV = EmitLValueForField(Addr, FD, 0);
Daniel Dunbar56273772008-09-17 00:51:38 +0000386 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
387 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
388 } else {
389 RValue RV = EmitLoadOfLValue(LV, FT);
Mike Stump1eb44332009-09-09 15:08:12 +0000390 assert(RV.isScalar() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000391 "Unexpected non-scalar rvalue during struct expansion.");
392 Args.push_back(RV.getScalarVal());
393 }
394 }
395}
396
Chris Lattnere7bb7772010-06-27 06:04:18 +0000397/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000398/// accessing some number of bytes out of it, try to gep into the struct to get
399/// at its inner goodness. Dive as deep as possible without entering an element
400/// with an in-memory size smaller than DstSize.
401static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000402EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
403 const llvm::StructType *SrcSTy,
404 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000405 // We can't dive into a zero-element struct.
406 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000407
Chris Lattner08dd2a02010-06-27 05:56:15 +0000408 const llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000409
Chris Lattner08dd2a02010-06-27 05:56:15 +0000410 // If the first elt is at least as large as what we're looking for, or if the
411 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000412 uint64_t FirstEltSize =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000413 CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000414 if (FirstEltSize < DstSize &&
Chris Lattner08dd2a02010-06-27 05:56:15 +0000415 FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
416 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000417
Chris Lattner08dd2a02010-06-27 05:56:15 +0000418 // GEP into the first element.
419 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000420
Chris Lattner08dd2a02010-06-27 05:56:15 +0000421 // If the first element is a struct, recurse.
422 const llvm::Type *SrcTy =
423 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
424 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000425 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000426
427 return SrcPtr;
428}
429
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000430/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
431/// are either integers or pointers. This does a truncation of the value if it
432/// is too large or a zero extension if it is too small.
433static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
434 const llvm::Type *Ty,
435 CodeGenFunction &CGF) {
436 if (Val->getType() == Ty)
437 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000438
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000439 if (isa<llvm::PointerType>(Val->getType())) {
440 // If this is Pointer->Pointer avoid conversion to and from int.
441 if (isa<llvm::PointerType>(Ty))
442 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000443
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000444 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000445 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000446 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000447
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000448 const llvm::Type *DestIntTy = Ty;
449 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000450 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000451
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000452 if (Val->getType() != DestIntTy)
453 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000454
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000455 if (isa<llvm::PointerType>(Ty))
456 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
457 return Val;
458}
459
Chris Lattner08dd2a02010-06-27 05:56:15 +0000460
461
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000462/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
463/// a pointer to an object of type \arg Ty.
464///
465/// This safely handles the case when the src type is smaller than the
466/// destination type; in this situation the values of bits which not
467/// present in the src are undefined.
468static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
469 const llvm::Type *Ty,
470 CodeGenFunction &CGF) {
Mike Stump1eb44332009-09-09 15:08:12 +0000471 const llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000472 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000473
Chris Lattner6ae00692010-06-28 22:51:39 +0000474 // If SrcTy and Ty are the same, just do a load.
475 if (SrcTy == Ty)
476 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000477
Duncan Sands9408c452009-05-09 07:08:47 +0000478 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000479
Chris Lattner08dd2a02010-06-27 05:56:15 +0000480 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000481 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000482 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
483 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000484
Chris Lattner08dd2a02010-06-27 05:56:15 +0000485 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000486
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000487 // If the source and destination are integer or pointer types, just do an
488 // extension or truncation to the desired type.
489 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
490 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
491 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
492 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
493 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000494
Daniel Dunbarb225be42009-02-03 05:59:18 +0000495 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000496 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000497 // Generally SrcSize is never greater than DstSize, since this means we are
498 // losing bits. However, this can happen in cases where the structure has
499 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000500 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000501 // FIXME: Assert that we aren't truncating non-padding bits when have access
502 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000503 llvm::Value *Casted =
504 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000505 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
506 // FIXME: Use better alignment / avoid requiring aligned load.
507 Load->setAlignment(1);
508 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000509 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000510
Chris Lattner35b21b82010-06-27 01:06:27 +0000511 // Otherwise do coercion through memory. This is stupid, but
512 // simple.
513 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
514 llvm::Value *Casted =
515 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
516 llvm::StoreInst *Store =
517 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
518 // FIXME: Use better alignment / avoid requiring aligned store.
519 Store->setAlignment(1);
520 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000521}
522
Eli Friedmanbadea572011-05-17 21:08:01 +0000523// Function to store a first-class aggregate into memory. We prefer to
524// store the elements rather than the aggregate to be more friendly to
525// fast-isel.
526// FIXME: Do we need to recurse here?
527static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
528 llvm::Value *DestPtr, bool DestIsVolatile,
529 bool LowAlignment) {
530 // Prefer scalar stores to first-class aggregate stores.
531 if (const llvm::StructType *STy =
532 dyn_cast<llvm::StructType>(Val->getType())) {
533 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
534 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
535 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
536 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
537 DestIsVolatile);
538 if (LowAlignment)
539 SI->setAlignment(1);
540 }
541 } else {
542 CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
543 }
544}
545
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000546/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
547/// where the source and destination may have different types.
548///
549/// This safely handles the case when the src type is larger than the
550/// destination type; the upper bits of the src will be lost.
551static void CreateCoercedStore(llvm::Value *Src,
552 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000553 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000554 CodeGenFunction &CGF) {
555 const llvm::Type *SrcTy = Src->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000556 const llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000557 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000558 if (SrcTy == DstTy) {
559 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
560 return;
561 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000562
Chris Lattner6ae00692010-06-28 22:51:39 +0000563 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000564
Chris Lattnere7bb7772010-06-27 06:04:18 +0000565 if (const llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
566 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
567 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
568 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000569
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000570 // If the source and destination are integer or pointer types, just do an
571 // extension or truncation to the desired type.
572 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
573 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
574 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
575 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
576 return;
577 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000578
Duncan Sands9408c452009-05-09 07:08:47 +0000579 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000580
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000581 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000582 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000583 llvm::Value *Casted =
584 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000585 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000586 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000587 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000588 // Otherwise do coercion through memory. This is stupid, but
589 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000590
591 // Generally SrcSize is never greater than DstSize, since this means we are
592 // losing bits. However, this can happen in cases where the structure has
593 // additional padding, for example due to a user specified alignment.
594 //
595 // FIXME: Assert that we aren't truncating non-padding bits when have access
596 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000597 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
598 CGF.Builder.CreateStore(Src, Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000599 llvm::Value *Casted =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000600 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000601 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
602 // FIXME: Use better alignment / avoid requiring aligned load.
603 Load->setAlignment(1);
Anders Carlssond2490a92009-12-24 20:40:36 +0000604 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000605 }
606}
607
Daniel Dunbar56273772008-09-17 00:51:38 +0000608/***/
609
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000610bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000611 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000612}
613
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000614bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
615 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
616 switch (BT->getKind()) {
617 default:
618 return false;
619 case BuiltinType::Float:
620 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Float);
621 case BuiltinType::Double:
622 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Double);
623 case BuiltinType::LongDouble:
624 return getContext().Target.useObjCFPRetForRealType(
625 TargetInfo::LongDouble);
626 }
627 }
628
629 return false;
630}
631
John McCallc0bf4622010-02-23 00:48:20 +0000632const llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
633 const CGFunctionInfo &FI = getFunctionInfo(GD);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000634
John McCallc0bf4622010-02-23 00:48:20 +0000635 // For definition purposes, don't consider a K&R function variadic.
636 bool Variadic = false;
637 if (const FunctionProtoType *FPT =
638 cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
639 Variadic = FPT->isVariadic();
640
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000641 return GetFunctionType(FI, Variadic, false);
John McCallc0bf4622010-02-23 00:48:20 +0000642}
643
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000644const llvm::FunctionType *
John McCall42e06112011-05-15 02:19:42 +0000645CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic,
646 bool isRecursive) {
647 llvm::SmallVector<const llvm::Type*, 8> argTypes;
648 const llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000649
John McCall42e06112011-05-15 02:19:42 +0000650 const ABIArgInfo &retAI = FI.getReturnInfo();
651 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000652 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000653 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000654
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000655 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000656 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000657 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000658 break;
659
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000660 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +0000661 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
662 resultType = llvm::Type::getVoidTy(getLLVMContext());
663
664 QualType ret = FI.getReturnType();
665 const llvm::Type *ty = ConvertType(ret, isRecursive);
666 unsigned addressSpace = Context.getTargetAddressSpace(ret);
667 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000668 break;
669 }
670
Daniel Dunbar11434922009-01-26 21:26:08 +0000671 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000672 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000673 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
676 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000677 ie = FI.arg_end(); it != ie; ++it) {
John McCall42e06112011-05-15 02:19:42 +0000678 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000679
John McCall42e06112011-05-15 02:19:42 +0000680 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000681 case ABIArgInfo::Ignore:
682 break;
683
Chris Lattner800588f2010-07-29 06:26:06 +0000684 case ABIArgInfo::Indirect: {
685 // indirect arguments are always on the stack, which is addr space #0.
John McCall42e06112011-05-15 02:19:42 +0000686 const llvm::Type *LTy = ConvertTypeForMem(it->type, isRecursive);
687 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000688 break;
689 }
690
691 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000692 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-06-28 23:44:11 +0000693 // If the coerce-to type is a first class aggregate, flatten it. Either
694 // way is semantically identical, but fast-isel and the optimizer
695 // generally likes scalar values better than FCAs.
John McCall42e06112011-05-15 02:19:42 +0000696 const llvm::Type *argType = argAI.getCoerceToType();
697 if (const llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
698 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
699 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000700 } else {
John McCall42e06112011-05-15 02:19:42 +0000701 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000702 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000703 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000706 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000707 GetExpandedTypes(it->type, argTypes, isRecursive);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000708 break;
709 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000710 }
711
John McCall42e06112011-05-15 02:19:42 +0000712 return llvm::FunctionType::get(resultType, argTypes, isVariadic);
Daniel Dunbar3913f182008-09-09 23:48:28 +0000713}
714
John McCall4c40d982010-08-31 07:33:07 +0000715const llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
716 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000717 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000718
John McCall4c40d982010-08-31 07:33:07 +0000719 if (!VerifyFuncTypeComplete(FPT)) {
720 const CGFunctionInfo *Info;
721 if (isa<CXXDestructorDecl>(MD))
722 Info = &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType());
723 else
724 Info = &getFunctionInfo(MD);
725 return GetFunctionType(*Info, FPT->isVariadic(), false);
726 }
Anders Carlssonecf282b2009-11-24 05:08:52 +0000727
728 return llvm::OpaqueType::get(getLLVMContext());
729}
730
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000731void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +0000732 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000733 AttributeListType &PAL,
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000734 unsigned &CallingConv) {
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000735 unsigned FuncAttrs = 0;
Devang Patela2c69122008-09-26 22:53:57 +0000736 unsigned RetAttrs = 0;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000737
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000738 CallingConv = FI.getEffectiveCallingConvention();
739
John McCall04a67a62010-02-05 21:31:56 +0000740 if (FI.isNoReturn())
741 FuncAttrs |= llvm::Attribute::NoReturn;
742
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000743 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000744 if (TargetDecl) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000745 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000746 FuncAttrs |= llvm::Attribute::NoUnwind;
John McCall9c0c1f32010-07-08 06:48:12 +0000747 else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
748 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000749 if (FPT && FPT->isNothrow(getContext()))
John McCall9c0c1f32010-07-08 06:48:12 +0000750 FuncAttrs |= llvm::Attribute::NoUnwind;
751 }
752
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000753 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000754 FuncAttrs |= llvm::Attribute::NoReturn;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000755 if (TargetDecl->hasAttr<ConstAttr>())
Anders Carlsson232eb7d2008-10-05 23:32:53 +0000756 FuncAttrs |= llvm::Attribute::ReadNone;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000757 else if (TargetDecl->hasAttr<PureAttr>())
Daniel Dunbar64c2e072009-04-10 22:14:52 +0000758 FuncAttrs |= llvm::Attribute::ReadOnly;
Ryan Flynn76168e22009-08-09 20:07:29 +0000759 if (TargetDecl->hasAttr<MallocAttr>())
760 RetAttrs |= llvm::Attribute::NoAlias;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000761 }
762
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000763 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar7ab1c3e2009-10-27 19:48:08 +0000764 FuncAttrs |= llvm::Attribute::OptimizeForSize;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000765 if (CodeGenOpts.DisableRedZone)
Devang Patel24095da2009-06-04 23:32:02 +0000766 FuncAttrs |= llvm::Attribute::NoRedZone;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000767 if (CodeGenOpts.NoImplicitFloat)
Devang Patelacebb392009-06-05 22:05:48 +0000768 FuncAttrs |= llvm::Attribute::NoImplicitFloat;
Devang Patel24095da2009-06-04 23:32:02 +0000769
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000770 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000771 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000772 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000773 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000774 case ABIArgInfo::Extend:
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000775 if (RetTy->hasSignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000776 RetAttrs |= llvm::Attribute::SExt;
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000777 else if (RetTy->hasUnsignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000778 RetAttrs |= llvm::Attribute::ZExt;
Chris Lattner800588f2010-07-29 06:26:06 +0000779 break;
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000780 case ABIArgInfo::Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000781 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000782 break;
783
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000784 case ABIArgInfo::Indirect:
Mike Stump1eb44332009-09-09 15:08:12 +0000785 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Chris Lattnerfb97cf22010-04-20 05:44:43 +0000786 llvm::Attribute::StructRet));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000787 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000788 // sret disables readnone and readonly
789 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
790 llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000791 break;
792
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000793 case ABIArgInfo::Expand:
Mike Stump1eb44332009-09-09 15:08:12 +0000794 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000795 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000796
Devang Patela2c69122008-09-26 22:53:57 +0000797 if (RetAttrs)
798 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000799
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000800 // FIXME: RegParm should be reduced in case of global register variable.
Eli Friedmana49218e2011-04-09 08:18:08 +0000801 signed RegParm;
802 if (FI.getHasRegParm())
803 RegParm = FI.getRegParm();
804 else
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000805 RegParm = CodeGenOpts.NumRegisterParameters;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000806
807 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000808 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000809 ie = FI.arg_end(); it != ie; ++it) {
810 QualType ParamType = it->type;
811 const ABIArgInfo &AI = it->info;
Devang Patel761d7f72008-09-25 21:02:23 +0000812 unsigned Attributes = 0;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000813
John McCalld8e10d22010-03-27 00:47:27 +0000814 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
815 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +0000816 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000817 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +0000818 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000819 if (ParamType->isSignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000820 Attributes |= llvm::Attribute::SExt;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000821 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000822 Attributes |= llvm::Attribute::ZExt;
823 // FALL THROUGH
824 case ABIArgInfo::Direct:
825 if (RegParm > 0 &&
826 (ParamType->isIntegerType() || ParamType->isPointerType())) {
827 RegParm -=
828 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
829 if (RegParm >= 0)
830 Attributes |= llvm::Attribute::InReg;
831 }
832 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000833
Chris Lattnerce700162010-06-28 23:44:11 +0000834 if (const llvm::StructType *STy =
Chris Lattner800588f2010-07-29 06:26:06 +0000835 dyn_cast<llvm::StructType>(AI.getCoerceToType()))
836 Index += STy->getNumElements()-1; // 1 will be added below.
837 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000838
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000839 case ABIArgInfo::Indirect:
Anders Carlsson0a8f8472009-09-16 15:53:40 +0000840 if (AI.getIndirectByVal())
841 Attributes |= llvm::Attribute::ByVal;
842
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000843 Attributes |=
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000844 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000845 // byval disables readnone and readonly.
846 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
847 llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000848 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000849
Daniel Dunbar11434922009-01-26 21:26:08 +0000850 case ABIArgInfo::Ignore:
851 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000852 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +0000853
Daniel Dunbar56273772008-09-17 00:51:38 +0000854 case ABIArgInfo::Expand: {
John McCall42e06112011-05-15 02:19:42 +0000855 llvm::SmallVector<const llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +0000856 // FIXME: This is rather inefficient. Do we ever actually need to do
857 // anything here? The result should be just reconstructed on the other
858 // side, so extension should be a non-issue.
John McCall42e06112011-05-15 02:19:42 +0000859 getTypes().GetExpandedTypes(ParamType, types, false);
860 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +0000861 continue;
862 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Devang Patel761d7f72008-09-25 21:02:23 +0000865 if (Attributes)
866 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar56273772008-09-17 00:51:38 +0000867 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000868 }
Devang Patela2c69122008-09-26 22:53:57 +0000869 if (FuncAttrs)
870 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000871}
872
John McCalld26bc762011-03-09 04:27:21 +0000873/// An argument came in as a promoted argument; demote it back to its
874/// declared type.
875static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
876 const VarDecl *var,
877 llvm::Value *value) {
878 const llvm::Type *varType = CGF.ConvertType(var->getType());
879
880 // This can happen with promotions that actually don't change the
881 // underlying type, like the enum promotions.
882 if (value->getType() == varType) return value;
883
884 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
885 && "unexpected promotion type");
886
887 if (isa<llvm::IntegerType>(varType))
888 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
889
890 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
891}
892
Daniel Dunbar88b53962009-02-02 22:03:45 +0000893void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
894 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000895 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +0000896 // If this is an implicit-return-zero function, go ahead and
897 // initialize the return value. TODO: it might be nice to have
898 // a more general mechanism for this that didn't require synthesized
899 // return statements.
Chris Lattner121b3fa2010-07-05 20:21:00 +0000900 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +0000901 if (FD->hasImplicitReturnZero()) {
902 QualType RetTy = FD->getResultType().getUnqualifiedType();
903 const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000904 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +0000905 Builder.CreateStore(Zero, ReturnValue);
906 }
907 }
908
Mike Stumpf5408fe2009-05-16 07:57:57 +0000909 // FIXME: We no longer need the types from FunctionArgList; lift up and
910 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +0000911
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000912 // Emit allocs for param decls. Give the LLVM Argument nodes names.
913 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000915 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000916 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000917 AI->setName("agg.result");
918 ++AI;
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +0000921 assert(FI.arg_size() == Args.size() &&
922 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +0000923 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000924 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +0000925 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
926 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +0000927 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000928 QualType Ty = info_it->type;
929 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000930
John McCalld26bc762011-03-09 04:27:21 +0000931 bool isPromoted =
932 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
933
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000934 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +0000935 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +0000936 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000937
Daniel Dunbar1f745982009-02-05 09:16:39 +0000938 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000939 // Aggregates and complex variables are accessed by reference. All we
940 // need to do is realign the value, if requested
941 if (ArgI.getIndirectRealign()) {
942 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
943
944 // Copy from the incoming argument pointer to the temporary with the
945 // appropriate alignment.
946 //
947 // FIXME: We should have a common utility for generating an aggregate
948 // copy.
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000949 const llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +0000950 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +0000951 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
952 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
953 Builder.CreateMemCpy(Dst,
954 Src,
Ken Dyckfe710082011-01-19 01:58:38 +0000955 llvm::ConstantInt::get(IntPtrTy,
956 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000957 ArgI.getIndirectAlign(),
958 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000959 V = AlignedTemp;
960 }
Daniel Dunbar1f745982009-02-05 09:16:39 +0000961 } else {
962 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +0000963 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
964 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalld26bc762011-03-09 04:27:21 +0000965
966 if (isPromoted)
967 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000968 }
Devang Patel093ac462011-03-03 20:13:15 +0000969 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000970 break;
971 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000972
973 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000974 case ABIArgInfo::Direct: {
Chris Lattner800588f2010-07-29 06:26:06 +0000975 // If we have the trivial case, handle it with no muss and fuss.
976 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +0000977 ArgI.getCoerceToType() == ConvertType(Ty) &&
978 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +0000979 assert(AI != Fn->arg_end() && "Argument mismatch!");
980 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000981
John McCalld8e10d22010-03-27 00:47:27 +0000982 if (Arg->getType().isRestrictQualified())
983 AI->addAttr(llvm::Attribute::NoAlias);
984
John McCalld26bc762011-03-09 04:27:21 +0000985 if (isPromoted)
986 V = emitArgumentDemotion(*this, Arg, V);
987
Devang Patel093ac462011-03-03 20:13:15 +0000988 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +0000989 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +0000990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner121b3fa2010-07-05 20:21:00 +0000992 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000993
Chris Lattnerdeabde22010-07-28 18:24:28 +0000994 // The alignment we need to use is the max of the requested alignment for
995 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000996 unsigned AlignmentToUse =
John McCalld16c2cf2011-02-08 08:22:06 +0000997 CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +0000998 AlignmentToUse = std::max(AlignmentToUse,
999 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001000
Chris Lattnerdeabde22010-07-28 18:24:28 +00001001 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001002 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001003 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001004
Chris Lattner117e3f42010-07-30 04:02:24 +00001005 // If the value is offset in memory, apply the offset now.
1006 if (unsigned Offs = ArgI.getDirectOffset()) {
1007 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1008 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001009 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001010 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1011 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001012
Chris Lattner309c59f2010-06-29 00:06:42 +00001013 // If the coerce-to type is a first class aggregate, we flatten it and
1014 // pass the elements. Either way is semantically identical, but fast-isel
1015 // and the optimizer generally likes scalar values better than FCAs.
1016 if (const llvm::StructType *STy =
1017 dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001018 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001019
Chris Lattner92826882010-07-05 20:41:41 +00001020 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1021 assert(AI != Fn->arg_end() && "Argument mismatch!");
1022 AI->setName(Arg->getName() + ".coerce" + llvm::Twine(i));
1023 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1024 Builder.CreateStore(AI++, EltPtr);
Chris Lattner309c59f2010-06-29 00:06:42 +00001025 }
1026 } else {
1027 // Simple case, just do a coerced store of the argument into the alloca.
1028 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001029 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001030 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001031 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001032
1033
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001034 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001035 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001036 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalld26bc762011-03-09 04:27:21 +00001037 if (isPromoted)
1038 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001039 }
Devang Patel093ac462011-03-03 20:13:15 +00001040 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001041 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001042 }
Chris Lattner800588f2010-07-29 06:26:06 +00001043
1044 case ABIArgInfo::Expand: {
1045 // If this structure was expanded into multiple arguments then
1046 // we need to create a temporary and reconstruct it from the
1047 // arguments.
1048 llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr");
Chris Lattner800588f2010-07-29 06:26:06 +00001049 llvm::Function::arg_iterator End =
Daniel Dunbar79c39282010-08-21 03:15:20 +00001050 ExpandTypeFromArgs(Ty, MakeAddrLValue(Temp, Ty), AI);
Devang Patel093ac462011-03-03 20:13:15 +00001051 EmitParmDecl(*Arg, Temp, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001052
1053 // Name the arguments used in expansion and increment AI.
1054 unsigned Index = 0;
1055 for (; AI != End; ++AI, ++Index)
1056 AI->setName(Arg->getName() + "." + llvm::Twine(Index));
1057 continue;
1058 }
1059
1060 case ABIArgInfo::Ignore:
1061 // Initialize the local variable appropriately.
1062 if (hasAggregateLLVMType(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001063 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001064 else
Devang Patel093ac462011-03-03 20:13:15 +00001065 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1066 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001067
1068 // Skip increment, no matching LLVM parameter.
1069 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001070 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001071
1072 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001073 }
1074 assert(AI == Fn->arg_end() && "Argument mismatch!");
1075}
1076
John McCallf85e1932011-06-15 23:02:42 +00001077/// Try to emit a fused autorelease of a return result.
1078static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1079 llvm::Value *result) {
1080 // We must be immediately followed the cast.
1081 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1082 if (BB->empty()) return 0;
1083 if (&BB->back() != result) return 0;
1084
1085 const llvm::Type *resultType = result->getType();
1086
1087 // result is in a BasicBlock and is therefore an Instruction.
1088 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1089
1090 llvm::SmallVector<llvm::Instruction*,4> insnsToKill;
1091
1092 // Look for:
1093 // %generator = bitcast %type1* %generator2 to %type2*
1094 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1095 // We would have emitted this as a constant if the operand weren't
1096 // an Instruction.
1097 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1098
1099 // Require the generator to be immediately followed by the cast.
1100 if (generator->getNextNode() != bitcast)
1101 return 0;
1102
1103 insnsToKill.push_back(bitcast);
1104 }
1105
1106 // Look for:
1107 // %generator = call i8* @objc_retain(i8* %originalResult)
1108 // or
1109 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1110 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1111 if (!call) return 0;
1112
1113 bool doRetainAutorelease;
1114
1115 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1116 doRetainAutorelease = true;
1117 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1118 .objc_retainAutoreleasedReturnValue) {
1119 doRetainAutorelease = false;
1120
1121 // Look for an inline asm immediately preceding the call and kill it, too.
1122 llvm::Instruction *prev = call->getPrevNode();
1123 if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev))
1124 if (asmCall->getCalledValue()
1125 == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker)
1126 insnsToKill.push_back(prev);
1127 } else {
1128 return 0;
1129 }
1130
1131 result = call->getArgOperand(0);
1132 insnsToKill.push_back(call);
1133
1134 // Keep killing bitcasts, for sanity. Note that we no longer care
1135 // about precise ordering as long as there's exactly one use.
1136 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1137 if (!bitcast->hasOneUse()) break;
1138 insnsToKill.push_back(bitcast);
1139 result = bitcast->getOperand(0);
1140 }
1141
1142 // Delete all the unnecessary instructions, from latest to earliest.
1143 for (llvm::SmallVectorImpl<llvm::Instruction*>::iterator
1144 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1145 (*i)->eraseFromParent();
1146
1147 // Do the fused retain/autorelease if we were asked to.
1148 if (doRetainAutorelease)
1149 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1150
1151 // Cast back to the result type.
1152 return CGF.Builder.CreateBitCast(result, resultType);
1153}
1154
1155/// Emit an ARC autorelease of the result of a function.
1156static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1157 llvm::Value *result) {
1158 // At -O0, try to emit a fused retain/autorelease.
1159 if (CGF.shouldUseFusedARCCalls())
1160 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1161 return fused;
1162
1163 return CGF.EmitARCAutoreleaseReturnValue(result);
1164}
1165
Chris Lattner35b21b82010-06-27 01:06:27 +00001166void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001167 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001168 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001169 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001170 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001171 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001172
Dan Gohman4751a532010-07-20 20:13:52 +00001173 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001174 llvm::Value *RV = 0;
1175 QualType RetTy = FI.getReturnType();
1176 const ABIArgInfo &RetAI = FI.getReturnInfo();
1177
1178 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001179 case ABIArgInfo::Indirect: {
1180 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001181 if (RetTy->isAnyComplexType()) {
1182 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1183 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1184 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1185 // Do nothing; aggregrates get evaluated directly into the destination.
1186 } else {
1187 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001188 false, Alignment, RetTy);
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001189 }
1190 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001191 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001192
1193 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001194 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001195 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1196 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001197 // The internal return value temp always will have pointer-to-return-type
1198 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001199
Chris Lattner800588f2010-07-29 06:26:06 +00001200 // If the instruction right before the insertion point is a store to the
1201 // return value, we can elide the load, zap the store, and usually zap the
1202 // alloca.
1203 llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1204 llvm::StoreInst *SI = 0;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001205 if (InsertBB->empty() ||
Chris Lattner800588f2010-07-29 06:26:06 +00001206 !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1207 SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1208 RV = Builder.CreateLoad(ReturnValue);
1209 } else {
1210 // Get the stored value and nuke the now-dead store.
1211 RetDbgLoc = SI->getDebugLoc();
1212 RV = SI->getValueOperand();
1213 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001214
Chris Lattner800588f2010-07-29 06:26:06 +00001215 // If that was the only use of the return value, nuke it as well now.
1216 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1217 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1218 ReturnValue = 0;
1219 }
Chris Lattner35b21b82010-06-27 01:06:27 +00001220 }
Chris Lattner800588f2010-07-29 06:26:06 +00001221 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001222 llvm::Value *V = ReturnValue;
1223 // If the value is offset in memory, apply the offset now.
1224 if (unsigned Offs = RetAI.getDirectOffset()) {
1225 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1226 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001227 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001228 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1229 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001230
Chris Lattner117e3f42010-07-30 04:02:24 +00001231 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001232 }
John McCallf85e1932011-06-15 23:02:42 +00001233
1234 // In ARC, end functions that return a retainable type with a call
1235 // to objc_autoreleaseReturnValue.
1236 if (AutoreleaseResult) {
1237 assert(getLangOptions().ObjCAutoRefCount &&
1238 !FI.isReturnsRetained() &&
1239 RetTy->isObjCRetainableType());
1240 RV = emitAutoreleaseOfResult(*this, RV);
1241 }
1242
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001243 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001244
Chris Lattner800588f2010-07-29 06:26:06 +00001245 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001246 break;
1247
1248 case ABIArgInfo::Expand:
1249 assert(0 && "Invalid ABI kind for return argument");
1250 }
1251
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001252 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001253 if (!RetDbgLoc.isUnknown())
1254 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001255}
1256
John McCall413ebdb2011-03-11 20:59:21 +00001257void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1258 const VarDecl *param) {
John McCall27360712010-05-26 22:34:26 +00001259 // StartFunction converted the ABI-lowered parameter(s) into a
1260 // local alloca. We need to turn that into an r-value suitable
1261 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001262 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001263
John McCall413ebdb2011-03-11 20:59:21 +00001264 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001265
John McCall27360712010-05-26 22:34:26 +00001266 // For the most part, we just need to load the alloca, except:
1267 // 1) aggregate r-values are actually pointers to temporaries, and
1268 // 2) references to aggregates are pointers directly to the aggregate.
1269 // I don't know why references to non-aggregates are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001270 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1271 if (hasAggregateLLVMType(ref->getPointeeType()))
1272 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001273
1274 // Locals which are references to scalars are represented
1275 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001276 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001277 }
1278
John McCall413ebdb2011-03-11 20:59:21 +00001279 if (type->isAnyComplexType()) {
1280 ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false);
1281 return args.add(RValue::getComplex(complex), type);
1282 }
John McCall27360712010-05-26 22:34:26 +00001283
John McCall413ebdb2011-03-11 20:59:21 +00001284 if (hasAggregateLLVMType(type))
1285 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001286
John McCall413ebdb2011-03-11 20:59:21 +00001287 unsigned alignment = getContext().getDeclAlign(param).getQuantity();
1288 llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type);
1289 return args.add(RValue::get(value), type);
John McCall27360712010-05-26 22:34:26 +00001290}
1291
John McCallf85e1932011-06-15 23:02:42 +00001292static bool isProvablyNull(llvm::Value *addr) {
1293 return isa<llvm::ConstantPointerNull>(addr);
1294}
1295
1296static bool isProvablyNonNull(llvm::Value *addr) {
1297 return isa<llvm::AllocaInst>(addr);
1298}
1299
1300/// Emit the actual writing-back of a writeback.
1301static void emitWriteback(CodeGenFunction &CGF,
1302 const CallArgList::Writeback &writeback) {
1303 llvm::Value *srcAddr = writeback.Address;
1304 assert(!isProvablyNull(srcAddr) &&
1305 "shouldn't have writeback for provably null argument");
1306
1307 llvm::BasicBlock *contBB = 0;
1308
1309 // If the argument wasn't provably non-null, we need to null check
1310 // before doing the store.
1311 bool provablyNonNull = isProvablyNonNull(srcAddr);
1312 if (!provablyNonNull) {
1313 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1314 contBB = CGF.createBasicBlock("icr.done");
1315
1316 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1317 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1318 CGF.EmitBlock(writebackBB);
1319 }
1320
1321 // Load the value to writeback.
1322 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1323
1324 // Cast it back, in case we're writing an id to a Foo* or something.
1325 value = CGF.Builder.CreateBitCast(value,
1326 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1327 "icr.writeback-cast");
1328
1329 // Perform the writeback.
1330 QualType srcAddrType = writeback.AddressType;
1331 CGF.EmitStoreThroughLValue(RValue::get(value),
1332 CGF.MakeAddrLValue(srcAddr, srcAddrType),
1333 srcAddrType);
1334
1335 // Jump to the continuation block.
1336 if (!provablyNonNull)
1337 CGF.EmitBlock(contBB);
1338}
1339
1340static void emitWritebacks(CodeGenFunction &CGF,
1341 const CallArgList &args) {
1342 for (CallArgList::writeback_iterator
1343 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1344 emitWriteback(CGF, *i);
1345}
1346
1347/// Emit an argument that's being passed call-by-writeback. That is,
1348/// we are passing the address of
1349static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1350 const ObjCIndirectCopyRestoreExpr *CRE) {
1351 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1352
1353 // The dest and src types don't necessarily match in LLVM terms
1354 // because of the crazy ObjC compatibility rules.
1355
1356 const llvm::PointerType *destType =
1357 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1358
1359 // If the address is a constant null, just pass the appropriate null.
1360 if (isProvablyNull(srcAddr)) {
1361 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1362 CRE->getType());
1363 return;
1364 }
1365
1366 QualType srcAddrType =
1367 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1368
1369 // Create the temporary.
1370 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1371 "icr.temp");
1372
1373 // Zero-initialize it if we're not doing a copy-initialization.
1374 bool shouldCopy = CRE->shouldCopy();
1375 if (!shouldCopy) {
1376 llvm::Value *null =
1377 llvm::ConstantPointerNull::get(
1378 cast<llvm::PointerType>(destType->getElementType()));
1379 CGF.Builder.CreateStore(null, temp);
1380 }
1381
1382 llvm::BasicBlock *contBB = 0;
1383
1384 // If the address is *not* known to be non-null, we need to switch.
1385 llvm::Value *finalArgument;
1386
1387 bool provablyNonNull = isProvablyNonNull(srcAddr);
1388 if (provablyNonNull) {
1389 finalArgument = temp;
1390 } else {
1391 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1392
1393 finalArgument = CGF.Builder.CreateSelect(isNull,
1394 llvm::ConstantPointerNull::get(destType),
1395 temp, "icr.argument");
1396
1397 // If we need to copy, then the load has to be conditional, which
1398 // means we need control flow.
1399 if (shouldCopy) {
1400 contBB = CGF.createBasicBlock("icr.cont");
1401 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1402 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1403 CGF.EmitBlock(copyBB);
1404 }
1405 }
1406
1407 // Perform a copy if necessary.
1408 if (shouldCopy) {
1409 LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
1410 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, srcAddrType);
1411 assert(srcRV.isScalar());
1412
1413 llvm::Value *src = srcRV.getScalarVal();
1414 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1415 "icr.cast");
1416
1417 // Use an ordinary store, not a store-to-lvalue.
1418 CGF.Builder.CreateStore(src, temp);
1419 }
1420
1421 // Finish the control flow if we needed it.
1422 if (shouldCopy && !provablyNonNull)
1423 CGF.EmitBlock(contBB);
1424
1425 args.addWriteback(srcAddr, srcAddrType, temp);
1426 args.add(RValue::get(finalArgument), CRE->getType());
1427}
1428
John McCall413ebdb2011-03-11 20:59:21 +00001429void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1430 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00001431 if (const ObjCIndirectCopyRestoreExpr *CRE
1432 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
1433 assert(getContext().getLangOptions().ObjCAutoRefCount);
1434 assert(getContext().hasSameType(E->getType(), type));
1435 return emitWritebackArg(*this, args, CRE);
1436 }
1437
John McCall413ebdb2011-03-11 20:59:21 +00001438 if (type->isReferenceType())
1439 return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0),
1440 type);
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001442 if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() &&
1443 isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00001444 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
1445 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
1446 assert(L.isSimple());
1447 args.add(RValue::getAggregate(L.getAddress(), L.isVolatileQualified()),
1448 type, /*NeedsCopy*/true);
1449 return;
1450 }
1451
John McCall413ebdb2011-03-11 20:59:21 +00001452 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00001453}
1454
John McCallf1549f62010-07-06 01:34:17 +00001455/// Emits a call or invoke instruction to the given function, depending
1456/// on the current state of the EH stack.
1457llvm::CallSite
1458CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1459 llvm::Value * const *ArgBegin,
1460 llvm::Value * const *ArgEnd,
1461 const llvm::Twine &Name) {
1462 llvm::BasicBlock *InvokeDest = getInvokeDest();
1463 if (!InvokeDest)
1464 return Builder.CreateCall(Callee, ArgBegin, ArgEnd, Name);
1465
1466 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1467 llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
1468 ArgBegin, ArgEnd, Name);
1469 EmitBlock(ContBB);
1470 return Invoke;
1471}
1472
Daniel Dunbar88b53962009-02-02 22:03:45 +00001473RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001474 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001475 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00001476 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00001477 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00001478 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001479 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001480 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001481
1482 // Handle struct-return functions by passing a pointer to the
1483 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001484 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001485 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001486
1487
Chris Lattner5db7ae52009-06-13 00:26:38 +00001488 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00001489 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001490 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00001491 llvm::Value *Value = ReturnValue.getValue();
1492 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00001493 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00001494 Args.push_back(Value);
1495 }
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001497 assert(CallInfo.arg_size() == CallArgs.size() &&
1498 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00001499 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001500 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001501 I != E; ++I, ++info_it) {
1502 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00001503 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00001504
Eli Friedman97cb5a42011-06-15 22:09:18 +00001505 unsigned TypeAlign =
Eli Friedmanc6d07822011-05-02 18:05:27 +00001506 getContext().getTypeAlignInChars(I->Ty).getQuantity();
Daniel Dunbar56273772008-09-17 00:51:38 +00001507 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001508 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001509 if (RV.isScalar() || RV.isComplex()) {
1510 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001511 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1512 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
1513 AI->setAlignment(ArgInfo.getIndirectAlign());
1514 Args.push_back(AI);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001515 if (RV.isScalar())
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001516 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false,
Eli Friedman97cb5a42011-06-15 22:09:18 +00001517 TypeAlign, I->Ty);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001518 else
Mike Stump1eb44332009-09-09 15:08:12 +00001519 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001520 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001521 // We want to avoid creating an unnecessary temporary+copy here;
1522 // however, we need one in two cases:
1523 // 1. If the argument is not byval, and we are required to copy the
1524 // source. (This case doesn't occur on any common architecture.)
1525 // 2. If the argument is byval, RV is not sufficiently aligned, and
1526 // we cannot force it to be sufficiently aligned.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001527 llvm::Value *Addr = RV.getAggregateAddr();
1528 unsigned Align = ArgInfo.getIndirectAlign();
1529 const llvm::TargetData *TD = &CGM.getTargetData();
1530 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
1531 (ArgInfo.getIndirectByVal() && TypeAlign < Align &&
1532 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001533 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001534 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1535 if (Align > AI->getAlignment())
1536 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001537 Args.push_back(AI);
Eli Friedman97cb5a42011-06-15 22:09:18 +00001538 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001539 } else {
1540 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001541 Args.push_back(Addr);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001542 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001543 }
1544 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001545 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001546
Daniel Dunbar11434922009-01-26 21:26:08 +00001547 case ABIArgInfo::Ignore:
1548 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001549
Chris Lattner800588f2010-07-29 06:26:06 +00001550 case ABIArgInfo::Extend:
1551 case ABIArgInfo::Direct: {
1552 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001553 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
1554 ArgInfo.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001555 if (RV.isScalar())
1556 Args.push_back(RV.getScalarVal());
1557 else
1558 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
1559 break;
1560 }
Daniel Dunbar11434922009-01-26 21:26:08 +00001561
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001562 // FIXME: Avoid the conversion through memory if possible.
1563 llvm::Value *SrcPtr;
1564 if (RV.isScalar()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001565 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Eli Friedman97cb5a42011-06-15 22:09:18 +00001566 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty);
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001567 } else if (RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001568 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001569 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001570 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001571 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001572
Chris Lattner117e3f42010-07-30 04:02:24 +00001573 // If the value is offset in memory, apply the offset now.
1574 if (unsigned Offs = ArgInfo.getDirectOffset()) {
1575 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
1576 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001577 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001578 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
1579
1580 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001581
Chris Lattnerce700162010-06-28 23:44:11 +00001582 // If the coerce-to type is a first class aggregate, we flatten it and
1583 // pass the elements. Either way is semantically identical, but fast-isel
1584 // and the optimizer generally likes scalar values better than FCAs.
1585 if (const llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00001586 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001587 SrcPtr = Builder.CreateBitCast(SrcPtr,
1588 llvm::PointerType::getUnqual(STy));
1589 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1590 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00001591 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
1592 // We don't know what we're loading from.
1593 LI->setAlignment(1);
1594 Args.push_back(LI);
Chris Lattner309c59f2010-06-29 00:06:42 +00001595 }
Chris Lattnerce700162010-06-28 23:44:11 +00001596 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00001597 // In the simple case, just pass the coerced loaded value.
1598 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1599 *this));
Chris Lattnerce700162010-06-28 23:44:11 +00001600 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001601
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001602 break;
1603 }
1604
Daniel Dunbar56273772008-09-17 00:51:38 +00001605 case ABIArgInfo::Expand:
Eli Friedmanc6d07822011-05-02 18:05:27 +00001606 ExpandTypeToArgs(I->Ty, RV, Args);
Daniel Dunbar56273772008-09-17 00:51:38 +00001607 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001608 }
1609 }
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Chris Lattner5db7ae52009-06-13 00:26:38 +00001611 // If the callee is a bitcast of a function to a varargs pointer to function
1612 // type, check to see if we can remove the bitcast. This handles some cases
1613 // with unprototyped functions.
1614 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1615 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
1616 const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1617 const llvm::FunctionType *CurFT =
1618 cast<llvm::FunctionType>(CurPT->getElementType());
1619 const llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Chris Lattner5db7ae52009-06-13 00:26:38 +00001621 if (CE->getOpcode() == llvm::Instruction::BitCast &&
1622 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00001623 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00001624 ActualFT->getNumParams() == Args.size() &&
1625 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00001626 bool ArgsMatch = true;
1627 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1628 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1629 ArgsMatch = false;
1630 break;
1631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner5db7ae52009-06-13 00:26:38 +00001633 // Strip the cast if we can get away with it. This is a nice cleanup,
1634 // but also allows us to inline the function at -O0 if it is marked
1635 // always_inline.
1636 if (ArgsMatch)
1637 Callee = CalleeF;
1638 }
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001641
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001642 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00001643 CodeGen::AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001644 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001645 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1646 AttributeList.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001647
John McCallf1549f62010-07-06 01:34:17 +00001648 llvm::BasicBlock *InvokeDest = 0;
1649 if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1650 InvokeDest = getInvokeDest();
1651
Daniel Dunbard14151d2009-03-02 04:32:35 +00001652 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00001653 if (!InvokeDest) {
Jay Foadbeaaccd2009-05-21 09:52:38 +00001654 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001655 } else {
1656 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Mike Stump1eb44332009-09-09 15:08:12 +00001657 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001658 Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001659 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001660 }
Chris Lattnerce933992010-06-29 16:40:28 +00001661 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00001662 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001663
Daniel Dunbard14151d2009-03-02 04:32:35 +00001664 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001665 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00001666
1667 // If the call doesn't return, finish the basic block and clear the
1668 // insertion point; this allows the rest of IRgen to discard
1669 // unreachable code.
1670 if (CS.doesNotReturn()) {
1671 Builder.CreateUnreachable();
1672 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Mike Stumpf5408fe2009-05-16 07:57:57 +00001674 // FIXME: For now, emit a dummy basic block because expr emitters in
1675 // generally are not ready to handle emitting expressions at unreachable
1676 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00001677 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Daniel Dunbard14151d2009-03-02 04:32:35 +00001679 // Return a reasonable RValue.
1680 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001681 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00001682
1683 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001684 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001685 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001686
John McCallf85e1932011-06-15 23:02:42 +00001687 // Emit any writebacks immediately. Arguably this should happen
1688 // after any return-value munging.
1689 if (CallArgs.hasWritebacks())
1690 emitWritebacks(*this, CallArgs);
1691
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001692 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001693 case ABIArgInfo::Indirect: {
1694 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001695 if (RetTy->isAnyComplexType())
Daniel Dunbar56273772008-09-17 00:51:38 +00001696 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner34030842009-03-22 00:32:22 +00001697 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar56273772008-09-17 00:51:38 +00001698 return RValue::getAggregate(Args[0]);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001699 return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy));
1700 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001701
Daniel Dunbar11434922009-01-26 21:26:08 +00001702 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001703 // If we are ignoring an argument that had a result, make sure to
1704 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00001705 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001706
Chris Lattner800588f2010-07-29 06:26:06 +00001707 case ABIArgInfo::Extend:
1708 case ABIArgInfo::Direct: {
Chris Lattner117e3f42010-07-30 04:02:24 +00001709 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1710 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001711 if (RetTy->isAnyComplexType()) {
1712 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1713 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1714 return RValue::getComplex(std::make_pair(Real, Imag));
1715 }
1716 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1717 llvm::Value *DestPtr = ReturnValue.getValue();
1718 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00001719
Chris Lattner800588f2010-07-29 06:26:06 +00001720 if (!DestPtr) {
1721 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1722 DestIsVolatile = false;
1723 }
Eli Friedmanbadea572011-05-17 21:08:01 +00001724 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00001725 return RValue::getAggregate(DestPtr);
1726 }
1727 return RValue::get(CI);
1728 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001729
Anders Carlssond2490a92009-12-24 20:40:36 +00001730 llvm::Value *DestPtr = ReturnValue.getValue();
1731 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001732
Anders Carlssond2490a92009-12-24 20:40:36 +00001733 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00001734 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00001735 DestIsVolatile = false;
1736 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001737
Chris Lattner117e3f42010-07-30 04:02:24 +00001738 // If the value is offset in memory, apply the offset now.
1739 llvm::Value *StorePtr = DestPtr;
1740 if (unsigned Offs = RetAI.getDirectOffset()) {
1741 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
1742 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001743 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001744 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1745 }
1746 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001747
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001748 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Anders Carlssonad3d6912008-11-25 22:21:48 +00001749 if (RetTy->isAnyComplexType())
Anders Carlssond2490a92009-12-24 20:40:36 +00001750 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
Chris Lattner34030842009-03-22 00:32:22 +00001751 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssond2490a92009-12-24 20:40:36 +00001752 return RValue::getAggregate(DestPtr);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001753 return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy));
Daniel Dunbar639ffe42008-09-10 07:04:09 +00001754 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001755
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001756 case ABIArgInfo::Expand:
Mike Stump1eb44332009-09-09 15:08:12 +00001757 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001758 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001759
1760 assert(0 && "Unhandled ABIArgInfo::Kind");
1761 return RValue::get(0);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001762}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001763
1764/* VarArg handling */
1765
1766llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1767 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1768}