blob: 51ce1b98b999e6b88c7df1b03dede72ca8462e2b [file] [log] [blame]
Anders Carlsson87fc5a52008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump11289f42009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000015
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson1235bbc2009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000025#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000029RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
30 llvm::Value *Callee,
31 llvm::Value *This,
32 CallExpr::const_arg_iterator ArgBeg,
33 CallExpr::const_arg_iterator ArgEnd) {
Mike Stump11289f42009-09-09 15:08:12 +000034 assert(MD->isInstance() &&
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000035 "Trying to emit a member call expr on a static method!");
36
John McCall9dd450b2009-09-21 23:43:11 +000037 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +000038
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000039 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +000040
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000041 // Push the this ptr.
42 Args.push_back(std::make_pair(RValue::get(This),
43 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +000044
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000045 // And the rest of the call args
46 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
Mike Stump11289f42009-09-09 15:08:12 +000047
John McCall9dd450b2009-09-21 23:43:11 +000048 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000049 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
50 Callee, Args, MD);
51}
52
Anders Carlssond7432df2009-10-12 19:41:04 +000053/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
54/// expr can be devirtualized.
55static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
56 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
57 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
58 // This is a record decl. We know the type and can devirtualize it.
59 return VD->getType()->isRecordType();
60 }
Anders Carlssonb61301f2009-10-12 19:45:47 +000061
62 return false;
Anders Carlssond7432df2009-10-12 19:41:04 +000063 }
64
Anders Carlssona1b54fd2009-10-12 19:59:15 +000065 // We can always devirtualize calls on temporary object expressions.
Anders Carlssonb61301f2009-10-12 19:45:47 +000066 if (isa<CXXTemporaryObjectExpr>(Base))
67 return true;
68
Anders Carlssona1b54fd2009-10-12 19:59:15 +000069 // And calls on bound temporaries.
70 if (isa<CXXBindTemporaryExpr>(Base))
71 return true;
72
Anders Carlsson2a017092009-10-12 19:51:33 +000073 // Check if this is a call expr that returns a record type.
74 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
75 return CE->getCallReturnType()->isRecordType();
76
Anders Carlssond7432df2009-10-12 19:41:04 +000077 // We can't devirtualize the call.
78 return false;
79}
80
Anders Carlssone5fd6f22009-04-03 22:50:24 +000081RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
Eli Friedman8aaff692009-12-08 02:09:46 +000082 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
Anders Carlsson2ee3c012009-10-03 19:43:08 +000083 return EmitCXXMemberPointerCallExpr(CE);
84
Eli Friedman8aaff692009-12-08 02:09:46 +000085 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
Anders Carlssone5fd6f22009-04-03 22:50:24 +000086 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000087
Anders Carlsson8f4fd602009-09-29 03:54:11 +000088 if (MD->isStatic()) {
89 // The method is static, emit it as we would a regular call.
90 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
91 return EmitCall(Callee, getContext().getPointerType(MD->getType()),
92 CE->arg_begin(), CE->arg_end(), 0);
93
94 }
95
John McCall9dd450b2009-09-21 23:43:11 +000096 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumpa523b2d2009-07-30 21:47:44 +000097
Mike Stump11289f42009-09-09 15:08:12 +000098 const llvm::Type *Ty =
99 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Anders Carlsson03a409f2009-04-08 20:31:57 +0000100 FPT->isVariadic());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000101 llvm::Value *This;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000103 if (ME->isArrow())
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000104 This = EmitScalarExpr(ME->getBase());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000105 else {
106 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000107 This = BaseLV.getAddress();
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000108 }
Mike Stumpa5588bf2009-08-26 20:46:33 +0000109
Eli Friedmanffc066f2009-11-26 07:45:48 +0000110 if (MD->isCopyAssignment() && MD->isTrivial()) {
111 // We don't like to generate the trivial copy assignment operator when
112 // it isn't necessary; just produce the proper effect here.
113 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
114 EmitAggregateCopy(This, RHS, CE->getType());
115 return RValue::get(This);
116 }
117
Douglas Gregorc1905232009-08-26 22:36:53 +0000118 // C++ [class.virtual]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000119 // Explicit qualification with the scope operator (5.1) suppresses the
Douglas Gregorc1905232009-08-26 22:36:53 +0000120 // virtual call mechanism.
Anders Carlssonb5296552009-10-11 23:55:52 +0000121 //
122 // We also don't emit a virtual call if the base expression has a record type
123 // because then we know what the type is.
Mike Stumpa5588bf2009-08-26 20:46:33 +0000124 llvm::Value *Callee;
Eli Friedmane6ce3542009-11-16 05:31:29 +0000125 if (const CXXDestructorDecl *Destructor
126 = dyn_cast<CXXDestructorDecl>(MD)) {
Eli Friedman84a7e342009-11-26 07:40:08 +0000127 if (Destructor->isTrivial())
128 return RValue::get(0);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000129 if (MD->isVirtual() && !ME->hasQualifier() &&
130 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
131 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
132 } else {
133 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
134 }
135 } else if (MD->isVirtual() && !ME->hasQualifier() &&
136 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
137 Callee = BuildVirtualCall(MD, This, Ty);
138 } else {
Anders Carlssonecf9bf02009-09-10 23:43:36 +0000139 Callee = CGM.GetAddrOfFunction(MD, Ty);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
142 return EmitCXXMemberCall(MD, Callee, This,
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000143 CE->arg_begin(), CE->arg_end());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000144}
Anders Carlssona5d077d2009-04-14 16:58:56 +0000145
Mike Stump11289f42009-09-09 15:08:12 +0000146RValue
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000147CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
Eli Friedman8aaff692009-12-08 02:09:46 +0000148 const BinaryOperator *BO =
149 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000150 const Expr *BaseExpr = BO->getLHS();
151 const Expr *MemFnExpr = BO->getRHS();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000152
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000153 const MemberPointerType *MPT =
154 MemFnExpr->getType()->getAs<MemberPointerType>();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000155 const FunctionProtoType *FPT =
156 MPT->getPointeeType()->getAs<FunctionProtoType>();
157 const CXXRecordDecl *RD =
Douglas Gregor615ac672009-11-04 16:49:01 +0000158 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000159
160 const llvm::FunctionType *FTy =
161 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
162 FPT->isVariadic());
163
164 const llvm::Type *Int8PtrTy =
165 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
166
167 // Get the member function pointer.
168 llvm::Value *MemFnPtr =
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000169 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
170 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171
172 // Emit the 'this' pointer.
173 llvm::Value *This;
174
175 if (BO->getOpcode() == BinaryOperator::PtrMemI)
176 This = EmitScalarExpr(BaseExpr);
177 else
178 This = EmitLValue(BaseExpr).getAddress();
179
180 // Adjust it.
181 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
182 Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
183
184 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
185 Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
186
187 This = Builder.CreateBitCast(Ptr, This->getType(), "this");
188
189 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
190
191 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
192
193 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
194
195 // If the LSB in the function pointer is 1, the function pointer points to
196 // a virtual function.
197 llvm::Value *IsVirtual
198 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
199 "and");
200
201 IsVirtual = Builder.CreateTrunc(IsVirtual,
202 llvm::Type::getInt1Ty(VMContext));
203
204 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
205 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
206 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
207
208 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
209 EmitBlock(FnVirtual);
210
211 const llvm::Type *VTableTy =
212 FTy->getPointerTo()->getPointerTo()->getPointerTo();
213
214 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
215 VTable = Builder.CreateLoad(VTable);
216
217 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
218
219 // Since the function pointer is 1 plus the virtual table offset, we
220 // subtract 1 by using a GEP.
Mike Stump0d479e62009-10-09 01:25:47 +0000221 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222
223 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
224
225 EmitBranch(FnEnd);
226 EmitBlock(FnNonVirtual);
227
228 // If the function is not virtual, just load the pointer.
229 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
230 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
231
232 EmitBlock(FnEnd);
233
234 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
235 Callee->reserveOperandSpace(2);
236 Callee->addIncoming(VirtualFn, FnVirtual);
237 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
238
239 CallArgList Args;
240
241 QualType ThisType =
242 getContext().getPointerType(getContext().getTagDeclType(RD));
243
244 // Push the this ptr.
245 Args.push_back(std::make_pair(RValue::get(This), ThisType));
246
247 // And the rest of the call args
248 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
249 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
250 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
251 Callee, Args, 0);
252}
253
254RValue
Anders Carlsson4034a952009-05-27 04:18:27 +0000255CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
256 const CXXMethodDecl *MD) {
Mike Stump11289f42009-09-09 15:08:12 +0000257 assert(MD->isInstance() &&
Anders Carlsson4034a952009-05-27 04:18:27 +0000258 "Trying to emit a member call expr on a static method!");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Fariborz Jahanian4985b332009-08-13 21:09:41 +0000260 if (MD->isCopyAssignment()) {
261 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
262 if (ClassDecl->hasTrivialCopyAssignment()) {
263 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
264 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
265 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
266 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
267 QualType Ty = E->getType();
268 EmitAggregateCopy(This, Src, Ty);
269 return RValue::get(This);
270 }
271 }
Mike Stump11289f42009-09-09 15:08:12 +0000272
John McCall9dd450b2009-09-21 23:43:11 +0000273 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000274 const llvm::Type *Ty =
275 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Mike Stump5a522352009-09-04 18:27:16 +0000276 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000277
Anders Carlsson4034a952009-05-27 04:18:27 +0000278 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
Mike Stump11289f42009-09-09 15:08:12 +0000279
Eli Friedmane6ce3542009-11-16 05:31:29 +0000280 llvm::Value *Callee;
281 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
282 Callee = BuildVirtualCall(MD, This, Ty);
283 else
284 Callee = CGM.GetAddrOfFunction(MD, Ty);
285
Anders Carlsson4034a952009-05-27 04:18:27 +0000286 return EmitCXXMemberCall(MD, Callee, This,
287 E->arg_begin() + 1, E->arg_end());
288}
289
Anders Carlssona5d077d2009-04-14 16:58:56 +0000290llvm::Value *CodeGenFunction::LoadCXXThis() {
Mike Stump11289f42009-09-09 15:08:12 +0000291 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
Anders Carlssona5d077d2009-04-14 16:58:56 +0000292 "Must be in a C++ member function decl to load 'this'");
293 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
294 "Must be in a C++ member function decl to load 'this'");
Mike Stump11289f42009-09-09 15:08:12 +0000295
Anders Carlssona5d077d2009-04-14 16:58:56 +0000296 // FIXME: What if we're inside a block?
Mike Stump18bb9282009-05-16 07:57:57 +0000297 // ans: See how CodeGenFunction::LoadObjCSelf() uses
298 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlssona5d077d2009-04-14 16:58:56 +0000299 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
300}
Anders Carlssonf7475242009-04-15 15:55:24 +0000301
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000302/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
303/// for-loop to call the default constructor on individual members of the
Anders Carlssond49844b2009-09-23 02:45:36 +0000304/// array.
305/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
306/// array type and 'ArrayPtr' points to the beginning fo the array.
307/// It is assumed that all relevant checks have been made by the caller.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000308void
309CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000310 const ConstantArrayType *ArrayTy,
311 llvm::Value *ArrayPtr,
312 CallExpr::const_arg_iterator ArgBeg,
313 CallExpr::const_arg_iterator ArgEnd) {
314
Anders Carlssond49844b2009-09-23 02:45:36 +0000315 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
316 llvm::Value * NumElements =
317 llvm::ConstantInt::get(SizeTy,
318 getContext().getConstantArrayElementCount(ArrayTy));
319
Anders Carlsson3a202f62009-11-24 18:43:52 +0000320 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
Anders Carlssond49844b2009-09-23 02:45:36 +0000321}
322
323void
324CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000325 llvm::Value *NumElements,
326 llvm::Value *ArrayPtr,
327 CallExpr::const_arg_iterator ArgBeg,
328 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssond49844b2009-09-23 02:45:36 +0000329 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000330
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000331 // Create a temporary for the loop index and initialize it with 0.
Anders Carlssond49844b2009-09-23 02:45:36 +0000332 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
333 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000334 Builder.CreateStore(Zero, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000336 // Start the loop with a block that tests the condition.
337 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
338 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000339
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000340 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000342 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000344 // Generate: if (loop-index < number-of-elements fall to the loop body,
345 // otherwise, go to the block after the for-loop.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000346 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000347 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000348 // If the condition is true, execute the body.
349 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000351 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000353 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000354 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniandd46eb72009-08-20 01:01:06 +0000355 Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000356 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
357 "arrayidx");
Mike Stump11289f42009-09-09 15:08:12 +0000358
Anders Carlsson3a202f62009-11-24 18:43:52 +0000359 // C++ [class.temporary]p4:
360 // There are two contexts in which temporaries are destroyed at a different
Mike Stump26004912009-12-10 00:05:14 +0000361 // point than the end of the full-expression. The first context is when a
Anders Carlsson3a202f62009-11-24 18:43:52 +0000362 // default constructor is called to initialize an element of an array.
363 // If the constructor has one or more default arguments, the destruction of
364 // every temporary created in a default argument expression is sequenced
365 // before the construction of the next array element, if any.
366
367 // Keep track of the current number of live temporaries.
368 unsigned OldNumLiveTemporaries = LiveTemporaries.size();
369
370 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
371
372 // Pop temporaries.
373 while (LiveTemporaries.size() > OldNumLiveTemporaries)
374 PopCXXTemporary();
375
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000376 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000378 // Emit the increment of the loop counter.
Anders Carlssond49844b2009-09-23 02:45:36 +0000379 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000380 Counter = Builder.CreateLoad(IndexPtr);
381 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000382 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000384 // Finally, branch back up to the condition for the next iteration.
385 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000387 // Emit the fall-through block.
388 EmitBlock(AfterFor, true);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000389}
390
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000391/// EmitCXXAggrDestructorCall - calls the default destructor on array
392/// elements in reverse order of construction.
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000393void
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000394CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
395 const ArrayType *Array,
396 llvm::Value *This) {
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000397 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
398 assert(CA && "Do we support VLA for destruction ?");
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000399 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Anders Carlsson21122cf2009-12-13 20:04:38 +0000400
401 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
402 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000403 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
404}
405
406/// EmitCXXAggrDestructorCall - calls the default destructor on array
407/// elements in reverse order of construction.
408void
409CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
410 llvm::Value *UpperCount,
411 llvm::Value *This) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000412 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
413 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
414
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000415 // Create a temporary for the loop index and initialize it with count of
416 // array elements.
Anders Carlsson21122cf2009-12-13 20:04:38 +0000417 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
418
419 // Store the number of elements in the index pointer.
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000420 Builder.CreateStore(UpperCount, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000422 // Start the loop with a block that tests the condition.
423 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
424 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000425
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000426 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000428 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000429
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000430 // Generate: if (loop-index != 0 fall to the loop body,
431 // otherwise, go to the block after the for-loop.
Mike Stump11289f42009-09-09 15:08:12 +0000432 llvm::Value* zeroConstant =
Anders Carlsson21122cf2009-12-13 20:04:38 +0000433 llvm::Constant::getNullValue(SizeLTy);
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000434 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
435 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
436 "isne");
437 // If the condition is true, execute the body.
438 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000440 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000442 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
443 // Inside the loop body, emit the constructor call on the array element.
444 Counter = Builder.CreateLoad(IndexPtr);
445 Counter = Builder.CreateSub(Counter, One);
446 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanianbe641492009-11-30 22:07:18 +0000447 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump11289f42009-09-09 15:08:12 +0000448
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000449 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000450
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000451 // Emit the decrement of the loop counter.
452 Counter = Builder.CreateLoad(IndexPtr);
453 Counter = Builder.CreateSub(Counter, One, "dec");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000454 Builder.CreateStore(Counter, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000456 // Finally, branch back up to the condition for the next iteration.
457 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000459 // Emit the fall-through block.
460 EmitBlock(AfterFor, true);
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000461}
462
Mike Stumpea950e22009-11-18 18:57:56 +0000463/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
464/// invoked, calls the default destructor on array elements in reverse order of
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000465/// construction.
466llvm::Constant *
467CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
468 const ArrayType *Array,
469 llvm::Value *This) {
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000470 FunctionArgList Args;
471 ImplicitParamDecl *Dst =
472 ImplicitParamDecl::Create(getContext(), 0,
473 SourceLocation(), 0,
474 getContext().getPointerType(getContext().VoidTy));
475 Args.push_back(std::make_pair(Dst, Dst->getType()));
476
477 llvm::SmallString<16> Name;
Eli Friedmand5bc94e2009-12-10 02:21:21 +0000478 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000479 QualType R = getContext().VoidTy;
480 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
481 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
482 llvm::Function *Fn =
483 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000484 Name.str(),
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000485 &CGM.getModule());
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000486 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000487 FunctionDecl *FD = FunctionDecl::Create(getContext(),
488 getContext().getTranslationUnitDecl(),
489 SourceLocation(), II, R, 0,
490 FunctionDecl::Static,
491 false, true);
492 StartFunction(FD, R, Fn, Args, SourceLocation());
493 QualType BaseElementTy = getContext().getBaseElementType(Array);
494 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
495 BasePtr = llvm::PointerType::getUnqual(BasePtr);
496 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
497 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
498 FinishFunction();
499 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
500 0);
501 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
502 return m;
503}
504
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000505void
Mike Stump11289f42009-09-09 15:08:12 +0000506CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
507 CXXCtorType Type,
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000508 llvm::Value *This,
509 CallExpr::const_arg_iterator ArgBeg,
510 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000511 if (D->isCopyConstructor(getContext())) {
512 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
513 if (ClassDecl->hasTrivialCopyConstructor()) {
514 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
515 "EmitCXXConstructorCall - user declared copy constructor");
516 const Expr *E = (*ArgBeg);
517 QualType Ty = E->getType();
518 llvm::Value *Src = EmitLValue(E).getAddress();
519 EmitAggregateCopy(This, Src, Ty);
520 return;
521 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000522 } else if (D->isTrivial()) {
523 // FIXME: Track down why we're trying to generate calls to the trivial
524 // default constructor!
525 return;
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000528 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
529
530 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000531}
532
Anders Carlssonce460522009-12-04 19:33:17 +0000533void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
Anders Carlsson0a637412009-05-29 21:03:38 +0000534 CXXDtorType Type,
535 llvm::Value *This) {
Anders Carlssonce460522009-12-04 19:33:17 +0000536 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
537
538 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Anders Carlssonce460522009-12-04 19:33:17 +0000540 // Push the this ptr.
541 Args.push_back(std::make_pair(RValue::get(This),
542 DD->getThisType(getContext())));
543
544 // Add a VTT parameter if necessary.
545 // FIXME: This should not be a dummy null parameter!
546 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
547 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
548
549 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
550 }
551
552 // FIXME: We should try to share this code with EmitCXXMemberCall.
553
554 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
555 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
Anders Carlsson0a637412009-05-29 21:03:38 +0000556}
557
Mike Stump11289f42009-09-09 15:08:12 +0000558void
559CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson1619a5042009-05-03 17:47:16 +0000560 const CXXConstructExpr *E) {
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000561 assert(Dest && "Must have a destination!");
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000562 const CXXConstructorDecl *CD = E->getConstructor();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000563 const ConstantArrayType *Array =
564 getContext().getAsConstantArrayType(E->getType());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000565 // For a copy constructor, even if it is trivial, must fall thru so
566 // its argument is code-gen'ed.
567 if (!CD->isCopyConstructor(getContext())) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000568 QualType InitType = E->getType();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000569 if (Array)
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000570 InitType = getContext().getBaseElementType(Array);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000571 const CXXRecordDecl *RD =
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000572 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000573 if (RD->hasTrivialConstructor())
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000574 return;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000577 // its first argument instead.
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000578 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000579 const Expr *Arg = E->getArg(0);
580
581 if (const CXXBindTemporaryExpr *BindExpr =
582 dyn_cast<CXXBindTemporaryExpr>(Arg))
583 Arg = BindExpr->getSubExpr();
584
585 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000586 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000587 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000588 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000589 QualType BaseElementTy = getContext().getBaseElementType(Array);
590 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
591 BasePtr = llvm::PointerType::getUnqual(BasePtr);
592 llvm::Value *BaseAddrPtr =
593 Builder.CreateBitCast(Dest, BasePtr);
Anders Carlsson3a202f62009-11-24 18:43:52 +0000594 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
595 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000596 }
597 else
598 // Call the constructor.
599 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
600 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000601}
602
Anders Carlssonf7475242009-04-15 15:55:24 +0000603void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000604 EmitGlobal(GlobalDecl(D, Ctor_Complete));
605 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000606}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000607
Mike Stump11289f42009-09-09 15:08:12 +0000608void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000609 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000610
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000611 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000612
Anders Carlsson73fcc952009-09-11 00:07:24 +0000613 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000615 SetFunctionDefinitionAttributes(D, Fn);
616 SetLLVMFunctionAttributesForDefinition(D, Fn);
617}
618
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000619llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000620CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000621 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000622 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000623 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000624 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000625 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000626
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000627 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000628 return cast<llvm::Function>(
629 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000630}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000631
Mike Stump11289f42009-09-09 15:08:12 +0000632const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000633 CXXCtorType Type) {
634 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000635 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000636
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000637 Name += '\0';
638 return UniqueMangledName(Name.begin(), Name.end());
639}
640
641void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000642 if (D->isVirtual())
Eli Friedman250534c2009-11-27 01:42:12 +0000643 EmitGlobalDefinition(GlobalDecl(D, Dtor_Deleting));
644 EmitGlobalDefinition(GlobalDecl(D, Dtor_Complete));
645 EmitGlobalDefinition(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000646}
647
Mike Stump11289f42009-09-09 15:08:12 +0000648void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000649 CXXDtorType Type) {
650 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000651
Anders Carlsson73fcc952009-09-11 00:07:24 +0000652 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000653
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000654 SetFunctionDefinitionAttributes(D, Fn);
655 SetLLVMFunctionAttributesForDefinition(D, Fn);
656}
657
658llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000659CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000660 CXXDtorType Type) {
661 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000662 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000663
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000664 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000665 return cast<llvm::Function>(
666 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000667}
668
Mike Stump11289f42009-09-09 15:08:12 +0000669const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000670 CXXDtorType Type) {
671 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000672 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000674 Name += '\0';
675 return UniqueMangledName(Name.begin(), Name.end());
676}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000677
Anders Carlssonc7785402009-11-26 02:32:05 +0000678llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000679CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000680 bool Extern,
681 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000682 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000683 CovariantThunkAdjustment(ThisAdjustment,
684 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000685}
686
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000687llvm::Value *
688CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
689 const ThunkAdjustment &Adjustment) {
690 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
691
Mike Stump77738202009-11-03 16:59:27 +0000692 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000693 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000694 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000695 V = Builder.CreateBitCast(V, Int8PtrTy);
696 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000697 V = Builder.CreateBitCast(V, OrigTy);
698 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000699
700 if (!Adjustment.Virtual)
701 return V;
702
703 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
704 "vtable entry unaligned");
705
706 // Do the virtual this adjustment
707 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
708 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
709
710 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
711 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
712 V = Builder.CreateLoad(V, "vtable");
713
714 llvm::Value *VTablePtr = V;
715 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
716 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
717 V = Builder.CreateLoad(V);
718 V = Builder.CreateGEP(ThisVal, V);
719
720 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000721}
722
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000723llvm::Constant *
724CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000725 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000726 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000727 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000728 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000729
730 FunctionArgList Args;
731 ImplicitParamDecl *ThisDecl =
732 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
733 MD->getThisType(getContext()));
734 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
735 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
736 e = MD->param_end();
737 i != e; ++i) {
738 ParmVarDecl *D = *i;
739 Args.push_back(std::make_pair(D, D->getType()));
740 }
741 IdentifierInfo *II
742 = &CGM.getContext().Idents.get("__thunk_named_foo_");
743 FunctionDecl *FD = FunctionDecl::Create(getContext(),
744 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000745 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000746 Extern
747 ? FunctionDecl::Extern
748 : FunctionDecl::Static,
749 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000750 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
751
752 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000753 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
754 const llvm::Type *Ty =
755 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
756 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000757 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000758
Mike Stump33ccd9e2009-11-02 23:22:01 +0000759 CallArgList CallArgs;
760
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000761 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000762 QualType ArgType = MD->getThisType(getContext());
763 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000764 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000765 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000766 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000767 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
768
769 if (!Adjustment.ReturnAdjustment.isEmpty()) {
770 const CovariantThunkAdjustment &ReturnAdjustment =
771 CovariantThunkAdjustment(ThunkAdjustment(),
772 Adjustment.ReturnAdjustment);
773
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000774 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000775
Mike Stump71609a22009-11-04 00:53:51 +0000776 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000777 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000778 }
779 }
780
Mike Stumpf3589722009-11-03 02:12:59 +0000781 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
782
Mike Stump33ccd9e2009-11-02 23:22:01 +0000783 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
784 e = MD->param_end();
785 i != e; ++i) {
786 ParmVarDecl *D = *i;
787 QualType ArgType = D->getType();
788
789 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000790 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
791 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000792 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
793 }
794
Mike Stump31e1d432009-11-02 23:47:45 +0000795 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
796 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000797 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000798 bool CanBeZero = !(ResultType->isReferenceType()
799 // FIXME: attr nonnull can't be zero either
800 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000801 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000802 if (CanBeZero) {
803 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
804 llvm::BasicBlock *ZeroBlock = createBasicBlock();
805 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000806
Mike Stumpc5507682009-11-05 06:32:02 +0000807 const llvm::Type *Ty = RV.getScalarVal()->getType();
808 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
809 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
810 NonZeroBlock, ZeroBlock);
811 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000812 llvm::Value *NZ =
813 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000814 EmitBranch(ContBlock);
815 EmitBlock(ZeroBlock);
816 llvm::Value *Z = RV.getScalarVal();
817 EmitBlock(ContBlock);
818 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
819 RVOrZero->reserveOperandSpace(2);
820 RVOrZero->addIncoming(NZ, NonZeroBlock);
821 RVOrZero->addIncoming(Z, ZeroBlock);
822 RV = RValue::get(RVOrZero);
823 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000824 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
825 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000826 }
827
Mike Stump31e1d432009-11-02 23:47:45 +0000828 if (!ResultType->isVoidType())
829 EmitReturnOfRValue(RV, ResultType);
830
Mike Stump80f6ac52009-09-11 23:25:56 +0000831 FinishFunction();
832 return Fn;
833}
834
Anders Carlssonc7785402009-11-26 02:32:05 +0000835llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000836CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
837 const ThunkAdjustment &ThisAdjustment) {
838 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
839
840 // Compute mangled name
841 llvm::SmallString<256> OutName;
842 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
843 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
844 OutName);
845 else
846 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
847 OutName += '\0';
848 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
849
850 // Get function for mangled name
851 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
852 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
853}
854
855llvm::Constant *
856CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
857 const CovariantThunkAdjustment &Adjustment) {
858 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
859
860 // Compute mangled name
861 llvm::SmallString<256> OutName;
862 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
863 OutName += '\0';
864 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
865
866 // Get function for mangled name
867 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
868 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
869}
870
871void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000872 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
873 if (!AdjPtr)
874 return;
875 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000876 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000877 for (unsigned i = 0; i < Adj.size(); i++) {
878 GlobalDecl OGD = Adj[i].first;
879 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000880 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
881 CanQualType oret = getContext().getCanonicalType(nc_oret);
882 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
883 CanQualType ret = getContext().getCanonicalType(nc_ret);
884 ThunkAdjustment ReturnAdjustment;
885 if (oret != ret) {
886 QualType qD = nc_ret->getPointeeType();
887 QualType qB = nc_oret->getPointeeType();
888 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
889 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
890 ReturnAdjustment = ComputeThunkAdjustment(D, B);
891 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000892 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000893 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
894 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
895 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
896 llvm::Constant *FnConst;
897 if (!ReturnAdjustment.isEmpty())
898 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
899 else
900 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
901 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000902 llvm::Constant *SubExpr =
903 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
904 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
905 std::string Name = OldFn->getNameStr();
906 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
907 Name.data() + Name.size() + 1));
908 llvm::Constant *NewFnConst;
909 if (!ReturnAdjustment.isEmpty())
910 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
911 else
912 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
913 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
914 NewFn->takeName(OldFn);
915 llvm::Constant *NewPtrForOldDecl =
916 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
917 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
918 OldFn->eraseFromParent();
919 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000920 }
921 llvm::Function *Fn = cast<llvm::Function>(FnConst);
922 if (Fn->isDeclaration()) {
923 llvm::GlobalVariable::LinkageTypes linktype;
924 linktype = llvm::GlobalValue::WeakAnyLinkage;
925 if (!Extern)
926 linktype = llvm::GlobalValue::InternalLinkage;
927 Fn->setLinkage(linktype);
928 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
929 Fn->addFnAttr(llvm::Attribute::NoUnwind);
930 Fn->setAlignment(2);
931 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
932 }
933 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000934 }
935}
936
937llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000938CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000939 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000940 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000941 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000942 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
943 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
944 OutName);
945 } else
946 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000947
Mike Stump5a522352009-09-04 18:27:16 +0000948 llvm::GlobalVariable::LinkageTypes linktype;
949 linktype = llvm::GlobalValue::WeakAnyLinkage;
950 if (!Extern)
951 linktype = llvm::GlobalValue::InternalLinkage;
952 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000953 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000954 const llvm::FunctionType *FTy =
955 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
956 FPT->isVariadic());
957
Daniel Dunbare128dd12009-11-21 09:06:22 +0000958 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000959 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000960 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000961 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
962 return m;
963}
964
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000965llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000966CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000967 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000968 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000969 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000970 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000971 llvm::GlobalVariable::LinkageTypes linktype;
972 linktype = llvm::GlobalValue::WeakAnyLinkage;
973 if (!Extern)
974 linktype = llvm::GlobalValue::InternalLinkage;
975 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000976 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000977 const llvm::FunctionType *FTy =
978 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
979 FPT->isVariadic());
980
Daniel Dunbare128dd12009-11-21 09:06:22 +0000981 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000982 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000983 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000984 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
985 return m;
986}
987
Mike Stumpa5588bf2009-08-26 20:46:33 +0000988llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000989CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
990 const CXXRecordDecl *ClassDecl,
991 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000992 const llvm::Type *Int8PtrTy =
993 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
994
995 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
996 Int8PtrTy->getPointerTo());
997 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
998
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000999 int64_t VBaseOffsetIndex =
1000 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1001
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001002 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001003 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001004 const llvm::Type *PtrDiffTy =
1005 ConvertType(getContext().getPointerDiffType());
1006
1007 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1008 PtrDiffTy->getPointerTo());
1009
1010 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1011
1012 return VBaseOffset;
1013}
1014
Anders Carlssonf942ee02009-11-27 20:47:55 +00001015static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001016 llvm::Value *This, const llvm::Type *Ty) {
1017 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001018
Anders Carlssone828c362009-11-13 04:45:41 +00001019 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1020 Vtable = CGF.Builder.CreateLoad(Vtable);
1021
1022 llvm::Value *VFuncPtr =
1023 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1024 return CGF.Builder.CreateLoad(VFuncPtr);
1025}
1026
1027llvm::Value *
1028CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1029 const llvm::Type *Ty) {
1030 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001031 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001032
1033 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1034}
1035
1036llvm::Value *
1037CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1038 llvm::Value *&This, const llvm::Type *Ty) {
1039 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001040 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001041 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001042
1043 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001044}
1045
Fariborz Jahanian56263842009-08-21 18:30:26 +00001046/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1047/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1048/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001049// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001050void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001051 llvm::Value *Src,
1052 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001053 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001054 QualType Ty) {
1055 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1056 assert(CA && "VLA cannot be copied over");
1057 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001058
Fariborz Jahanian56263842009-08-21 18:30:26 +00001059 // Create a temporary for the loop index and initialize it with 0.
1060 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1061 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001062 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001063 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001064 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001065 // Start the loop with a block that tests the condition.
1066 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1067 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001068
Fariborz Jahanian56263842009-08-21 18:30:26 +00001069 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001070
Fariborz Jahanian56263842009-08-21 18:30:26 +00001071 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1072 // Generate: if (loop-index < number-of-elements fall to the loop body,
1073 // otherwise, go to the block after the for-loop.
1074 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001075 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001076 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1077 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001078 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001079 "isless");
1080 // If the condition is true, execute the body.
1081 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001082
Fariborz Jahanian56263842009-08-21 18:30:26 +00001083 EmitBlock(ForBody);
1084 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1085 // Inside the loop body, emit the constructor call on the array element.
1086 Counter = Builder.CreateLoad(IndexPtr);
1087 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1088 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1089 if (BitwiseCopy)
1090 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001091 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001092 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001093 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001094 Ctor_Complete);
1095 CallArgList CallArgs;
1096 // Push the this (Dest) ptr.
1097 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1098 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001099
Fariborz Jahanian56263842009-08-21 18:30:26 +00001100 // Push the Src ptr.
1101 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001102 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001103 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001104 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001105 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1106 Callee, CallArgs, BaseCopyCtor);
1107 }
1108 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001109
Fariborz Jahanian56263842009-08-21 18:30:26 +00001110 // Emit the increment of the loop counter.
1111 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1112 Counter = Builder.CreateLoad(IndexPtr);
1113 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001114 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001115
Fariborz Jahanian56263842009-08-21 18:30:26 +00001116 // Finally, branch back up to the condition for the next iteration.
1117 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Fariborz Jahanian56263842009-08-21 18:30:26 +00001119 // Emit the fall-through block.
1120 EmitBlock(AfterFor, true);
1121}
1122
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001123/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001124/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001125/// bitwise assignment or via a copy assignment operator function call.
1126/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001127void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001128 llvm::Value *Src,
1129 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001130 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001131 QualType Ty) {
1132 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1133 assert(CA && "VLA cannot be asssigned");
1134 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001135
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001136 // Create a temporary for the loop index and initialize it with 0.
1137 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1138 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001139 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001140 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001141 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001142 // Start the loop with a block that tests the condition.
1143 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1144 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001145
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001146 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001147
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001148 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1149 // Generate: if (loop-index < number-of-elements fall to the loop body,
1150 // otherwise, go to the block after the for-loop.
1151 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001152 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001153 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1154 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001155 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001156 "isless");
1157 // If the condition is true, execute the body.
1158 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001159
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001160 EmitBlock(ForBody);
1161 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1162 // Inside the loop body, emit the assignment operator call on array element.
1163 Counter = Builder.CreateLoad(IndexPtr);
1164 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1165 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1166 const CXXMethodDecl *MD = 0;
1167 if (BitwiseAssign)
1168 EmitAggregateCopy(Dest, Src, Ty);
1169 else {
1170 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1171 MD);
1172 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1173 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001174 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001175 const llvm::Type *LTy =
1176 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1177 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001178 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001179
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001180 CallArgList CallArgs;
1181 // Push the this (Dest) ptr.
1182 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1183 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001184
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001185 // Push the Src ptr.
1186 CallArgs.push_back(std::make_pair(RValue::get(Src),
1187 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001188 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001189 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1190 Callee, CallArgs, MD);
1191 }
1192 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001193
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001194 // Emit the increment of the loop counter.
1195 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1196 Counter = Builder.CreateLoad(IndexPtr);
1197 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001198 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001199
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001200 // Finally, branch back up to the condition for the next iteration.
1201 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001202
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001203 // Emit the fall-through block.
1204 EmitBlock(AfterFor, true);
1205}
1206
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001207/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1208/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001209/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001210void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001211 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001212 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001213 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1214 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001215 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1216 /*NullCheckValue=*/false);
1217 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1218 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001219 }
1220 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1221 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001222 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
1225 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001226 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001227 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001228 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001229 CallArgList CallArgs;
1230 // Push the this (Dest) ptr.
1231 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1232 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001233
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001234 // Push the Src ptr.
1235 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001236 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001237 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001238 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001239 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1240 Callee, CallArgs, BaseCopyCtor);
1241 }
1242}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001243
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001244/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001245/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001246/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001247// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001248void CodeGenFunction::EmitClassCopyAssignment(
1249 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001250 const CXXRecordDecl *ClassDecl,
1251 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001252 QualType Ty) {
1253 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001254 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1255 /*NullCheckValue=*/false);
1256 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1257 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001258 }
1259 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1260 EmitAggregateCopy(Dest, Src, Ty);
1261 return;
1262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001264 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001265 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001266 MD);
1267 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1268 (void)ConstCopyAssignOp;
1269
John McCall9dd450b2009-09-21 23:43:11 +00001270 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001271 const llvm::Type *LTy =
1272 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001273 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001274 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001276 CallArgList CallArgs;
1277 // Push the this (Dest) ptr.
1278 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1279 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001280
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001281 // Push the Src ptr.
1282 CallArgs.push_back(std::make_pair(RValue::get(Src),
1283 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001284 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001285 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001286 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1287 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001288}
1289
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001290/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001291void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001292CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1293 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001294 llvm::Function *Fn,
1295 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001296 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001297 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1298 SourceLocation());
1299 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001300 FinishFunction();
1301}
1302
Mike Stumpb9c9b352009-11-04 01:11:15 +00001303/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1304/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001305/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001306/// copy of its subobjects. The order of copying is the same as the order of
1307/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001308/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001309/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001310/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001311/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001312/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001313/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001314/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001315/// Virtual base class subobjects shall be copied only once by the
1316/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001317
Anders Carlssonddf57d32009-09-14 05:32:02 +00001318void
1319CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1320 CXXCtorType Type,
1321 llvm::Function *Fn,
1322 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001323 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001324 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001325 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001326 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001327 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1328 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001329
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001330 FunctionArgList::const_iterator i = Args.begin();
1331 const VarDecl *ThisArg = i->first;
1332 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1333 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1334 const VarDecl *SrcArg = (i+1)->first;
1335 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1336 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001337
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001338 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1339 Base != ClassDecl->bases_end(); ++Base) {
1340 // FIXME. copy constrution of virtual base NYI
1341 if (Base->isVirtual())
1342 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001344 CXXRecordDecl *BaseClassDecl
1345 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001346 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1347 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001350 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1351 E = ClassDecl->field_end(); I != E; ++I) {
1352 const FieldDecl *Field = *I;
1353
1354 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001355 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001356 getContext().getAsConstantArrayType(FieldType);
1357 if (Array)
1358 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001359
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001360 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1361 CXXRecordDecl *FieldClassDecl
1362 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001363 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1364 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001365 if (Array) {
1366 const llvm::Type *BasePtr = ConvertType(FieldType);
1367 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001368 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001369 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001370 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001371 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1372 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1373 FieldClassDecl, FieldType);
1374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375 else
1376 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001377 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001378 continue;
1379 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001380
1381 if (Field->getType()->isReferenceType()) {
1382 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1383
1384 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1385 "lhs.ref");
1386
1387 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1388 "rhs.ref");
1389
1390 // Load the value in RHS.
1391 RHS = Builder.CreateLoad(RHS);
1392
1393 // And store it in the LHS
1394 Builder.CreateStore(RHS, LHS);
1395
1396 continue;
1397 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001398 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001399 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1400 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1401
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001402 if (!hasAggregateLLVMType(Field->getType())) {
1403 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1404 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1405 } else if (Field->getType()->isAnyComplexType()) {
1406 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1407 RHS.isVolatileQualified());
1408 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1409 } else {
1410 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1411 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001412 }
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001413
1414 InitializeVtablePtrs(ClassDecl);
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001415 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001416}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001417
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001418/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001419/// Before the implicitly-declared copy assignment operator for a class is
1420/// implicitly defined, all implicitly- declared copy assignment operators for
1421/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001422/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001423/// The implicitly-defined copy assignment operator for class X performs
1424/// memberwise assignment of its subob- jects. The direct base classes of X are
1425/// assigned first, in the order of their declaration in
1426/// the base-specifier-list, and then the immediate nonstatic data members of X
1427/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001428/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001429/// if the subobject is of class type, the copy assignment operator for the
1430/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001431/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001432///
Mike Stump11289f42009-09-09 15:08:12 +00001433/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001434/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001435///
Mike Stump11289f42009-09-09 15:08:12 +00001436/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001437/// used.
1438void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001439 llvm::Function *Fn,
1440 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001441
1442 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1443 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1444 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001445 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001446
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001447 FunctionArgList::const_iterator i = Args.begin();
1448 const VarDecl *ThisArg = i->first;
1449 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1450 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1451 const VarDecl *SrcArg = (i+1)->first;
1452 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1453 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001455 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1456 Base != ClassDecl->bases_end(); ++Base) {
1457 // FIXME. copy assignment of virtual base NYI
1458 if (Base->isVirtual())
1459 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001461 CXXRecordDecl *BaseClassDecl
1462 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1463 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1464 Base->getType());
1465 }
Mike Stump11289f42009-09-09 15:08:12 +00001466
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001467 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1468 FieldEnd = ClassDecl->field_end();
1469 Field != FieldEnd; ++Field) {
1470 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001471 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001472 getContext().getAsConstantArrayType(FieldType);
1473 if (Array)
1474 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001476 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1477 CXXRecordDecl *FieldClassDecl
1478 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1479 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1480 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001481 if (Array) {
1482 const llvm::Type *BasePtr = ConvertType(FieldType);
1483 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1484 llvm::Value *DestBaseAddrPtr =
1485 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1486 llvm::Value *SrcBaseAddrPtr =
1487 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1488 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1489 FieldClassDecl, FieldType);
1490 }
1491 else
Mike Stump11289f42009-09-09 15:08:12 +00001492 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001493 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001494 continue;
1495 }
1496 // Do a built-in assignment of scalar data members.
1497 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1498 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001499 if (!hasAggregateLLVMType(Field->getType())) {
1500 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1501 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1502 } else if (Field->getType()->isAnyComplexType()) {
1503 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1504 RHS.isVolatileQualified());
1505 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1506 } else {
1507 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1508 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001511 // return *this;
1512 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001513
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001514 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001515}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001516
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001517static void EmitBaseInitializer(CodeGenFunction &CGF,
1518 const CXXRecordDecl *ClassDecl,
1519 CXXBaseOrMemberInitializer *BaseInit,
1520 CXXCtorType CtorType) {
1521 assert(BaseInit->isBaseInitializer() &&
1522 "Must have base initializer!");
1523
1524 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1525
1526 const Type *BaseType = BaseInit->getBaseClass();
1527 CXXRecordDecl *BaseClassDecl =
1528 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Anders Carlsson8c793172009-11-23 17:57:54 +00001529 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1530 BaseClassDecl,
1531 /*NullCheckValue=*/false);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001532 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1533 CtorType, V,
1534 BaseInit->const_arg_begin(),
1535 BaseInit->const_arg_end());
1536}
1537
1538static void EmitMemberInitializer(CodeGenFunction &CGF,
1539 const CXXRecordDecl *ClassDecl,
1540 CXXBaseOrMemberInitializer *MemberInit) {
1541 assert(MemberInit->isMemberInitializer() &&
1542 "Must have member initializer!");
1543
1544 // non-static data member initializers.
1545 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001546 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001547
1548 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1549 LValue LHS;
1550 if (FieldType->isReferenceType()) {
1551 // FIXME: This is really ugly; should be refactored somehow
1552 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1553 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1554 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1555 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1556 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001557 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001558 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001559
1560 // If we are initializing an anonymous union field, drill down to the field.
1561 if (MemberInit->getAnonUnionMember()) {
1562 Field = MemberInit->getAnonUnionMember();
1563 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1564 /*IsUnion=*/true, 0);
1565 FieldType = Field->getType();
1566 }
1567
1568 // If the field is an array, branch based on the element type.
1569 const ConstantArrayType *Array =
1570 CGF.getContext().getAsConstantArrayType(FieldType);
1571 if (Array)
1572 FieldType = CGF.getContext().getBaseElementType(FieldType);
1573
Eli Friedmane85ef712009-11-16 23:53:01 +00001574 // We lose the constructor for anonymous union members, so handle them
1575 // explicitly.
1576 // FIXME: This is somwhat ugly.
1577 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1578 if (MemberInit->getNumArgs())
1579 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1580 LHS.isVolatileQualified());
1581 else
1582 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1583 return;
1584 }
1585
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001586 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001587 assert(MemberInit->getConstructor() &&
1588 "EmitCtorPrologue - no constructor to initialize member");
1589 if (Array) {
1590 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1591 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1592 llvm::Value *BaseAddrPtr =
1593 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1594 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001595 Array, BaseAddrPtr,
1596 MemberInit->const_arg_begin(),
1597 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001598 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001599 else
1600 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1601 Ctor_Complete, LHS.getAddress(),
1602 MemberInit->const_arg_begin(),
1603 MemberInit->const_arg_end());
1604 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001605 }
1606
1607 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1608 Expr *RhsExpr = *MemberInit->arg_begin();
1609 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001610 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001611 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1612 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001613 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001614 } else if (Array) {
1615 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1616 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1617 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1618 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1619 } else if (RhsExpr->getType()->isAnyComplexType()) {
1620 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1621 LHS.isVolatileQualified());
1622 } else {
1623 // Handle member function pointers; other aggregates shouldn't get this far.
1624 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1625 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001626}
1627
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001628/// EmitCtorPrologue - This routine generates necessary code to initialize
1629/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001630/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001631void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1632 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001633 const CXXRecordDecl *ClassDecl = CD->getParent();
1634
Mike Stump6b2556f2009-08-06 13:41:24 +00001635 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001636
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001637 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001638 E = CD->init_end();
1639 B != E; ++B) {
1640 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001641
Anders Carlsson5852b132009-11-06 04:11:09 +00001642 assert(LiveTemporaries.empty() &&
1643 "Should not have any live temporaries at initializer start!");
1644
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001645 if (Member->isBaseInitializer())
1646 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1647 else
1648 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001649
1650 // Pop any live temporaries that the initializers might have pushed.
1651 while (!LiveTemporaries.empty())
1652 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001653 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001654
Eli Friedman80888c72009-12-08 06:54:20 +00001655 InitializeVtablePtrs(ClassDecl);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001656}
1657
1658void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001659 if (!ClassDecl->isDynamicClass())
1660 return;
1661
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001662 // Initialize the vtable pointer.
1663 // FIXME: This needs to initialize secondary vtable pointers too.
1664 llvm::Value *ThisPtr = LoadCXXThis();
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001665
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001666 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1667 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1668
1669 llvm::Value *VtableAddressPoint =
1670 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1671
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001672 llvm::Value *VtableField =
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001673 Builder.CreateBitCast(ThisPtr,
1674 VtableAddressPoint->getType()->getPointerTo());
1675
1676 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001677}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001678
1679/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001680/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001681/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001682/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001683void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1684 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001685 assert(!DD->isTrivial() &&
1686 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001687
Anders Carlssondee9a302009-11-17 04:44:12 +00001688 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001689
Anders Carlssondee9a302009-11-17 04:44:12 +00001690 // Collect the fields.
1691 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1692 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1693 E = ClassDecl->field_end(); I != E; ++I) {
1694 const FieldDecl *Field = *I;
1695
1696 QualType FieldType = getContext().getCanonicalType(Field->getType());
1697 FieldType = getContext().getBaseElementType(FieldType);
1698
1699 const RecordType *RT = FieldType->getAs<RecordType>();
1700 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001701 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001702
1703 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1704 if (FieldClassDecl->hasTrivialDestructor())
1705 continue;
1706
1707 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001708 }
Anders Carlssond7872042009-11-15 23:03:25 +00001709
Anders Carlssondee9a302009-11-17 04:44:12 +00001710 // Now destroy the fields.
1711 for (size_t i = FieldDecls.size(); i > 0; --i) {
1712 const FieldDecl *Field = FieldDecls[i - 1];
1713
1714 QualType FieldType = Field->getType();
1715 const ConstantArrayType *Array =
1716 getContext().getAsConstantArrayType(FieldType);
1717 if (Array)
1718 FieldType = getContext().getBaseElementType(FieldType);
1719
1720 const RecordType *RT = FieldType->getAs<RecordType>();
1721 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1722
1723 llvm::Value *ThisPtr = LoadCXXThis();
1724
1725 LValue LHS = EmitLValueForField(ThisPtr, Field,
1726 /*isUnion=*/false,
1727 // FIXME: Qualifiers?
1728 /*CVRQualifiers=*/0);
1729 if (Array) {
1730 const llvm::Type *BasePtr = ConvertType(FieldType);
1731 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1732 llvm::Value *BaseAddrPtr =
1733 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1734 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1735 Array, BaseAddrPtr);
1736 } else
1737 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1738 Dtor_Complete, LHS.getAddress());
1739 }
1740
1741 // Destroy non-virtual bases.
1742 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1743 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1744 const CXXBaseSpecifier &Base = *I;
1745
1746 // Ignore virtual bases.
1747 if (Base.isVirtual())
1748 continue;
1749
1750 CXXRecordDecl *BaseClassDecl
1751 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1752
1753 // Ignore trivial destructors.
1754 if (BaseClassDecl->hasTrivialDestructor())
1755 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001756 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1757
Anders Carlsson8c793172009-11-23 17:57:54 +00001758 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1759 ClassDecl, BaseClassDecl,
1760 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001761 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001762 }
1763
1764 // If we're emitting a base destructor, we don't want to emit calls to the
1765 // virtual bases.
1766 if (DtorType == Dtor_Base)
1767 return;
1768
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001769 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001770 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1771 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001772 const CXXBaseSpecifier &Base = *I;
1773 CXXRecordDecl *BaseClassDecl
1774 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1775
1776 // Ignore trivial destructors.
1777 if (BaseClassDecl->hasTrivialDestructor())
1778 continue;
1779 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1780 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1781 ClassDecl, BaseClassDecl,
1782 /*NullCheckValue=*/false);
1783 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001784 }
1785
1786 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001787 if (DtorType == Dtor_Deleting) {
1788 assert(DD->getOperatorDelete() &&
1789 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001790 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1791 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001792 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001793}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001794
Anders Carlssonddf57d32009-09-14 05:32:02 +00001795void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1796 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001797 llvm::Function *Fn,
1798 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001799 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001800 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001801
Anders Carlssonddf57d32009-09-14 05:32:02 +00001802 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1803 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001804
Anders Carlssonddf57d32009-09-14 05:32:02 +00001805 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001806 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001807}