blob: 0237a322a526eab0f87ccef1be9f17c13dbb9f49 [file] [log] [blame]
Anders Carlsson87fc5a52008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump11289f42009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000015
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson1235bbc2009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000025#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000029RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
30 llvm::Value *Callee,
31 llvm::Value *This,
32 CallExpr::const_arg_iterator ArgBeg,
33 CallExpr::const_arg_iterator ArgEnd) {
Mike Stump11289f42009-09-09 15:08:12 +000034 assert(MD->isInstance() &&
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000035 "Trying to emit a member call expr on a static method!");
36
John McCall9dd450b2009-09-21 23:43:11 +000037 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +000038
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000039 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +000040
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000041 // Push the this ptr.
42 Args.push_back(std::make_pair(RValue::get(This),
43 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +000044
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000045 // And the rest of the call args
46 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
Mike Stump11289f42009-09-09 15:08:12 +000047
John McCall9dd450b2009-09-21 23:43:11 +000048 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000049 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
50 Callee, Args, MD);
51}
52
Anders Carlssond7432df2009-10-12 19:41:04 +000053/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
54/// expr can be devirtualized.
55static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
56 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
57 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
58 // This is a record decl. We know the type and can devirtualize it.
59 return VD->getType()->isRecordType();
60 }
Anders Carlssonb61301f2009-10-12 19:45:47 +000061
62 return false;
Anders Carlssond7432df2009-10-12 19:41:04 +000063 }
64
Anders Carlssona1b54fd2009-10-12 19:59:15 +000065 // We can always devirtualize calls on temporary object expressions.
Anders Carlssonb61301f2009-10-12 19:45:47 +000066 if (isa<CXXTemporaryObjectExpr>(Base))
67 return true;
68
Anders Carlssona1b54fd2009-10-12 19:59:15 +000069 // And calls on bound temporaries.
70 if (isa<CXXBindTemporaryExpr>(Base))
71 return true;
72
Anders Carlsson2a017092009-10-12 19:51:33 +000073 // Check if this is a call expr that returns a record type.
74 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
75 return CE->getCallReturnType()->isRecordType();
76
Anders Carlssond7432df2009-10-12 19:41:04 +000077 // We can't devirtualize the call.
78 return false;
79}
80
Anders Carlssone5fd6f22009-04-03 22:50:24 +000081RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
Eli Friedman8aaff692009-12-08 02:09:46 +000082 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
Anders Carlsson2ee3c012009-10-03 19:43:08 +000083 return EmitCXXMemberPointerCallExpr(CE);
84
Eli Friedman8aaff692009-12-08 02:09:46 +000085 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
Anders Carlssone5fd6f22009-04-03 22:50:24 +000086 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000087
Anders Carlsson8f4fd602009-09-29 03:54:11 +000088 if (MD->isStatic()) {
89 // The method is static, emit it as we would a regular call.
90 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
91 return EmitCall(Callee, getContext().getPointerType(MD->getType()),
92 CE->arg_begin(), CE->arg_end(), 0);
93
94 }
95
John McCall9dd450b2009-09-21 23:43:11 +000096 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumpa523b2d2009-07-30 21:47:44 +000097
Mike Stump11289f42009-09-09 15:08:12 +000098 const llvm::Type *Ty =
99 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Anders Carlsson03a409f2009-04-08 20:31:57 +0000100 FPT->isVariadic());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000101 llvm::Value *This;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000103 if (ME->isArrow())
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000104 This = EmitScalarExpr(ME->getBase());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000105 else {
106 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000107 This = BaseLV.getAddress();
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000108 }
Mike Stumpa5588bf2009-08-26 20:46:33 +0000109
Eli Friedmanffc066f2009-11-26 07:45:48 +0000110 if (MD->isCopyAssignment() && MD->isTrivial()) {
111 // We don't like to generate the trivial copy assignment operator when
112 // it isn't necessary; just produce the proper effect here.
113 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
114 EmitAggregateCopy(This, RHS, CE->getType());
115 return RValue::get(This);
116 }
117
Douglas Gregorc1905232009-08-26 22:36:53 +0000118 // C++ [class.virtual]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000119 // Explicit qualification with the scope operator (5.1) suppresses the
Douglas Gregorc1905232009-08-26 22:36:53 +0000120 // virtual call mechanism.
Anders Carlssonb5296552009-10-11 23:55:52 +0000121 //
122 // We also don't emit a virtual call if the base expression has a record type
123 // because then we know what the type is.
Mike Stumpa5588bf2009-08-26 20:46:33 +0000124 llvm::Value *Callee;
Eli Friedmane6ce3542009-11-16 05:31:29 +0000125 if (const CXXDestructorDecl *Destructor
126 = dyn_cast<CXXDestructorDecl>(MD)) {
Eli Friedman84a7e342009-11-26 07:40:08 +0000127 if (Destructor->isTrivial())
128 return RValue::get(0);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000129 if (MD->isVirtual() && !ME->hasQualifier() &&
130 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
131 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
132 } else {
133 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
134 }
135 } else if (MD->isVirtual() && !ME->hasQualifier() &&
136 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
137 Callee = BuildVirtualCall(MD, This, Ty);
138 } else {
Anders Carlssonecf9bf02009-09-10 23:43:36 +0000139 Callee = CGM.GetAddrOfFunction(MD, Ty);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
142 return EmitCXXMemberCall(MD, Callee, This,
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000143 CE->arg_begin(), CE->arg_end());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000144}
Anders Carlssona5d077d2009-04-14 16:58:56 +0000145
Mike Stump11289f42009-09-09 15:08:12 +0000146RValue
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000147CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
Eli Friedman8aaff692009-12-08 02:09:46 +0000148 const BinaryOperator *BO =
149 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000150 const Expr *BaseExpr = BO->getLHS();
151 const Expr *MemFnExpr = BO->getRHS();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000152
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000153 const MemberPointerType *MPT =
154 MemFnExpr->getType()->getAs<MemberPointerType>();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000155 const FunctionProtoType *FPT =
156 MPT->getPointeeType()->getAs<FunctionProtoType>();
157 const CXXRecordDecl *RD =
Douglas Gregor615ac672009-11-04 16:49:01 +0000158 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000159
160 const llvm::FunctionType *FTy =
161 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
162 FPT->isVariadic());
163
164 const llvm::Type *Int8PtrTy =
165 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
166
167 // Get the member function pointer.
168 llvm::Value *MemFnPtr =
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000169 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
170 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171
172 // Emit the 'this' pointer.
173 llvm::Value *This;
174
175 if (BO->getOpcode() == BinaryOperator::PtrMemI)
176 This = EmitScalarExpr(BaseExpr);
177 else
178 This = EmitLValue(BaseExpr).getAddress();
179
180 // Adjust it.
181 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
182 Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
183
184 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
185 Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
186
187 This = Builder.CreateBitCast(Ptr, This->getType(), "this");
188
189 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
190
191 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
192
193 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
194
195 // If the LSB in the function pointer is 1, the function pointer points to
196 // a virtual function.
197 llvm::Value *IsVirtual
198 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
199 "and");
200
201 IsVirtual = Builder.CreateTrunc(IsVirtual,
202 llvm::Type::getInt1Ty(VMContext));
203
204 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
205 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
206 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
207
208 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
209 EmitBlock(FnVirtual);
210
211 const llvm::Type *VTableTy =
212 FTy->getPointerTo()->getPointerTo()->getPointerTo();
213
214 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
215 VTable = Builder.CreateLoad(VTable);
216
217 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
218
219 // Since the function pointer is 1 plus the virtual table offset, we
220 // subtract 1 by using a GEP.
Mike Stump0d479e62009-10-09 01:25:47 +0000221 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222
223 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
224
225 EmitBranch(FnEnd);
226 EmitBlock(FnNonVirtual);
227
228 // If the function is not virtual, just load the pointer.
229 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
230 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
231
232 EmitBlock(FnEnd);
233
234 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
235 Callee->reserveOperandSpace(2);
236 Callee->addIncoming(VirtualFn, FnVirtual);
237 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
238
239 CallArgList Args;
240
241 QualType ThisType =
242 getContext().getPointerType(getContext().getTagDeclType(RD));
243
244 // Push the this ptr.
245 Args.push_back(std::make_pair(RValue::get(This), ThisType));
246
247 // And the rest of the call args
248 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
249 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
250 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
251 Callee, Args, 0);
252}
253
254RValue
Anders Carlsson4034a952009-05-27 04:18:27 +0000255CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
256 const CXXMethodDecl *MD) {
Mike Stump11289f42009-09-09 15:08:12 +0000257 assert(MD->isInstance() &&
Anders Carlsson4034a952009-05-27 04:18:27 +0000258 "Trying to emit a member call expr on a static method!");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Fariborz Jahanian4985b332009-08-13 21:09:41 +0000260 if (MD->isCopyAssignment()) {
261 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
262 if (ClassDecl->hasTrivialCopyAssignment()) {
263 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
264 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
265 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
266 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
267 QualType Ty = E->getType();
268 EmitAggregateCopy(This, Src, Ty);
269 return RValue::get(This);
270 }
271 }
Mike Stump11289f42009-09-09 15:08:12 +0000272
John McCall9dd450b2009-09-21 23:43:11 +0000273 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000274 const llvm::Type *Ty =
275 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Mike Stump5a522352009-09-04 18:27:16 +0000276 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000277
Anders Carlsson4034a952009-05-27 04:18:27 +0000278 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
Mike Stump11289f42009-09-09 15:08:12 +0000279
Eli Friedmane6ce3542009-11-16 05:31:29 +0000280 llvm::Value *Callee;
281 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
282 Callee = BuildVirtualCall(MD, This, Ty);
283 else
284 Callee = CGM.GetAddrOfFunction(MD, Ty);
285
Anders Carlsson4034a952009-05-27 04:18:27 +0000286 return EmitCXXMemberCall(MD, Callee, This,
287 E->arg_begin() + 1, E->arg_end());
288}
289
Anders Carlssona5d077d2009-04-14 16:58:56 +0000290llvm::Value *CodeGenFunction::LoadCXXThis() {
Mike Stump11289f42009-09-09 15:08:12 +0000291 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
Anders Carlssona5d077d2009-04-14 16:58:56 +0000292 "Must be in a C++ member function decl to load 'this'");
293 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
294 "Must be in a C++ member function decl to load 'this'");
Mike Stump11289f42009-09-09 15:08:12 +0000295
Anders Carlssona5d077d2009-04-14 16:58:56 +0000296 // FIXME: What if we're inside a block?
Mike Stump18bb9282009-05-16 07:57:57 +0000297 // ans: See how CodeGenFunction::LoadObjCSelf() uses
298 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlssona5d077d2009-04-14 16:58:56 +0000299 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
300}
Anders Carlssonf7475242009-04-15 15:55:24 +0000301
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000302/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
303/// for-loop to call the default constructor on individual members of the
Anders Carlssond49844b2009-09-23 02:45:36 +0000304/// array.
305/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
306/// array type and 'ArrayPtr' points to the beginning fo the array.
307/// It is assumed that all relevant checks have been made by the caller.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000308void
309CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000310 const ConstantArrayType *ArrayTy,
311 llvm::Value *ArrayPtr,
312 CallExpr::const_arg_iterator ArgBeg,
313 CallExpr::const_arg_iterator ArgEnd) {
314
Anders Carlssond49844b2009-09-23 02:45:36 +0000315 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
316 llvm::Value * NumElements =
317 llvm::ConstantInt::get(SizeTy,
318 getContext().getConstantArrayElementCount(ArrayTy));
319
Anders Carlsson3a202f62009-11-24 18:43:52 +0000320 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
Anders Carlssond49844b2009-09-23 02:45:36 +0000321}
322
323void
324CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000325 llvm::Value *NumElements,
326 llvm::Value *ArrayPtr,
327 CallExpr::const_arg_iterator ArgBeg,
328 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssond49844b2009-09-23 02:45:36 +0000329 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000330
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000331 // Create a temporary for the loop index and initialize it with 0.
Anders Carlssond49844b2009-09-23 02:45:36 +0000332 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
333 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000334 Builder.CreateStore(Zero, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000336 // Start the loop with a block that tests the condition.
337 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
338 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000339
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000340 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000342 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000344 // Generate: if (loop-index < number-of-elements fall to the loop body,
345 // otherwise, go to the block after the for-loop.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000346 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000347 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000348 // If the condition is true, execute the body.
349 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000351 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000353 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000354 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniandd46eb72009-08-20 01:01:06 +0000355 Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000356 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
357 "arrayidx");
Mike Stump11289f42009-09-09 15:08:12 +0000358
Anders Carlsson3a202f62009-11-24 18:43:52 +0000359 // C++ [class.temporary]p4:
360 // There are two contexts in which temporaries are destroyed at a different
Mike Stump26004912009-12-10 00:05:14 +0000361 // point than the end of the full-expression. The first context is when a
Anders Carlsson3a202f62009-11-24 18:43:52 +0000362 // default constructor is called to initialize an element of an array.
363 // If the constructor has one or more default arguments, the destruction of
364 // every temporary created in a default argument expression is sequenced
365 // before the construction of the next array element, if any.
366
367 // Keep track of the current number of live temporaries.
368 unsigned OldNumLiveTemporaries = LiveTemporaries.size();
369
370 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
371
372 // Pop temporaries.
373 while (LiveTemporaries.size() > OldNumLiveTemporaries)
374 PopCXXTemporary();
375
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000376 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000378 // Emit the increment of the loop counter.
Anders Carlssond49844b2009-09-23 02:45:36 +0000379 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000380 Counter = Builder.CreateLoad(IndexPtr);
381 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000382 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000384 // Finally, branch back up to the condition for the next iteration.
385 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000387 // Emit the fall-through block.
388 EmitBlock(AfterFor, true);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000389}
390
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000391/// EmitCXXAggrDestructorCall - calls the default destructor on array
392/// elements in reverse order of construction.
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000393void
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000394CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
395 const ArrayType *Array,
396 llvm::Value *This) {
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000397 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
398 assert(CA && "Do we support VLA for destruction ?");
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000399 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Anders Carlsson21122cf2009-12-13 20:04:38 +0000400
401 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
402 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000403 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
404}
405
406/// EmitCXXAggrDestructorCall - calls the default destructor on array
407/// elements in reverse order of construction.
408void
409CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
410 llvm::Value *UpperCount,
411 llvm::Value *This) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000412 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
413 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
414
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000415 // Create a temporary for the loop index and initialize it with count of
416 // array elements.
Anders Carlsson21122cf2009-12-13 20:04:38 +0000417 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
418
419 // Store the number of elements in the index pointer.
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000420 Builder.CreateStore(UpperCount, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000422 // Start the loop with a block that tests the condition.
423 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
424 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000425
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000426 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000428 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000429
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000430 // Generate: if (loop-index != 0 fall to the loop body,
431 // otherwise, go to the block after the for-loop.
Mike Stump11289f42009-09-09 15:08:12 +0000432 llvm::Value* zeroConstant =
Anders Carlsson21122cf2009-12-13 20:04:38 +0000433 llvm::Constant::getNullValue(SizeLTy);
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000434 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
435 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
436 "isne");
437 // If the condition is true, execute the body.
438 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000440 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000442 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
443 // Inside the loop body, emit the constructor call on the array element.
444 Counter = Builder.CreateLoad(IndexPtr);
445 Counter = Builder.CreateSub(Counter, One);
446 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanianbe641492009-11-30 22:07:18 +0000447 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump11289f42009-09-09 15:08:12 +0000448
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000449 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000450
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000451 // Emit the decrement of the loop counter.
452 Counter = Builder.CreateLoad(IndexPtr);
453 Counter = Builder.CreateSub(Counter, One, "dec");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000454 Builder.CreateStore(Counter, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000456 // Finally, branch back up to the condition for the next iteration.
457 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000459 // Emit the fall-through block.
460 EmitBlock(AfterFor, true);
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000461}
462
Mike Stumpea950e22009-11-18 18:57:56 +0000463/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
464/// invoked, calls the default destructor on array elements in reverse order of
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000465/// construction.
466llvm::Constant *
467CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
468 const ArrayType *Array,
469 llvm::Value *This) {
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000470 FunctionArgList Args;
471 ImplicitParamDecl *Dst =
472 ImplicitParamDecl::Create(getContext(), 0,
473 SourceLocation(), 0,
474 getContext().getPointerType(getContext().VoidTy));
475 Args.push_back(std::make_pair(Dst, Dst->getType()));
476
477 llvm::SmallString<16> Name;
Eli Friedmand5bc94e2009-12-10 02:21:21 +0000478 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000479 QualType R = getContext().VoidTy;
480 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
481 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
482 llvm::Function *Fn =
483 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000484 Name.str(),
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000485 &CGM.getModule());
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000486 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000487 FunctionDecl *FD = FunctionDecl::Create(getContext(),
488 getContext().getTranslationUnitDecl(),
489 SourceLocation(), II, R, 0,
490 FunctionDecl::Static,
491 false, true);
492 StartFunction(FD, R, Fn, Args, SourceLocation());
493 QualType BaseElementTy = getContext().getBaseElementType(Array);
494 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
495 BasePtr = llvm::PointerType::getUnqual(BasePtr);
496 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
497 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
498 FinishFunction();
499 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
500 0);
501 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
502 return m;
503}
504
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000505void
Mike Stump11289f42009-09-09 15:08:12 +0000506CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
507 CXXCtorType Type,
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000508 llvm::Value *This,
509 CallExpr::const_arg_iterator ArgBeg,
510 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000511 if (D->isCopyConstructor(getContext())) {
512 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
513 if (ClassDecl->hasTrivialCopyConstructor()) {
514 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
515 "EmitCXXConstructorCall - user declared copy constructor");
516 const Expr *E = (*ArgBeg);
517 QualType Ty = E->getType();
518 llvm::Value *Src = EmitLValue(E).getAddress();
519 EmitAggregateCopy(This, Src, Ty);
520 return;
521 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000522 } else if (D->isTrivial()) {
523 // FIXME: Track down why we're trying to generate calls to the trivial
524 // default constructor!
525 return;
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000528 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
529
530 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000531}
532
Anders Carlssonce460522009-12-04 19:33:17 +0000533void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
Anders Carlsson0a637412009-05-29 21:03:38 +0000534 CXXDtorType Type,
535 llvm::Value *This) {
Anders Carlssonce460522009-12-04 19:33:17 +0000536 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
537
538 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Anders Carlssonce460522009-12-04 19:33:17 +0000540 // Push the this ptr.
541 Args.push_back(std::make_pair(RValue::get(This),
542 DD->getThisType(getContext())));
543
544 // Add a VTT parameter if necessary.
545 // FIXME: This should not be a dummy null parameter!
546 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
547 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
548
549 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
550 }
551
552 // FIXME: We should try to share this code with EmitCXXMemberCall.
553
554 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
555 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
Anders Carlsson0a637412009-05-29 21:03:38 +0000556}
557
Mike Stump11289f42009-09-09 15:08:12 +0000558void
559CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson1619a5042009-05-03 17:47:16 +0000560 const CXXConstructExpr *E) {
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000561 assert(Dest && "Must have a destination!");
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000562 const CXXConstructorDecl *CD = E->getConstructor();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000563 const ConstantArrayType *Array =
564 getContext().getAsConstantArrayType(E->getType());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000565 // For a copy constructor, even if it is trivial, must fall thru so
566 // its argument is code-gen'ed.
567 if (!CD->isCopyConstructor(getContext())) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000568 QualType InitType = E->getType();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000569 if (Array)
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000570 InitType = getContext().getBaseElementType(Array);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000571 const CXXRecordDecl *RD =
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000572 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000573 if (RD->hasTrivialConstructor())
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000574 return;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000577 // its first argument instead.
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000578 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000579 const Expr *Arg = E->getArg(0);
Douglas Gregore1314a62009-12-18 05:02:21 +0000580
581 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
Douglas Gregor357b6fd2009-12-18 05:19:44 +0000582 assert((ICE->getCastKind() == CastExpr::CK_NoOp ||
Anders Carlsson28a133d2009-12-18 17:29:21 +0000583 ICE->getCastKind() == CastExpr::CK_ConstructorConversion ||
584 ICE->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
Douglas Gregor357b6fd2009-12-18 05:19:44 +0000585 "Unknown implicit cast kind in constructor elision");
586 Arg = ICE->getSubExpr();
587 }
588
589 if (const CXXBindTemporaryExpr *BindExpr =
590 dyn_cast<CXXBindTemporaryExpr>(Arg))
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000591 Arg = BindExpr->getSubExpr();
592
593 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000594 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000595 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000596 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000597 QualType BaseElementTy = getContext().getBaseElementType(Array);
598 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
599 BasePtr = llvm::PointerType::getUnqual(BasePtr);
600 llvm::Value *BaseAddrPtr =
601 Builder.CreateBitCast(Dest, BasePtr);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000602
Anders Carlsson3a202f62009-11-24 18:43:52 +0000603 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
604 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000605 }
606 else
607 // Call the constructor.
608 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
609 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000610}
611
Anders Carlssonf7475242009-04-15 15:55:24 +0000612void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000613 EmitGlobal(GlobalDecl(D, Ctor_Complete));
614 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000615}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000616
Mike Stump11289f42009-09-09 15:08:12 +0000617void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000618 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000619
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000620 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000621
Anders Carlsson73fcc952009-09-11 00:07:24 +0000622 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000623
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000624 SetFunctionDefinitionAttributes(D, Fn);
625 SetLLVMFunctionAttributesForDefinition(D, Fn);
626}
627
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000628llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000629CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000630 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000631 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000632 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000633 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000634 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000635
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000636 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000637 return cast<llvm::Function>(
638 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000639}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000640
Mike Stump11289f42009-09-09 15:08:12 +0000641const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000642 CXXCtorType Type) {
643 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000644 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000646 Name += '\0';
647 return UniqueMangledName(Name.begin(), Name.end());
648}
649
650void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000651 if (D->isVirtual())
Eli Friedmand777ccc2009-12-15 02:06:15 +0000652 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
653 EmitGlobal(GlobalDecl(D, Dtor_Complete));
654 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000655}
656
Mike Stump11289f42009-09-09 15:08:12 +0000657void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000658 CXXDtorType Type) {
659 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000660
Anders Carlsson73fcc952009-09-11 00:07:24 +0000661 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000662
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000663 SetFunctionDefinitionAttributes(D, Fn);
664 SetLLVMFunctionAttributesForDefinition(D, Fn);
665}
666
667llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000668CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000669 CXXDtorType Type) {
670 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000671 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000672
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000673 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000674 return cast<llvm::Function>(
675 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000676}
677
Mike Stump11289f42009-09-09 15:08:12 +0000678const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000679 CXXDtorType Type) {
680 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000681 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000682
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000683 Name += '\0';
684 return UniqueMangledName(Name.begin(), Name.end());
685}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000686
Anders Carlssonc7785402009-11-26 02:32:05 +0000687llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000688CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000689 bool Extern,
690 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000691 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000692 CovariantThunkAdjustment(ThisAdjustment,
693 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000694}
695
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000696llvm::Value *
697CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
698 const ThunkAdjustment &Adjustment) {
699 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
700
Mike Stump77738202009-11-03 16:59:27 +0000701 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000702 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000703 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000704 V = Builder.CreateBitCast(V, Int8PtrTy);
705 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000706 V = Builder.CreateBitCast(V, OrigTy);
707 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000708
709 if (!Adjustment.Virtual)
710 return V;
711
712 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
713 "vtable entry unaligned");
714
715 // Do the virtual this adjustment
716 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
717 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
718
719 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
720 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
721 V = Builder.CreateLoad(V, "vtable");
722
723 llvm::Value *VTablePtr = V;
724 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
725 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
726 V = Builder.CreateLoad(V);
727 V = Builder.CreateGEP(ThisVal, V);
728
729 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000730}
731
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000732llvm::Constant *
733CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000734 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000735 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000736 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000737 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000738
739 FunctionArgList Args;
740 ImplicitParamDecl *ThisDecl =
741 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
742 MD->getThisType(getContext()));
743 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
744 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
745 e = MD->param_end();
746 i != e; ++i) {
747 ParmVarDecl *D = *i;
748 Args.push_back(std::make_pair(D, D->getType()));
749 }
750 IdentifierInfo *II
751 = &CGM.getContext().Idents.get("__thunk_named_foo_");
752 FunctionDecl *FD = FunctionDecl::Create(getContext(),
753 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000754 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000755 Extern
756 ? FunctionDecl::Extern
757 : FunctionDecl::Static,
758 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000759 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
760
761 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000762 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
763 const llvm::Type *Ty =
764 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
765 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000766 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000767
Mike Stump33ccd9e2009-11-02 23:22:01 +0000768 CallArgList CallArgs;
769
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000770 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000771 QualType ArgType = MD->getThisType(getContext());
772 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000773 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000774 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000775 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000776 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
777
778 if (!Adjustment.ReturnAdjustment.isEmpty()) {
779 const CovariantThunkAdjustment &ReturnAdjustment =
780 CovariantThunkAdjustment(ThunkAdjustment(),
781 Adjustment.ReturnAdjustment);
782
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000783 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000784
Mike Stump71609a22009-11-04 00:53:51 +0000785 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000786 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000787 }
788 }
789
Mike Stumpf3589722009-11-03 02:12:59 +0000790 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
791
Mike Stump33ccd9e2009-11-02 23:22:01 +0000792 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
793 e = MD->param_end();
794 i != e; ++i) {
795 ParmVarDecl *D = *i;
796 QualType ArgType = D->getType();
797
798 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000799 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
800 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000801 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
802 }
803
Mike Stump31e1d432009-11-02 23:47:45 +0000804 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
805 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000806 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000807 bool CanBeZero = !(ResultType->isReferenceType()
808 // FIXME: attr nonnull can't be zero either
809 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000810 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000811 if (CanBeZero) {
812 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
813 llvm::BasicBlock *ZeroBlock = createBasicBlock();
814 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000815
Mike Stumpc5507682009-11-05 06:32:02 +0000816 const llvm::Type *Ty = RV.getScalarVal()->getType();
817 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
818 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
819 NonZeroBlock, ZeroBlock);
820 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000821 llvm::Value *NZ =
822 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000823 EmitBranch(ContBlock);
824 EmitBlock(ZeroBlock);
825 llvm::Value *Z = RV.getScalarVal();
826 EmitBlock(ContBlock);
827 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
828 RVOrZero->reserveOperandSpace(2);
829 RVOrZero->addIncoming(NZ, NonZeroBlock);
830 RVOrZero->addIncoming(Z, ZeroBlock);
831 RV = RValue::get(RVOrZero);
832 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000833 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
834 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000835 }
836
Mike Stump31e1d432009-11-02 23:47:45 +0000837 if (!ResultType->isVoidType())
838 EmitReturnOfRValue(RV, ResultType);
839
Mike Stump80f6ac52009-09-11 23:25:56 +0000840 FinishFunction();
841 return Fn;
842}
843
Anders Carlssonc7785402009-11-26 02:32:05 +0000844llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000845CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
846 const ThunkAdjustment &ThisAdjustment) {
847 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
848
849 // Compute mangled name
850 llvm::SmallString<256> OutName;
851 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
852 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
853 OutName);
854 else
855 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
856 OutName += '\0';
857 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
858
859 // Get function for mangled name
860 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
861 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
862}
863
864llvm::Constant *
865CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
866 const CovariantThunkAdjustment &Adjustment) {
867 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
868
869 // Compute mangled name
870 llvm::SmallString<256> OutName;
871 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
872 OutName += '\0';
873 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
874
875 // Get function for mangled name
876 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
877 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
878}
879
880void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000881 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
882 if (!AdjPtr)
883 return;
884 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000885 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000886 for (unsigned i = 0; i < Adj.size(); i++) {
887 GlobalDecl OGD = Adj[i].first;
888 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000889 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
890 CanQualType oret = getContext().getCanonicalType(nc_oret);
891 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
892 CanQualType ret = getContext().getCanonicalType(nc_ret);
893 ThunkAdjustment ReturnAdjustment;
894 if (oret != ret) {
895 QualType qD = nc_ret->getPointeeType();
896 QualType qB = nc_oret->getPointeeType();
897 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
898 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
899 ReturnAdjustment = ComputeThunkAdjustment(D, B);
900 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000901 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000902 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
903 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
904 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
905 llvm::Constant *FnConst;
906 if (!ReturnAdjustment.isEmpty())
907 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
908 else
909 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
910 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000911 llvm::Constant *SubExpr =
912 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
913 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
914 std::string Name = OldFn->getNameStr();
915 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
916 Name.data() + Name.size() + 1));
917 llvm::Constant *NewFnConst;
918 if (!ReturnAdjustment.isEmpty())
919 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
920 else
921 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
922 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
923 NewFn->takeName(OldFn);
924 llvm::Constant *NewPtrForOldDecl =
925 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
926 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
927 OldFn->eraseFromParent();
928 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000929 }
930 llvm::Function *Fn = cast<llvm::Function>(FnConst);
931 if (Fn->isDeclaration()) {
932 llvm::GlobalVariable::LinkageTypes linktype;
933 linktype = llvm::GlobalValue::WeakAnyLinkage;
934 if (!Extern)
935 linktype = llvm::GlobalValue::InternalLinkage;
936 Fn->setLinkage(linktype);
937 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
938 Fn->addFnAttr(llvm::Attribute::NoUnwind);
939 Fn->setAlignment(2);
940 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
941 }
942 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000943 }
944}
945
946llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000947CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000948 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000949 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000950 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000951 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
952 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
953 OutName);
954 } else
955 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000956
Mike Stump5a522352009-09-04 18:27:16 +0000957 llvm::GlobalVariable::LinkageTypes linktype;
958 linktype = llvm::GlobalValue::WeakAnyLinkage;
959 if (!Extern)
960 linktype = llvm::GlobalValue::InternalLinkage;
961 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000962 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000963 const llvm::FunctionType *FTy =
964 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
965 FPT->isVariadic());
966
Daniel Dunbare128dd12009-11-21 09:06:22 +0000967 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000968 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000969 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000970 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
971 return m;
972}
973
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000974llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000975CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000976 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000977 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000978 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000979 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000980 llvm::GlobalVariable::LinkageTypes linktype;
981 linktype = llvm::GlobalValue::WeakAnyLinkage;
982 if (!Extern)
983 linktype = llvm::GlobalValue::InternalLinkage;
984 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000985 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000986 const llvm::FunctionType *FTy =
987 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
988 FPT->isVariadic());
989
Daniel Dunbare128dd12009-11-21 09:06:22 +0000990 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000991 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000992 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000993 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
994 return m;
995}
996
Mike Stumpa5588bf2009-08-26 20:46:33 +0000997llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000998CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
999 const CXXRecordDecl *ClassDecl,
1000 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001001 const llvm::Type *Int8PtrTy =
1002 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1003
1004 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1005 Int8PtrTy->getPointerTo());
1006 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1007
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001008 int64_t VBaseOffsetIndex =
1009 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1010
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001011 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001012 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001013 const llvm::Type *PtrDiffTy =
1014 ConvertType(getContext().getPointerDiffType());
1015
1016 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1017 PtrDiffTy->getPointerTo());
1018
1019 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1020
1021 return VBaseOffset;
1022}
1023
Anders Carlssonf942ee02009-11-27 20:47:55 +00001024static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001025 llvm::Value *This, const llvm::Type *Ty) {
1026 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001027
Anders Carlssone828c362009-11-13 04:45:41 +00001028 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1029 Vtable = CGF.Builder.CreateLoad(Vtable);
1030
1031 llvm::Value *VFuncPtr =
1032 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1033 return CGF.Builder.CreateLoad(VFuncPtr);
1034}
1035
1036llvm::Value *
1037CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1038 const llvm::Type *Ty) {
1039 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001040 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001041
1042 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1043}
1044
1045llvm::Value *
1046CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1047 llvm::Value *&This, const llvm::Type *Ty) {
1048 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001049 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001050 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001051
1052 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001053}
1054
Fariborz Jahanian56263842009-08-21 18:30:26 +00001055/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1056/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1057/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001058// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001059void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001060 llvm::Value *Src,
1061 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001062 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001063 QualType Ty) {
1064 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1065 assert(CA && "VLA cannot be copied over");
1066 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001067
Fariborz Jahanian56263842009-08-21 18:30:26 +00001068 // Create a temporary for the loop index and initialize it with 0.
1069 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1070 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001071 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001072 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001073 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001074 // Start the loop with a block that tests the condition.
1075 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1076 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001077
Fariborz Jahanian56263842009-08-21 18:30:26 +00001078 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001079
Fariborz Jahanian56263842009-08-21 18:30:26 +00001080 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1081 // Generate: if (loop-index < number-of-elements fall to the loop body,
1082 // otherwise, go to the block after the for-loop.
1083 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001084 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001085 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1086 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001087 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001088 "isless");
1089 // If the condition is true, execute the body.
1090 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001091
Fariborz Jahanian56263842009-08-21 18:30:26 +00001092 EmitBlock(ForBody);
1093 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1094 // Inside the loop body, emit the constructor call on the array element.
1095 Counter = Builder.CreateLoad(IndexPtr);
1096 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1097 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1098 if (BitwiseCopy)
1099 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001100 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001101 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001102 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001103 Ctor_Complete);
1104 CallArgList CallArgs;
1105 // Push the this (Dest) ptr.
1106 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1107 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001108
Fariborz Jahanian56263842009-08-21 18:30:26 +00001109 // Push the Src ptr.
1110 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001111 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001112 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001113 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001114 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1115 Callee, CallArgs, BaseCopyCtor);
1116 }
1117 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Fariborz Jahanian56263842009-08-21 18:30:26 +00001119 // Emit the increment of the loop counter.
1120 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1121 Counter = Builder.CreateLoad(IndexPtr);
1122 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001123 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001124
Fariborz Jahanian56263842009-08-21 18:30:26 +00001125 // Finally, branch back up to the condition for the next iteration.
1126 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Fariborz Jahanian56263842009-08-21 18:30:26 +00001128 // Emit the fall-through block.
1129 EmitBlock(AfterFor, true);
1130}
1131
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001132/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001133/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001134/// bitwise assignment or via a copy assignment operator function call.
1135/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001136void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001137 llvm::Value *Src,
1138 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001139 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001140 QualType Ty) {
1141 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1142 assert(CA && "VLA cannot be asssigned");
1143 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001144
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001145 // Create a temporary for the loop index and initialize it with 0.
1146 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1147 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001148 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001149 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001150 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001151 // Start the loop with a block that tests the condition.
1152 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1153 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001154
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001155 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001156
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001157 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1158 // Generate: if (loop-index < number-of-elements fall to the loop body,
1159 // otherwise, go to the block after the for-loop.
1160 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001161 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001162 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1163 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001164 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001165 "isless");
1166 // If the condition is true, execute the body.
1167 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001169 EmitBlock(ForBody);
1170 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1171 // Inside the loop body, emit the assignment operator call on array element.
1172 Counter = Builder.CreateLoad(IndexPtr);
1173 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1174 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1175 const CXXMethodDecl *MD = 0;
1176 if (BitwiseAssign)
1177 EmitAggregateCopy(Dest, Src, Ty);
1178 else {
1179 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1180 MD);
1181 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1182 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001183 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001184 const llvm::Type *LTy =
1185 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1186 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001187 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001189 CallArgList CallArgs;
1190 // Push the this (Dest) ptr.
1191 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1192 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001193
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001194 // Push the Src ptr.
1195 CallArgs.push_back(std::make_pair(RValue::get(Src),
1196 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001197 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001198 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1199 Callee, CallArgs, MD);
1200 }
1201 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001202
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001203 // Emit the increment of the loop counter.
1204 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1205 Counter = Builder.CreateLoad(IndexPtr);
1206 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001207 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001208
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001209 // Finally, branch back up to the condition for the next iteration.
1210 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001211
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001212 // Emit the fall-through block.
1213 EmitBlock(AfterFor, true);
1214}
1215
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001216/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1217/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001218/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001219void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001220 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001221 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001222 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1223 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001224 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1225 /*NullCheckValue=*/false);
1226 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1227 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001228 }
1229 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1230 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001231 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001232 }
Mike Stump11289f42009-09-09 15:08:12 +00001233
1234 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001235 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001236 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001237 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001238 CallArgList CallArgs;
1239 // Push the this (Dest) ptr.
1240 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1241 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001242
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001243 // Push the Src ptr.
1244 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001245 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001246 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001247 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001248 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1249 Callee, CallArgs, BaseCopyCtor);
1250 }
1251}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001252
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001253/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001254/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001255/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001256// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001257void CodeGenFunction::EmitClassCopyAssignment(
1258 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001259 const CXXRecordDecl *ClassDecl,
1260 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001261 QualType Ty) {
1262 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001263 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1264 /*NullCheckValue=*/false);
1265 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1266 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001267 }
1268 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1269 EmitAggregateCopy(Dest, Src, Ty);
1270 return;
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001273 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001274 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001275 MD);
1276 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1277 (void)ConstCopyAssignOp;
1278
John McCall9dd450b2009-09-21 23:43:11 +00001279 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001280 const llvm::Type *LTy =
1281 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001282 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001283 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001284
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001285 CallArgList CallArgs;
1286 // Push the this (Dest) ptr.
1287 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1288 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001289
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001290 // Push the Src ptr.
1291 CallArgs.push_back(std::make_pair(RValue::get(Src),
1292 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001293 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001294 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001295 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1296 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001297}
1298
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001299/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001300void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001301CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1302 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001303 llvm::Function *Fn,
1304 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001305 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001306 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1307 SourceLocation());
1308 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001309 FinishFunction();
1310}
1311
Mike Stumpb9c9b352009-11-04 01:11:15 +00001312/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1313/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001314/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001315/// copy of its subobjects. The order of copying is the same as the order of
1316/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001317/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001318/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001319/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001320/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001321/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001322/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001323/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001324/// Virtual base class subobjects shall be copied only once by the
1325/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001326
Anders Carlssonddf57d32009-09-14 05:32:02 +00001327void
1328CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1329 CXXCtorType Type,
1330 llvm::Function *Fn,
1331 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001332 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001333 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001334 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001335 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001336 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1337 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001338
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001339 FunctionArgList::const_iterator i = Args.begin();
1340 const VarDecl *ThisArg = i->first;
1341 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1342 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1343 const VarDecl *SrcArg = (i+1)->first;
1344 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1345 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001347 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1348 Base != ClassDecl->bases_end(); ++Base) {
1349 // FIXME. copy constrution of virtual base NYI
1350 if (Base->isVirtual())
1351 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001352
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001353 CXXRecordDecl *BaseClassDecl
1354 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001355 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1356 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001359 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1360 E = ClassDecl->field_end(); I != E; ++I) {
1361 const FieldDecl *Field = *I;
1362
1363 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001364 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001365 getContext().getAsConstantArrayType(FieldType);
1366 if (Array)
1367 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001369 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1370 CXXRecordDecl *FieldClassDecl
1371 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001372 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1373 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001374 if (Array) {
1375 const llvm::Type *BasePtr = ConvertType(FieldType);
1376 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001377 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001378 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001379 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001380 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1381 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1382 FieldClassDecl, FieldType);
1383 }
Mike Stump11289f42009-09-09 15:08:12 +00001384 else
1385 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001386 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001387 continue;
1388 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001389
1390 if (Field->getType()->isReferenceType()) {
1391 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1392
1393 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1394 "lhs.ref");
1395
1396 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1397 "rhs.ref");
1398
1399 // Load the value in RHS.
1400 RHS = Builder.CreateLoad(RHS);
1401
1402 // And store it in the LHS
1403 Builder.CreateStore(RHS, LHS);
1404
1405 continue;
1406 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001407 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001408 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1409 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1410
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001411 if (!hasAggregateLLVMType(Field->getType())) {
1412 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1413 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1414 } else if (Field->getType()->isAnyComplexType()) {
1415 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1416 RHS.isVolatileQualified());
1417 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1418 } else {
1419 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1420 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001421 }
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001422
1423 InitializeVtablePtrs(ClassDecl);
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001424 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001425}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001426
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001427/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001428/// Before the implicitly-declared copy assignment operator for a class is
1429/// implicitly defined, all implicitly- declared copy assignment operators for
1430/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001431/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001432/// The implicitly-defined copy assignment operator for class X performs
1433/// memberwise assignment of its subob- jects. The direct base classes of X are
1434/// assigned first, in the order of their declaration in
1435/// the base-specifier-list, and then the immediate nonstatic data members of X
1436/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001437/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001438/// if the subobject is of class type, the copy assignment operator for the
1439/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001440/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001441///
Mike Stump11289f42009-09-09 15:08:12 +00001442/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001443/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001444///
Mike Stump11289f42009-09-09 15:08:12 +00001445/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001446/// used.
1447void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001448 llvm::Function *Fn,
1449 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001450
1451 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1452 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1453 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001454 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001455
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001456 FunctionArgList::const_iterator i = Args.begin();
1457 const VarDecl *ThisArg = i->first;
1458 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1459 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1460 const VarDecl *SrcArg = (i+1)->first;
1461 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1462 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001463
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001464 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1465 Base != ClassDecl->bases_end(); ++Base) {
1466 // FIXME. copy assignment of virtual base NYI
1467 if (Base->isVirtual())
1468 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001469
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001470 CXXRecordDecl *BaseClassDecl
1471 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1472 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1473 Base->getType());
1474 }
Mike Stump11289f42009-09-09 15:08:12 +00001475
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001476 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1477 FieldEnd = ClassDecl->field_end();
1478 Field != FieldEnd; ++Field) {
1479 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001480 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001481 getContext().getAsConstantArrayType(FieldType);
1482 if (Array)
1483 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001484
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001485 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1486 CXXRecordDecl *FieldClassDecl
1487 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1488 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1489 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001490 if (Array) {
1491 const llvm::Type *BasePtr = ConvertType(FieldType);
1492 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1493 llvm::Value *DestBaseAddrPtr =
1494 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1495 llvm::Value *SrcBaseAddrPtr =
1496 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1497 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1498 FieldClassDecl, FieldType);
1499 }
1500 else
Mike Stump11289f42009-09-09 15:08:12 +00001501 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001502 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001503 continue;
1504 }
1505 // Do a built-in assignment of scalar data members.
1506 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1507 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001508 if (!hasAggregateLLVMType(Field->getType())) {
1509 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1510 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1511 } else if (Field->getType()->isAnyComplexType()) {
1512 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1513 RHS.isVolatileQualified());
1514 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1515 } else {
1516 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1517 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001520 // return *this;
1521 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001523 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001524}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001525
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001526static void EmitBaseInitializer(CodeGenFunction &CGF,
1527 const CXXRecordDecl *ClassDecl,
1528 CXXBaseOrMemberInitializer *BaseInit,
1529 CXXCtorType CtorType) {
1530 assert(BaseInit->isBaseInitializer() &&
1531 "Must have base initializer!");
1532
1533 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1534
1535 const Type *BaseType = BaseInit->getBaseClass();
1536 CXXRecordDecl *BaseClassDecl =
1537 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Eli Friedman303e4572009-12-18 23:27:44 +00001538
1539 // FIXME: This method of determining whether a base is virtual is ridiculous;
1540 // it should be part of BaseInit.
1541 bool isBaseVirtual = false;
1542 for (CXXRecordDecl::base_class_const_iterator I = ClassDecl->vbases_begin(),
1543 E = ClassDecl->vbases_end(); I != E; ++I)
1544 if (I->getType()->getAs<RecordType>()->getDecl() == BaseClassDecl) {
1545 isBaseVirtual = true;
1546 break;
1547 }
1548
1549 // The base constructor doesn't construct virtual bases.
1550 if (CtorType == Ctor_Base && isBaseVirtual)
1551 return;
1552
1553 // Compute the offset to the base; we do this directly instead of using
1554 // GetAddressOfBaseClass because the class doesn't have a vtable pointer
1555 // at this point.
1556 // FIXME: This could be refactored back into GetAddressOfBaseClass if it took
1557 // an extra parameter for whether the derived class is the complete object
1558 // class.
1559 const ASTRecordLayout &Layout =
1560 CGF.getContext().getASTRecordLayout(ClassDecl);
1561 uint64_t Offset;
1562 if (isBaseVirtual)
1563 Offset = Layout.getVBaseClassOffset(BaseClassDecl);
1564 else
1565 Offset = Layout.getBaseClassOffset(BaseClassDecl);
1566 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1567 const llvm::Type *BaseClassType = CGF.ConvertType(QualType(BaseType, 0));
1568 llvm::Value *V = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
1569 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, Offset/8);
1570 V = CGF.Builder.CreateBitCast(V, BaseClassType->getPointerTo());
1571
1572 // FIXME: This should always use Ctor_Base as the ctor type! (But that
1573 // causes crashes in tests.)
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001574 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1575 CtorType, V,
1576 BaseInit->const_arg_begin(),
1577 BaseInit->const_arg_end());
1578}
1579
1580static void EmitMemberInitializer(CodeGenFunction &CGF,
1581 const CXXRecordDecl *ClassDecl,
1582 CXXBaseOrMemberInitializer *MemberInit) {
1583 assert(MemberInit->isMemberInitializer() &&
1584 "Must have member initializer!");
1585
1586 // non-static data member initializers.
1587 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001588 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001589
1590 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1591 LValue LHS;
1592 if (FieldType->isReferenceType()) {
1593 // FIXME: This is really ugly; should be refactored somehow
1594 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1595 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1596 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1597 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1598 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001599 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001600 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001601
1602 // If we are initializing an anonymous union field, drill down to the field.
1603 if (MemberInit->getAnonUnionMember()) {
1604 Field = MemberInit->getAnonUnionMember();
1605 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1606 /*IsUnion=*/true, 0);
1607 FieldType = Field->getType();
1608 }
1609
1610 // If the field is an array, branch based on the element type.
1611 const ConstantArrayType *Array =
1612 CGF.getContext().getAsConstantArrayType(FieldType);
1613 if (Array)
1614 FieldType = CGF.getContext().getBaseElementType(FieldType);
1615
Eli Friedmane85ef712009-11-16 23:53:01 +00001616 // We lose the constructor for anonymous union members, so handle them
1617 // explicitly.
1618 // FIXME: This is somwhat ugly.
1619 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1620 if (MemberInit->getNumArgs())
1621 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1622 LHS.isVolatileQualified());
1623 else
1624 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1625 return;
1626 }
1627
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001628 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001629 assert(MemberInit->getConstructor() &&
1630 "EmitCtorPrologue - no constructor to initialize member");
1631 if (Array) {
1632 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1633 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1634 llvm::Value *BaseAddrPtr =
1635 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1636 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001637 Array, BaseAddrPtr,
1638 MemberInit->const_arg_begin(),
1639 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001640 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001641 else
1642 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1643 Ctor_Complete, LHS.getAddress(),
1644 MemberInit->const_arg_begin(),
1645 MemberInit->const_arg_end());
1646 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001647 }
1648
1649 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1650 Expr *RhsExpr = *MemberInit->arg_begin();
1651 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001652 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001653 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1654 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001655 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001656 } else if (Array) {
1657 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1658 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1659 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1660 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1661 } else if (RhsExpr->getType()->isAnyComplexType()) {
1662 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1663 LHS.isVolatileQualified());
1664 } else {
1665 // Handle member function pointers; other aggregates shouldn't get this far.
1666 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1667 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001668}
1669
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001670/// EmitCtorPrologue - This routine generates necessary code to initialize
1671/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001672/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001673void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1674 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001675 const CXXRecordDecl *ClassDecl = CD->getParent();
1676
Mike Stump6b2556f2009-08-06 13:41:24 +00001677 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001678
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001679 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001680 E = CD->init_end();
1681 B != E; ++B) {
1682 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001683
Anders Carlsson5852b132009-11-06 04:11:09 +00001684 assert(LiveTemporaries.empty() &&
1685 "Should not have any live temporaries at initializer start!");
1686
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001687 if (Member->isBaseInitializer())
1688 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1689 else
1690 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001691
1692 // Pop any live temporaries that the initializers might have pushed.
1693 while (!LiveTemporaries.empty())
1694 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001695 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001696
Eli Friedman80888c72009-12-08 06:54:20 +00001697 InitializeVtablePtrs(ClassDecl);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001698}
1699
1700void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001701 if (!ClassDecl->isDynamicClass())
1702 return;
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001703
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001704 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
Eli Friedman70724ad2009-12-18 23:47:41 +00001705 CodeGenModule::AddrSubMap_t& AddressPoints =
1706 *(*CGM.AddressPoints[ClassDecl])[ClassDecl];
1707 llvm::Value *ThisPtr = LoadCXXThis();
1708 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001709
Eli Friedman70724ad2009-12-18 23:47:41 +00001710 // Store address points for virtual bases
1711 for (CXXRecordDecl::base_class_const_iterator I =
1712 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); I != E; ++I) {
1713 const CXXBaseSpecifier &Base = *I;
1714 CXXRecordDecl *BaseClassDecl
1715 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1716 uint64_t Offset = Layout.getVBaseClassOffset(BaseClassDecl);
1717 InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1718 ThisPtr, Offset);
1719 }
1720
1721 // Store address points for non-virtual bases and current class
1722 InitializeVtablePtrsRecursive(ClassDecl, Vtable, AddressPoints, ThisPtr, 0);
1723}
1724
1725void CodeGenFunction::InitializeVtablePtrsRecursive(
1726 const CXXRecordDecl *ClassDecl,
1727 llvm::Constant *Vtable,
1728 CodeGenModule::AddrSubMap_t& AddressPoints,
1729 llvm::Value *ThisPtr,
1730 uint64_t Offset) {
1731 if (!ClassDecl->isDynamicClass())
1732 return;
1733
1734 // Store address points for non-virtual bases
1735 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
1736 for (CXXRecordDecl::base_class_const_iterator I =
1737 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1738 const CXXBaseSpecifier &Base = *I;
1739 if (Base.isVirtual())
1740 continue;
1741 CXXRecordDecl *BaseClassDecl
1742 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1743 uint64_t NewOffset = Offset + Layout.getBaseClassOffset(BaseClassDecl);
1744 InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1745 ThisPtr, NewOffset);
1746 }
1747
1748 // Compute the address point
1749 uint64_t AddressPoint = AddressPoints[std::make_pair(ClassDecl, Offset)];
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001750 llvm::Value *VtableAddressPoint =
Eli Friedman70724ad2009-12-18 23:47:41 +00001751 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1752
1753 // Compute the address to store the address point
1754 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
1755 llvm::Value *VtableField = Builder.CreateBitCast(ThisPtr, Int8PtrTy);
1756 VtableField = Builder.CreateConstInBoundsGEP1_64(VtableField, Offset/8);
1757 const llvm::Type *AddressPointPtrTy =
1758 VtableAddressPoint->getType()->getPointerTo();
1759 VtableField = Builder.CreateBitCast(ThisPtr, AddressPointPtrTy);
1760
1761 // Store address point
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001762 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001763}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001764
1765/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001766/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001767/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001768/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001769void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1770 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001771 assert(!DD->isTrivial() &&
1772 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001773
Anders Carlssondee9a302009-11-17 04:44:12 +00001774 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001775
Anders Carlssondee9a302009-11-17 04:44:12 +00001776 // Collect the fields.
1777 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1778 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1779 E = ClassDecl->field_end(); I != E; ++I) {
1780 const FieldDecl *Field = *I;
1781
1782 QualType FieldType = getContext().getCanonicalType(Field->getType());
1783 FieldType = getContext().getBaseElementType(FieldType);
1784
1785 const RecordType *RT = FieldType->getAs<RecordType>();
1786 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001787 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001788
1789 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1790 if (FieldClassDecl->hasTrivialDestructor())
1791 continue;
1792
1793 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001794 }
Anders Carlssond7872042009-11-15 23:03:25 +00001795
Anders Carlssondee9a302009-11-17 04:44:12 +00001796 // Now destroy the fields.
1797 for (size_t i = FieldDecls.size(); i > 0; --i) {
1798 const FieldDecl *Field = FieldDecls[i - 1];
1799
1800 QualType FieldType = Field->getType();
1801 const ConstantArrayType *Array =
1802 getContext().getAsConstantArrayType(FieldType);
1803 if (Array)
1804 FieldType = getContext().getBaseElementType(FieldType);
1805
1806 const RecordType *RT = FieldType->getAs<RecordType>();
1807 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1808
1809 llvm::Value *ThisPtr = LoadCXXThis();
1810
1811 LValue LHS = EmitLValueForField(ThisPtr, Field,
1812 /*isUnion=*/false,
1813 // FIXME: Qualifiers?
1814 /*CVRQualifiers=*/0);
1815 if (Array) {
1816 const llvm::Type *BasePtr = ConvertType(FieldType);
1817 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1818 llvm::Value *BaseAddrPtr =
1819 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1820 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1821 Array, BaseAddrPtr);
1822 } else
1823 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1824 Dtor_Complete, LHS.getAddress());
1825 }
1826
1827 // Destroy non-virtual bases.
1828 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1829 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1830 const CXXBaseSpecifier &Base = *I;
1831
1832 // Ignore virtual bases.
1833 if (Base.isVirtual())
1834 continue;
1835
1836 CXXRecordDecl *BaseClassDecl
1837 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1838
1839 // Ignore trivial destructors.
1840 if (BaseClassDecl->hasTrivialDestructor())
1841 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001842 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1843
Anders Carlsson8c793172009-11-23 17:57:54 +00001844 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1845 ClassDecl, BaseClassDecl,
1846 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001847 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001848 }
1849
1850 // If we're emitting a base destructor, we don't want to emit calls to the
1851 // virtual bases.
1852 if (DtorType == Dtor_Base)
1853 return;
1854
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001855 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001856 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1857 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001858 const CXXBaseSpecifier &Base = *I;
1859 CXXRecordDecl *BaseClassDecl
1860 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1861
1862 // Ignore trivial destructors.
1863 if (BaseClassDecl->hasTrivialDestructor())
1864 continue;
1865 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1866 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1867 ClassDecl, BaseClassDecl,
1868 /*NullCheckValue=*/false);
1869 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001870 }
1871
1872 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001873 if (DtorType == Dtor_Deleting) {
1874 assert(DD->getOperatorDelete() &&
1875 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001876 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1877 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001878 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001879}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001880
Anders Carlssonddf57d32009-09-14 05:32:02 +00001881void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1882 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001883 llvm::Function *Fn,
1884 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001885 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001886 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001887
Anders Carlssonddf57d32009-09-14 05:32:02 +00001888 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1889 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001890
Anders Carlssonddf57d32009-09-14 05:32:02 +00001891 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001892 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001893}