blob: 24e3ffda82d066d51735fa01c7007b00a03a1c50 [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);
400 llvm::Value* ElementCountPtr =
401 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
402 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
403}
404
405/// EmitCXXAggrDestructorCall - calls the default destructor on array
406/// elements in reverse order of construction.
407void
408CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
409 llvm::Value *UpperCount,
410 llvm::Value *This) {
Mike Stump11289f42009-09-09 15:08:12 +0000411 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000412 1);
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000413 // Create a temporary for the loop index and initialize it with count of
414 // array elements.
415 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
416 "loop.index");
417 // Index = ElementCount;
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000418 Builder.CreateStore(UpperCount, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000420 // Start the loop with a block that tests the condition.
421 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
422 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000423
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000424 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000426 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000427
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000428 // Generate: if (loop-index != 0 fall to the loop body,
429 // otherwise, go to the block after the for-loop.
Mike Stump11289f42009-09-09 15:08:12 +0000430 llvm::Value* zeroConstant =
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000431 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
432 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
433 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
434 "isne");
435 // If the condition is true, execute the body.
436 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000437
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000438 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000440 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
441 // Inside the loop body, emit the constructor call on the array element.
442 Counter = Builder.CreateLoad(IndexPtr);
443 Counter = Builder.CreateSub(Counter, One);
444 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanianbe641492009-11-30 22:07:18 +0000445 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump11289f42009-09-09 15:08:12 +0000446
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000447 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000448
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000449 // Emit the decrement of the loop counter.
450 Counter = Builder.CreateLoad(IndexPtr);
451 Counter = Builder.CreateSub(Counter, One, "dec");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000452 Builder.CreateStore(Counter, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000453
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000454 // Finally, branch back up to the condition for the next iteration.
455 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000456
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000457 // Emit the fall-through block.
458 EmitBlock(AfterFor, true);
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000459}
460
Mike Stumpea950e22009-11-18 18:57:56 +0000461/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
462/// invoked, calls the default destructor on array elements in reverse order of
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000463/// construction.
464llvm::Constant *
465CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
466 const ArrayType *Array,
467 llvm::Value *This) {
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000468 FunctionArgList Args;
469 ImplicitParamDecl *Dst =
470 ImplicitParamDecl::Create(getContext(), 0,
471 SourceLocation(), 0,
472 getContext().getPointerType(getContext().VoidTy));
473 Args.push_back(std::make_pair(Dst, Dst->getType()));
474
475 llvm::SmallString<16> Name;
Eli Friedmand5bc94e2009-12-10 02:21:21 +0000476 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000477 QualType R = getContext().VoidTy;
478 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
479 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
480 llvm::Function *Fn =
481 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000482 Name.str(),
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000483 &CGM.getModule());
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000484 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000485 FunctionDecl *FD = FunctionDecl::Create(getContext(),
486 getContext().getTranslationUnitDecl(),
487 SourceLocation(), II, R, 0,
488 FunctionDecl::Static,
489 false, true);
490 StartFunction(FD, R, Fn, Args, SourceLocation());
491 QualType BaseElementTy = getContext().getBaseElementType(Array);
492 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
493 BasePtr = llvm::PointerType::getUnqual(BasePtr);
494 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
495 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
496 FinishFunction();
497 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
498 0);
499 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
500 return m;
501}
502
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000503void
Mike Stump11289f42009-09-09 15:08:12 +0000504CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
505 CXXCtorType Type,
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000506 llvm::Value *This,
507 CallExpr::const_arg_iterator ArgBeg,
508 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000509 if (D->isCopyConstructor(getContext())) {
510 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
511 if (ClassDecl->hasTrivialCopyConstructor()) {
512 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
513 "EmitCXXConstructorCall - user declared copy constructor");
514 const Expr *E = (*ArgBeg);
515 QualType Ty = E->getType();
516 llvm::Value *Src = EmitLValue(E).getAddress();
517 EmitAggregateCopy(This, Src, Ty);
518 return;
519 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000520 } else if (D->isTrivial()) {
521 // FIXME: Track down why we're trying to generate calls to the trivial
522 // default constructor!
523 return;
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000526 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
527
528 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000529}
530
Anders Carlssonce460522009-12-04 19:33:17 +0000531void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
Anders Carlsson0a637412009-05-29 21:03:38 +0000532 CXXDtorType Type,
533 llvm::Value *This) {
Anders Carlssonce460522009-12-04 19:33:17 +0000534 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
535
536 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Anders Carlssonce460522009-12-04 19:33:17 +0000538 // Push the this ptr.
539 Args.push_back(std::make_pair(RValue::get(This),
540 DD->getThisType(getContext())));
541
542 // Add a VTT parameter if necessary.
543 // FIXME: This should not be a dummy null parameter!
544 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
545 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
546
547 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
548 }
549
550 // FIXME: We should try to share this code with EmitCXXMemberCall.
551
552 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
553 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
Anders Carlsson0a637412009-05-29 21:03:38 +0000554}
555
Mike Stump11289f42009-09-09 15:08:12 +0000556void
557CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson1619a5042009-05-03 17:47:16 +0000558 const CXXConstructExpr *E) {
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000559 assert(Dest && "Must have a destination!");
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000560 const CXXConstructorDecl *CD = E->getConstructor();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000561 const ConstantArrayType *Array =
562 getContext().getAsConstantArrayType(E->getType());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000563 // For a copy constructor, even if it is trivial, must fall thru so
564 // its argument is code-gen'ed.
565 if (!CD->isCopyConstructor(getContext())) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000566 QualType InitType = E->getType();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000567 if (Array)
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000568 InitType = getContext().getBaseElementType(Array);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000569 const CXXRecordDecl *RD =
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000570 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000571 if (RD->hasTrivialConstructor())
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000572 return;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000575 // its first argument instead.
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000576 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000577 const Expr *Arg = E->getArg(0);
578
579 if (const CXXBindTemporaryExpr *BindExpr =
580 dyn_cast<CXXBindTemporaryExpr>(Arg))
581 Arg = BindExpr->getSubExpr();
582
583 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000584 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000585 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000586 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000587 QualType BaseElementTy = getContext().getBaseElementType(Array);
588 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
589 BasePtr = llvm::PointerType::getUnqual(BasePtr);
590 llvm::Value *BaseAddrPtr =
591 Builder.CreateBitCast(Dest, BasePtr);
Anders Carlsson3a202f62009-11-24 18:43:52 +0000592 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
593 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000594 }
595 else
596 // Call the constructor.
597 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
598 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000599}
600
Anders Carlssonf7475242009-04-15 15:55:24 +0000601void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000602 EmitGlobal(GlobalDecl(D, Ctor_Complete));
603 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000604}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000605
Mike Stump11289f42009-09-09 15:08:12 +0000606void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000607 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000608
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000609 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000610
Anders Carlsson73fcc952009-09-11 00:07:24 +0000611 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000612
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000613 SetFunctionDefinitionAttributes(D, Fn);
614 SetLLVMFunctionAttributesForDefinition(D, Fn);
615}
616
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000617llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000618CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000619 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000620 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000621 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000622 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000623 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000624
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000625 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000626 return cast<llvm::Function>(
627 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000628}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000629
Mike Stump11289f42009-09-09 15:08:12 +0000630const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000631 CXXCtorType Type) {
632 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000633 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000634
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000635 Name += '\0';
636 return UniqueMangledName(Name.begin(), Name.end());
637}
638
639void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000640 if (D->isVirtual())
Eli Friedman250534c2009-11-27 01:42:12 +0000641 EmitGlobalDefinition(GlobalDecl(D, Dtor_Deleting));
642 EmitGlobalDefinition(GlobalDecl(D, Dtor_Complete));
643 EmitGlobalDefinition(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000644}
645
Mike Stump11289f42009-09-09 15:08:12 +0000646void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000647 CXXDtorType Type) {
648 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000649
Anders Carlsson73fcc952009-09-11 00:07:24 +0000650 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000651
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000652 SetFunctionDefinitionAttributes(D, Fn);
653 SetLLVMFunctionAttributesForDefinition(D, Fn);
654}
655
656llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000657CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000658 CXXDtorType Type) {
659 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000660 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000662 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000663 return cast<llvm::Function>(
664 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000665}
666
Mike Stump11289f42009-09-09 15:08:12 +0000667const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000668 CXXDtorType Type) {
669 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000670 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000671
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000672 Name += '\0';
673 return UniqueMangledName(Name.begin(), Name.end());
674}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000675
Anders Carlssonc7785402009-11-26 02:32:05 +0000676llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000677CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000678 bool Extern,
679 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000680 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000681 CovariantThunkAdjustment(ThisAdjustment,
682 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000683}
684
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000685llvm::Value *
686CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
687 const ThunkAdjustment &Adjustment) {
688 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
689
Mike Stump77738202009-11-03 16:59:27 +0000690 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000691 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000692 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000693 V = Builder.CreateBitCast(V, Int8PtrTy);
694 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000695 V = Builder.CreateBitCast(V, OrigTy);
696 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000697
698 if (!Adjustment.Virtual)
699 return V;
700
701 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
702 "vtable entry unaligned");
703
704 // Do the virtual this adjustment
705 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
706 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
707
708 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
709 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
710 V = Builder.CreateLoad(V, "vtable");
711
712 llvm::Value *VTablePtr = V;
713 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
714 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
715 V = Builder.CreateLoad(V);
716 V = Builder.CreateGEP(ThisVal, V);
717
718 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000719}
720
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000721llvm::Constant *
722CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000723 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000724 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000725 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000726 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000727
728 FunctionArgList Args;
729 ImplicitParamDecl *ThisDecl =
730 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
731 MD->getThisType(getContext()));
732 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
733 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
734 e = MD->param_end();
735 i != e; ++i) {
736 ParmVarDecl *D = *i;
737 Args.push_back(std::make_pair(D, D->getType()));
738 }
739 IdentifierInfo *II
740 = &CGM.getContext().Idents.get("__thunk_named_foo_");
741 FunctionDecl *FD = FunctionDecl::Create(getContext(),
742 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000743 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000744 Extern
745 ? FunctionDecl::Extern
746 : FunctionDecl::Static,
747 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000748 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
749
750 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000751 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
752 const llvm::Type *Ty =
753 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
754 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000755 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000756
Mike Stump33ccd9e2009-11-02 23:22:01 +0000757 CallArgList CallArgs;
758
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000759 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000760 QualType ArgType = MD->getThisType(getContext());
761 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000762 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000763 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000764 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000765 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
766
767 if (!Adjustment.ReturnAdjustment.isEmpty()) {
768 const CovariantThunkAdjustment &ReturnAdjustment =
769 CovariantThunkAdjustment(ThunkAdjustment(),
770 Adjustment.ReturnAdjustment);
771
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000772 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000773
Mike Stump71609a22009-11-04 00:53:51 +0000774 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000775 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000776 }
777 }
778
Mike Stumpf3589722009-11-03 02:12:59 +0000779 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
780
Mike Stump33ccd9e2009-11-02 23:22:01 +0000781 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
782 e = MD->param_end();
783 i != e; ++i) {
784 ParmVarDecl *D = *i;
785 QualType ArgType = D->getType();
786
787 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000788 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
789 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000790 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
791 }
792
Mike Stump31e1d432009-11-02 23:47:45 +0000793 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
794 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000795 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000796 bool CanBeZero = !(ResultType->isReferenceType()
797 // FIXME: attr nonnull can't be zero either
798 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000799 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000800 if (CanBeZero) {
801 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
802 llvm::BasicBlock *ZeroBlock = createBasicBlock();
803 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000804
Mike Stumpc5507682009-11-05 06:32:02 +0000805 const llvm::Type *Ty = RV.getScalarVal()->getType();
806 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
807 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
808 NonZeroBlock, ZeroBlock);
809 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000810 llvm::Value *NZ =
811 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000812 EmitBranch(ContBlock);
813 EmitBlock(ZeroBlock);
814 llvm::Value *Z = RV.getScalarVal();
815 EmitBlock(ContBlock);
816 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
817 RVOrZero->reserveOperandSpace(2);
818 RVOrZero->addIncoming(NZ, NonZeroBlock);
819 RVOrZero->addIncoming(Z, ZeroBlock);
820 RV = RValue::get(RVOrZero);
821 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000822 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
823 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000824 }
825
Mike Stump31e1d432009-11-02 23:47:45 +0000826 if (!ResultType->isVoidType())
827 EmitReturnOfRValue(RV, ResultType);
828
Mike Stump80f6ac52009-09-11 23:25:56 +0000829 FinishFunction();
830 return Fn;
831}
832
Anders Carlssonc7785402009-11-26 02:32:05 +0000833llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000834CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
835 const ThunkAdjustment &ThisAdjustment) {
836 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
837
838 // Compute mangled name
839 llvm::SmallString<256> OutName;
840 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
841 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
842 OutName);
843 else
844 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
845 OutName += '\0';
846 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
847
848 // Get function for mangled name
849 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
850 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
851}
852
853llvm::Constant *
854CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
855 const CovariantThunkAdjustment &Adjustment) {
856 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
857
858 // Compute mangled name
859 llvm::SmallString<256> OutName;
860 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
861 OutName += '\0';
862 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
863
864 // Get function for mangled name
865 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
866 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
867}
868
869void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000870 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
871 if (!AdjPtr)
872 return;
873 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000874 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000875 for (unsigned i = 0; i < Adj.size(); i++) {
876 GlobalDecl OGD = Adj[i].first;
877 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000878 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
879 CanQualType oret = getContext().getCanonicalType(nc_oret);
880 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
881 CanQualType ret = getContext().getCanonicalType(nc_ret);
882 ThunkAdjustment ReturnAdjustment;
883 if (oret != ret) {
884 QualType qD = nc_ret->getPointeeType();
885 QualType qB = nc_oret->getPointeeType();
886 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
887 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
888 ReturnAdjustment = ComputeThunkAdjustment(D, B);
889 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000890 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000891 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
892 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
893 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
894 llvm::Constant *FnConst;
895 if (!ReturnAdjustment.isEmpty())
896 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
897 else
898 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
899 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000900 llvm::Constant *SubExpr =
901 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
902 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
903 std::string Name = OldFn->getNameStr();
904 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
905 Name.data() + Name.size() + 1));
906 llvm::Constant *NewFnConst;
907 if (!ReturnAdjustment.isEmpty())
908 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
909 else
910 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
911 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
912 NewFn->takeName(OldFn);
913 llvm::Constant *NewPtrForOldDecl =
914 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
915 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
916 OldFn->eraseFromParent();
917 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000918 }
919 llvm::Function *Fn = cast<llvm::Function>(FnConst);
920 if (Fn->isDeclaration()) {
921 llvm::GlobalVariable::LinkageTypes linktype;
922 linktype = llvm::GlobalValue::WeakAnyLinkage;
923 if (!Extern)
924 linktype = llvm::GlobalValue::InternalLinkage;
925 Fn->setLinkage(linktype);
926 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
927 Fn->addFnAttr(llvm::Attribute::NoUnwind);
928 Fn->setAlignment(2);
929 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
930 }
931 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000932 }
933}
934
935llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000936CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000937 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000938 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000939 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000940 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
941 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
942 OutName);
943 } else
944 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000945
Mike Stump5a522352009-09-04 18:27:16 +0000946 llvm::GlobalVariable::LinkageTypes linktype;
947 linktype = llvm::GlobalValue::WeakAnyLinkage;
948 if (!Extern)
949 linktype = llvm::GlobalValue::InternalLinkage;
950 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000951 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000952 const llvm::FunctionType *FTy =
953 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
954 FPT->isVariadic());
955
Daniel Dunbare128dd12009-11-21 09:06:22 +0000956 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000957 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000958 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000959 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
960 return m;
961}
962
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000963llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000964CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000965 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000966 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000967 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000968 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000969 llvm::GlobalVariable::LinkageTypes linktype;
970 linktype = llvm::GlobalValue::WeakAnyLinkage;
971 if (!Extern)
972 linktype = llvm::GlobalValue::InternalLinkage;
973 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000974 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000975 const llvm::FunctionType *FTy =
976 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
977 FPT->isVariadic());
978
Daniel Dunbare128dd12009-11-21 09:06:22 +0000979 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000980 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000981 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000982 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
983 return m;
984}
985
Mike Stumpa5588bf2009-08-26 20:46:33 +0000986llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000987CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
988 const CXXRecordDecl *ClassDecl,
989 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000990 const llvm::Type *Int8PtrTy =
991 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
992
993 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
994 Int8PtrTy->getPointerTo());
995 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
996
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000997 int64_t VBaseOffsetIndex =
998 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
999
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001000 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001001 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001002 const llvm::Type *PtrDiffTy =
1003 ConvertType(getContext().getPointerDiffType());
1004
1005 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1006 PtrDiffTy->getPointerTo());
1007
1008 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1009
1010 return VBaseOffset;
1011}
1012
Anders Carlssonf942ee02009-11-27 20:47:55 +00001013static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001014 llvm::Value *This, const llvm::Type *Ty) {
1015 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001016
Anders Carlssone828c362009-11-13 04:45:41 +00001017 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1018 Vtable = CGF.Builder.CreateLoad(Vtable);
1019
1020 llvm::Value *VFuncPtr =
1021 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1022 return CGF.Builder.CreateLoad(VFuncPtr);
1023}
1024
1025llvm::Value *
1026CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1027 const llvm::Type *Ty) {
1028 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001029 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001030
1031 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1032}
1033
1034llvm::Value *
1035CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1036 llvm::Value *&This, const llvm::Type *Ty) {
1037 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001038 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001039 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001040
1041 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001042}
1043
Fariborz Jahanian56263842009-08-21 18:30:26 +00001044/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1045/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1046/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001047// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001048void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001049 llvm::Value *Src,
1050 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001051 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001052 QualType Ty) {
1053 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1054 assert(CA && "VLA cannot be copied over");
1055 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001056
Fariborz Jahanian56263842009-08-21 18:30:26 +00001057 // Create a temporary for the loop index and initialize it with 0.
1058 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1059 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001060 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001061 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001062 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001063 // Start the loop with a block that tests the condition.
1064 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1065 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001066
Fariborz Jahanian56263842009-08-21 18:30:26 +00001067 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Fariborz Jahanian56263842009-08-21 18:30:26 +00001069 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1070 // Generate: if (loop-index < number-of-elements fall to the loop body,
1071 // otherwise, go to the block after the for-loop.
1072 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001073 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001074 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1075 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001076 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001077 "isless");
1078 // If the condition is true, execute the body.
1079 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Fariborz Jahanian56263842009-08-21 18:30:26 +00001081 EmitBlock(ForBody);
1082 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1083 // Inside the loop body, emit the constructor call on the array element.
1084 Counter = Builder.CreateLoad(IndexPtr);
1085 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1086 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1087 if (BitwiseCopy)
1088 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001089 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001090 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001091 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001092 Ctor_Complete);
1093 CallArgList CallArgs;
1094 // Push the this (Dest) ptr.
1095 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1096 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian56263842009-08-21 18:30:26 +00001098 // Push the Src ptr.
1099 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001100 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001101 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001102 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001103 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1104 Callee, CallArgs, BaseCopyCtor);
1105 }
1106 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian56263842009-08-21 18:30:26 +00001108 // Emit the increment of the loop counter.
1109 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1110 Counter = Builder.CreateLoad(IndexPtr);
1111 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001112 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001113
Fariborz Jahanian56263842009-08-21 18:30:26 +00001114 // Finally, branch back up to the condition for the next iteration.
1115 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001116
Fariborz Jahanian56263842009-08-21 18:30:26 +00001117 // Emit the fall-through block.
1118 EmitBlock(AfterFor, true);
1119}
1120
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001121/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001122/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001123/// bitwise assignment or via a copy assignment operator function call.
1124/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001125void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001126 llvm::Value *Src,
1127 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001128 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001129 QualType Ty) {
1130 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1131 assert(CA && "VLA cannot be asssigned");
1132 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001133
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001134 // Create a temporary for the loop index and initialize it with 0.
1135 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1136 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001137 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001138 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001139 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001140 // Start the loop with a block that tests the condition.
1141 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1142 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001143
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001144 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001146 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1147 // Generate: if (loop-index < number-of-elements fall to the loop body,
1148 // otherwise, go to the block after the for-loop.
1149 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001150 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001151 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1152 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001153 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001154 "isless");
1155 // If the condition is true, execute the body.
1156 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001157
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001158 EmitBlock(ForBody);
1159 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1160 // Inside the loop body, emit the assignment operator call on array element.
1161 Counter = Builder.CreateLoad(IndexPtr);
1162 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1163 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1164 const CXXMethodDecl *MD = 0;
1165 if (BitwiseAssign)
1166 EmitAggregateCopy(Dest, Src, Ty);
1167 else {
1168 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1169 MD);
1170 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1171 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001172 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001173 const llvm::Type *LTy =
1174 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1175 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001176 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001178 CallArgList CallArgs;
1179 // Push the this (Dest) ptr.
1180 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1181 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001182
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001183 // Push the Src ptr.
1184 CallArgs.push_back(std::make_pair(RValue::get(Src),
1185 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001186 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001187 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1188 Callee, CallArgs, MD);
1189 }
1190 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001192 // Emit the increment of the loop counter.
1193 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1194 Counter = Builder.CreateLoad(IndexPtr);
1195 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001196 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001198 // Finally, branch back up to the condition for the next iteration.
1199 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001200
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001201 // Emit the fall-through block.
1202 EmitBlock(AfterFor, true);
1203}
1204
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001205/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1206/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001207/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001208void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001209 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001210 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001211 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1212 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001213 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1214 /*NullCheckValue=*/false);
1215 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1216 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001217 }
1218 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1219 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001220 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001221 }
Mike Stump11289f42009-09-09 15:08:12 +00001222
1223 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001224 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001225 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001226 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001227 CallArgList CallArgs;
1228 // Push the this (Dest) ptr.
1229 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1230 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001231
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001232 // Push the Src ptr.
1233 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001234 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001235 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001236 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001237 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1238 Callee, CallArgs, BaseCopyCtor);
1239 }
1240}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001241
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001242/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001243/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001244/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001245// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001246void CodeGenFunction::EmitClassCopyAssignment(
1247 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001248 const CXXRecordDecl *ClassDecl,
1249 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001250 QualType Ty) {
1251 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001252 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1253 /*NullCheckValue=*/false);
1254 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1255 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001256 }
1257 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1258 EmitAggregateCopy(Dest, Src, Ty);
1259 return;
1260 }
Mike Stump11289f42009-09-09 15:08:12 +00001261
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001262 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001263 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001264 MD);
1265 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1266 (void)ConstCopyAssignOp;
1267
John McCall9dd450b2009-09-21 23:43:11 +00001268 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001269 const llvm::Type *LTy =
1270 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001271 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001272 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001273
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001274 CallArgList CallArgs;
1275 // Push the this (Dest) ptr.
1276 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1277 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001278
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001279 // Push the Src ptr.
1280 CallArgs.push_back(std::make_pair(RValue::get(Src),
1281 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001282 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001283 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001284 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1285 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001286}
1287
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001288/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001289void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001290CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1291 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001292 llvm::Function *Fn,
1293 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001294 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001295 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1296 SourceLocation());
1297 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001298 FinishFunction();
1299}
1300
Mike Stumpb9c9b352009-11-04 01:11:15 +00001301/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1302/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001303/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001304/// copy of its subobjects. The order of copying is the same as the order of
1305/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001306/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001307/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001308/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001309/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001310/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001311/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001312/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001313/// Virtual base class subobjects shall be copied only once by the
1314/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001315
Anders Carlssonddf57d32009-09-14 05:32:02 +00001316void
1317CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1318 CXXCtorType Type,
1319 llvm::Function *Fn,
1320 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001321 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001322 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001323 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001324 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001325 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1326 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001327
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001328 FunctionArgList::const_iterator i = Args.begin();
1329 const VarDecl *ThisArg = i->first;
1330 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1331 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1332 const VarDecl *SrcArg = (i+1)->first;
1333 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1334 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001335
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001336 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1337 Base != ClassDecl->bases_end(); ++Base) {
1338 // FIXME. copy constrution of virtual base NYI
1339 if (Base->isVirtual())
1340 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001342 CXXRecordDecl *BaseClassDecl
1343 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001344 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1345 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001348 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1349 E = ClassDecl->field_end(); I != E; ++I) {
1350 const FieldDecl *Field = *I;
1351
1352 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001353 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001354 getContext().getAsConstantArrayType(FieldType);
1355 if (Array)
1356 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001358 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1359 CXXRecordDecl *FieldClassDecl
1360 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001361 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1362 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001363 if (Array) {
1364 const llvm::Type *BasePtr = ConvertType(FieldType);
1365 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001366 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001367 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001368 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001369 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1370 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1371 FieldClassDecl, FieldType);
1372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373 else
1374 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001375 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001376 continue;
1377 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001378
1379 if (Field->getType()->isReferenceType()) {
1380 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1381
1382 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1383 "lhs.ref");
1384
1385 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1386 "rhs.ref");
1387
1388 // Load the value in RHS.
1389 RHS = Builder.CreateLoad(RHS);
1390
1391 // And store it in the LHS
1392 Builder.CreateStore(RHS, LHS);
1393
1394 continue;
1395 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001396 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001397 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1398 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1399
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001400 if (!hasAggregateLLVMType(Field->getType())) {
1401 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1402 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1403 } else if (Field->getType()->isAnyComplexType()) {
1404 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1405 RHS.isVolatileQualified());
1406 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1407 } else {
1408 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1409 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001410 }
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001411
1412 InitializeVtablePtrs(ClassDecl);
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001413 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001414}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001415
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001416/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001417/// Before the implicitly-declared copy assignment operator for a class is
1418/// implicitly defined, all implicitly- declared copy assignment operators for
1419/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001420/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001421/// The implicitly-defined copy assignment operator for class X performs
1422/// memberwise assignment of its subob- jects. The direct base classes of X are
1423/// assigned first, in the order of their declaration in
1424/// the base-specifier-list, and then the immediate nonstatic data members of X
1425/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001426/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001427/// if the subobject is of class type, the copy assignment operator for the
1428/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001429/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001430///
Mike Stump11289f42009-09-09 15:08:12 +00001431/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001432/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001433///
Mike Stump11289f42009-09-09 15:08:12 +00001434/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001435/// used.
1436void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001437 llvm::Function *Fn,
1438 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001439
1440 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1441 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1442 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001443 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001444
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001445 FunctionArgList::const_iterator i = Args.begin();
1446 const VarDecl *ThisArg = i->first;
1447 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1448 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1449 const VarDecl *SrcArg = (i+1)->first;
1450 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1451 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001453 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1454 Base != ClassDecl->bases_end(); ++Base) {
1455 // FIXME. copy assignment of virtual base NYI
1456 if (Base->isVirtual())
1457 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001458
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001459 CXXRecordDecl *BaseClassDecl
1460 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1461 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1462 Base->getType());
1463 }
Mike Stump11289f42009-09-09 15:08:12 +00001464
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001465 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1466 FieldEnd = ClassDecl->field_end();
1467 Field != FieldEnd; ++Field) {
1468 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001469 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001470 getContext().getAsConstantArrayType(FieldType);
1471 if (Array)
1472 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001473
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001474 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1475 CXXRecordDecl *FieldClassDecl
1476 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1477 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1478 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001479 if (Array) {
1480 const llvm::Type *BasePtr = ConvertType(FieldType);
1481 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1482 llvm::Value *DestBaseAddrPtr =
1483 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1484 llvm::Value *SrcBaseAddrPtr =
1485 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1486 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1487 FieldClassDecl, FieldType);
1488 }
1489 else
Mike Stump11289f42009-09-09 15:08:12 +00001490 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001491 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001492 continue;
1493 }
1494 // Do a built-in assignment of scalar data members.
1495 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1496 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001497 if (!hasAggregateLLVMType(Field->getType())) {
1498 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1499 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1500 } else if (Field->getType()->isAnyComplexType()) {
1501 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1502 RHS.isVolatileQualified());
1503 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1504 } else {
1505 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1506 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001507 }
Mike Stump11289f42009-09-09 15:08:12 +00001508
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001509 // return *this;
1510 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001512 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001513}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001514
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001515static void EmitBaseInitializer(CodeGenFunction &CGF,
1516 const CXXRecordDecl *ClassDecl,
1517 CXXBaseOrMemberInitializer *BaseInit,
1518 CXXCtorType CtorType) {
1519 assert(BaseInit->isBaseInitializer() &&
1520 "Must have base initializer!");
1521
1522 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1523
1524 const Type *BaseType = BaseInit->getBaseClass();
1525 CXXRecordDecl *BaseClassDecl =
1526 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Anders Carlsson8c793172009-11-23 17:57:54 +00001527 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1528 BaseClassDecl,
1529 /*NullCheckValue=*/false);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001530 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1531 CtorType, V,
1532 BaseInit->const_arg_begin(),
1533 BaseInit->const_arg_end());
1534}
1535
1536static void EmitMemberInitializer(CodeGenFunction &CGF,
1537 const CXXRecordDecl *ClassDecl,
1538 CXXBaseOrMemberInitializer *MemberInit) {
1539 assert(MemberInit->isMemberInitializer() &&
1540 "Must have member initializer!");
1541
1542 // non-static data member initializers.
1543 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001544 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001545
1546 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1547 LValue LHS;
1548 if (FieldType->isReferenceType()) {
1549 // FIXME: This is really ugly; should be refactored somehow
1550 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1551 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1552 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1553 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1554 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001555 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001556 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001557
1558 // If we are initializing an anonymous union field, drill down to the field.
1559 if (MemberInit->getAnonUnionMember()) {
1560 Field = MemberInit->getAnonUnionMember();
1561 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1562 /*IsUnion=*/true, 0);
1563 FieldType = Field->getType();
1564 }
1565
1566 // If the field is an array, branch based on the element type.
1567 const ConstantArrayType *Array =
1568 CGF.getContext().getAsConstantArrayType(FieldType);
1569 if (Array)
1570 FieldType = CGF.getContext().getBaseElementType(FieldType);
1571
Eli Friedmane85ef712009-11-16 23:53:01 +00001572 // We lose the constructor for anonymous union members, so handle them
1573 // explicitly.
1574 // FIXME: This is somwhat ugly.
1575 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1576 if (MemberInit->getNumArgs())
1577 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1578 LHS.isVolatileQualified());
1579 else
1580 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1581 return;
1582 }
1583
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001584 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001585 assert(MemberInit->getConstructor() &&
1586 "EmitCtorPrologue - no constructor to initialize member");
1587 if (Array) {
1588 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1589 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1590 llvm::Value *BaseAddrPtr =
1591 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1592 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001593 Array, BaseAddrPtr,
1594 MemberInit->const_arg_begin(),
1595 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001596 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001597 else
1598 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1599 Ctor_Complete, LHS.getAddress(),
1600 MemberInit->const_arg_begin(),
1601 MemberInit->const_arg_end());
1602 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001603 }
1604
1605 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1606 Expr *RhsExpr = *MemberInit->arg_begin();
1607 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001608 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001609 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1610 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001611 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001612 } else if (Array) {
1613 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1614 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1615 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1616 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1617 } else if (RhsExpr->getType()->isAnyComplexType()) {
1618 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1619 LHS.isVolatileQualified());
1620 } else {
1621 // Handle member function pointers; other aggregates shouldn't get this far.
1622 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1623 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001624}
1625
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001626/// EmitCtorPrologue - This routine generates necessary code to initialize
1627/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001628/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001629void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1630 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001631 const CXXRecordDecl *ClassDecl = CD->getParent();
1632
Mike Stump6b2556f2009-08-06 13:41:24 +00001633 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001634
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001635 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001636 E = CD->init_end();
1637 B != E; ++B) {
1638 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001639
Anders Carlsson5852b132009-11-06 04:11:09 +00001640 assert(LiveTemporaries.empty() &&
1641 "Should not have any live temporaries at initializer start!");
1642
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001643 if (Member->isBaseInitializer())
1644 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1645 else
1646 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001647
1648 // Pop any live temporaries that the initializers might have pushed.
1649 while (!LiveTemporaries.empty())
1650 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001651 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001652
Eli Friedman80888c72009-12-08 06:54:20 +00001653 InitializeVtablePtrs(ClassDecl);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001654}
1655
1656void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001657 if (!ClassDecl->isDynamicClass())
1658 return;
1659
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001660 // Initialize the vtable pointer.
1661 // FIXME: This needs to initialize secondary vtable pointers too.
1662 llvm::Value *ThisPtr = LoadCXXThis();
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001663
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001664 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1665 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1666
1667 llvm::Value *VtableAddressPoint =
1668 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1669
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001670 llvm::Value *VtableField =
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001671 Builder.CreateBitCast(ThisPtr,
1672 VtableAddressPoint->getType()->getPointerTo());
1673
1674 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001675}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001676
1677/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001678/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001679/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001680/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001681void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1682 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001683 assert(!DD->isTrivial() &&
1684 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001685
Anders Carlssondee9a302009-11-17 04:44:12 +00001686 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001687
Anders Carlssondee9a302009-11-17 04:44:12 +00001688 // Collect the fields.
1689 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1690 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1691 E = ClassDecl->field_end(); I != E; ++I) {
1692 const FieldDecl *Field = *I;
1693
1694 QualType FieldType = getContext().getCanonicalType(Field->getType());
1695 FieldType = getContext().getBaseElementType(FieldType);
1696
1697 const RecordType *RT = FieldType->getAs<RecordType>();
1698 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001699 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001700
1701 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1702 if (FieldClassDecl->hasTrivialDestructor())
1703 continue;
1704
1705 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001706 }
Anders Carlssond7872042009-11-15 23:03:25 +00001707
Anders Carlssondee9a302009-11-17 04:44:12 +00001708 // Now destroy the fields.
1709 for (size_t i = FieldDecls.size(); i > 0; --i) {
1710 const FieldDecl *Field = FieldDecls[i - 1];
1711
1712 QualType FieldType = Field->getType();
1713 const ConstantArrayType *Array =
1714 getContext().getAsConstantArrayType(FieldType);
1715 if (Array)
1716 FieldType = getContext().getBaseElementType(FieldType);
1717
1718 const RecordType *RT = FieldType->getAs<RecordType>();
1719 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1720
1721 llvm::Value *ThisPtr = LoadCXXThis();
1722
1723 LValue LHS = EmitLValueForField(ThisPtr, Field,
1724 /*isUnion=*/false,
1725 // FIXME: Qualifiers?
1726 /*CVRQualifiers=*/0);
1727 if (Array) {
1728 const llvm::Type *BasePtr = ConvertType(FieldType);
1729 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1730 llvm::Value *BaseAddrPtr =
1731 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1732 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1733 Array, BaseAddrPtr);
1734 } else
1735 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1736 Dtor_Complete, LHS.getAddress());
1737 }
1738
1739 // Destroy non-virtual bases.
1740 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1741 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1742 const CXXBaseSpecifier &Base = *I;
1743
1744 // Ignore virtual bases.
1745 if (Base.isVirtual())
1746 continue;
1747
1748 CXXRecordDecl *BaseClassDecl
1749 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1750
1751 // Ignore trivial destructors.
1752 if (BaseClassDecl->hasTrivialDestructor())
1753 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001754 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1755
Anders Carlsson8c793172009-11-23 17:57:54 +00001756 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1757 ClassDecl, BaseClassDecl,
1758 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001759 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001760 }
1761
1762 // If we're emitting a base destructor, we don't want to emit calls to the
1763 // virtual bases.
1764 if (DtorType == Dtor_Base)
1765 return;
1766
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001767 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001768 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1769 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001770 const CXXBaseSpecifier &Base = *I;
1771 CXXRecordDecl *BaseClassDecl
1772 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1773
1774 // Ignore trivial destructors.
1775 if (BaseClassDecl->hasTrivialDestructor())
1776 continue;
1777 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1778 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1779 ClassDecl, BaseClassDecl,
1780 /*NullCheckValue=*/false);
1781 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001782 }
1783
1784 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001785 if (DtorType == Dtor_Deleting) {
1786 assert(DD->getOperatorDelete() &&
1787 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001788 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1789 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001790 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001791}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001792
Anders Carlssonddf57d32009-09-14 05:32:02 +00001793void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1794 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001795 llvm::Function *Fn,
1796 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001797 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001798 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001799
Anders Carlssonddf57d32009-09-14 05:32:02 +00001800 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1801 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001802
Anders Carlssonddf57d32009-09-14 05:32:02 +00001803 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001804 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001805}