blob: 4f0d9a0c5cdbbacd591b83f199679f332fd7e615 [file] [log] [blame]
Anders Carlssone1b29ef2008-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
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbar0096acf2009-02-25 19:24:29 +000028void
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson0032b272009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson0032b272009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlsson622f9dc2009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlsson89ed31d2009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson0032b272009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer10c40ee2009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000136
Anders Carlsson283a0622009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson0032b272009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson0032b272009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar77659342009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000147
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson0032b272009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson0032b272009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar55e87422008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson0032b272009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000171}
172
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
Douglas Gregor4fe95f92009-09-04 19:04:08 +0000181 // A call to a trivial destructor requires no code generation.
182 if (const CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(MD))
183 if (Destructor->isTrivial())
184 return RValue::get(0);
185
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000186 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
187
188 CallArgList Args;
189
190 // Push the this ptr.
191 Args.push_back(std::make_pair(RValue::get(This),
192 MD->getThisType(getContext())));
193
194 // And the rest of the call args
195 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
196
197 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
198 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
199 Callee, Args, MD);
200}
201
Anders Carlsson774e7c62009-04-03 22:50:24 +0000202RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
203 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
204 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000205
Anders Carlssone9918d22009-04-08 20:31:57 +0000206 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000207
Anders Carlsson774e7c62009-04-03 22:50:24 +0000208 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000209 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
210 FPT->isVariadic());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000211 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000212
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000214 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000215 else {
216 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000217 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000218 }
Mike Stumpf0070db2009-08-26 20:46:33 +0000219
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000220 // C++ [class.virtual]p12:
221 // Explicit qualification with the scope operator (5.1) suppresses the
222 // virtual call mechanism.
Mike Stumpf0070db2009-08-26 20:46:33 +0000223 llvm::Value *Callee;
Douglas Gregor0979c802009-08-31 21:41:48 +0000224 if (MD->isVirtual() && !ME->hasQualifier())
Mike Stumpf0070db2009-08-26 20:46:33 +0000225 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregor4fe95f92009-09-04 19:04:08 +0000226 else if (const CXXDestructorDecl *Destructor
227 = dyn_cast<CXXDestructorDecl>(MD))
228 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
Douglas Gregor0979c802009-08-31 21:41:48 +0000229 else
Mike Stumpf0070db2009-08-26 20:46:33 +0000230 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000231
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000232 return EmitCXXMemberCall(MD, Callee, This,
233 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000234}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000235
Anders Carlsson0f294632009-05-27 04:18:27 +0000236RValue
237CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
238 const CXXMethodDecl *MD) {
239 assert(MD->isInstance() &&
240 "Trying to emit a member call expr on a static method!");
241
Fariborz Jahanianad258832009-08-13 21:09:41 +0000242 if (MD->isCopyAssignment()) {
243 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
244 if (ClassDecl->hasTrivialCopyAssignment()) {
245 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
246 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
247 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
248 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
249 QualType Ty = E->getType();
250 EmitAggregateCopy(This, Src, Ty);
251 return RValue::get(This);
252 }
253 }
Anders Carlsson0f294632009-05-27 04:18:27 +0000254
255 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
256 const llvm::Type *Ty =
Mike Stumped032eb2009-09-04 18:27:16 +0000257 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
258 FPT->isVariadic());
Anders Carlsson0f294632009-05-27 04:18:27 +0000259 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
260
261 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
262
263 return EmitCXXMemberCall(MD, Callee, This,
264 E->arg_begin() + 1, E->arg_end());
265}
266
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000267RValue
268CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
269 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
270 "EmitCXXFunctionalCastExpr - called with wrong cast");
271
272 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000273 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
274 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
275 " method decl");
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000276 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000277
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000278 const llvm::Type *Ty =
279 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
280 FPT->isVariadic());
281 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
282 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
283 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
284 if (RV.isAggregate())
285 RV = RValue::get(RV.getAggregateAddr());
286 return RV;
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000287}
288
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000289llvm::Value *CodeGenFunction::LoadCXXThis() {
290 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
291 "Must be in a C++ member function decl to load 'this'");
292 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
293 "Must be in a C++ member function decl to load 'this'");
294
295 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000296 // ans: See how CodeGenFunction::LoadObjCSelf() uses
297 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000298 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
299}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000300
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000301static bool
302GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
303 const CXXRecordDecl *ClassDecl,
304 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000305 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
306 e = ClassDecl->bases_end(); i != e; ++i) {
307 if (i->isVirtual())
308 continue;
309 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000310 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000311 if (Base == BaseClassDecl) {
312 NestedBasePaths.push_back(BaseClassDecl);
313 return true;
314 }
315 }
316 // BaseClassDecl not an immediate base of ClassDecl.
317 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
318 e = ClassDecl->bases_end(); i != e; ++i) {
319 if (i->isVirtual())
320 continue;
321 const CXXRecordDecl *Base =
322 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
323 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
324 NestedBasePaths.push_back(Base);
325 return true;
326 }
327 }
328 return false;
329}
330
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000331llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000332 const CXXRecordDecl *ClassDecl,
333 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000334 if (ClassDecl == BaseClassDecl)
335 return BaseValue;
336
Owen Anderson0032b272009-08-13 21:57:51 +0000337 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000338 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
339 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
340 assert(NestedBasePaths.size() > 0 &&
341 "AddressCXXOfBaseClass - inheritence path failed");
342 NestedBasePaths.push_back(ClassDecl);
343 uint64_t Offset = 0;
344
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000345 // Accessing a member of the base class. Must add delata to
346 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000347 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
348 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
349 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
350 const ASTRecordLayout &Layout =
351 getContext().getASTRecordLayout(DerivedClass);
352 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
353 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000354 llvm::Value *OffsetVal =
355 llvm::ConstantInt::get(
356 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000357 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
358 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
359 QualType BTy =
360 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000361 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000362 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000363 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000364 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
365 return BaseValue;
366}
367
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000368/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
369/// for-loop to call the default constructor on individual members of the
370/// array. 'Array' is the array type, 'This' is llvm pointer of the start
371/// of the array and 'D' is the default costructor Decl for elements of the
372/// array. It is assumed that all relevant checks have been made by the
373/// caller.
374void
375CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
376 const ArrayType *Array,
377 llvm::Value *This) {
378 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
379 assert(CA && "Do we support VLA for construction ?");
380
381 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000382 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000383 "loop.index");
384 llvm::Value* zeroConstant =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000385 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000386 Builder.CreateStore(zeroConstant, IndexPtr, false);
387
388 // Start the loop with a block that tests the condition.
389 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
390 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
391
392 EmitBlock(CondBlock);
393
394 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
395
396 // Generate: if (loop-index < number-of-elements fall to the loop body,
397 // otherwise, go to the block after the for-loop.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000398 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000399 llvm::Value * NumElementsPtr =
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000400 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000401 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
402 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
403 "isless");
404 // If the condition is true, execute the body.
405 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
406
407 EmitBlock(ForBody);
408
409 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000410 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000411 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000412 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
413 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000414
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000415 EmitBlock(ContinueBlock);
416
417 // Emit the increment of the loop counter.
418 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
419 Counter = Builder.CreateLoad(IndexPtr);
420 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
421 Builder.CreateStore(NextVal, IndexPtr, false);
422
423 // Finally, branch back up to the condition for the next iteration.
424 EmitBranch(CondBlock);
425
426 // Emit the fall-through block.
427 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000428}
429
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000430/// EmitCXXAggrDestructorCall - calls the default destructor on array
431/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000432void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000433CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
434 const ArrayType *Array,
435 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000436 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
437 assert(CA && "Do we support VLA for destruction ?");
438 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
439 1);
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000440 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000441 // Create a temporary for the loop index and initialize it with count of
442 // array elements.
443 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
444 "loop.index");
445 // Index = ElementCount;
446 llvm::Value* UpperCount =
447 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
448 Builder.CreateStore(UpperCount, IndexPtr, false);
449
450 // Start the loop with a block that tests the condition.
451 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
452 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
453
454 EmitBlock(CondBlock);
455
456 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
457
458 // Generate: if (loop-index != 0 fall to the loop body,
459 // otherwise, go to the block after the for-loop.
460 llvm::Value* zeroConstant =
461 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
462 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
463 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
464 "isne");
465 // If the condition is true, execute the body.
466 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
467
468 EmitBlock(ForBody);
469
470 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
471 // Inside the loop body, emit the constructor call on the array element.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One);
474 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
475 EmitCXXDestructorCall(D, Dtor_Complete, Address);
476
477 EmitBlock(ContinueBlock);
478
479 // Emit the decrement of the loop counter.
480 Counter = Builder.CreateLoad(IndexPtr);
481 Counter = Builder.CreateSub(Counter, One, "dec");
482 Builder.CreateStore(Counter, IndexPtr, false);
483
484 // Finally, branch back up to the condition for the next iteration.
485 EmitBranch(CondBlock);
486
487 // Emit the fall-through block.
488 EmitBlock(AfterFor, true);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000489}
490
491void
Anders Carlssonb14095a2009-04-17 00:06:03 +0000492CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
493 CXXCtorType Type,
494 llvm::Value *This,
495 CallExpr::const_arg_iterator ArgBeg,
496 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000497 if (D->isCopyConstructor(getContext())) {
498 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
499 if (ClassDecl->hasTrivialCopyConstructor()) {
500 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
501 "EmitCXXConstructorCall - user declared copy constructor");
502 const Expr *E = (*ArgBeg);
503 QualType Ty = E->getType();
504 llvm::Value *Src = EmitLValue(E).getAddress();
505 EmitAggregateCopy(This, Src, Ty);
506 return;
507 }
508 }
509
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000510 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000513}
514
Anders Carlsson7267c162009-05-29 21:03:38 +0000515void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
516 CXXDtorType Type,
517 llvm::Value *This) {
518 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
519
520 EmitCXXMemberCall(D, Callee, This, 0, 0);
521}
522
Anders Carlssonb14095a2009-04-17 00:06:03 +0000523void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000524CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
525 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000526 assert(Dest && "Must have a destination!");
527
528 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000529 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000530 if (RD->hasTrivialConstructor())
531 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000532
533 // Code gen optimization to eliminate copy constructor and return
534 // its first argument instead.
Anders Carlsson92f58222009-08-22 22:30:33 +0000535 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000536 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000537 EmitAggExpr((*i), Dest, false);
538 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000539 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000540 // Call the constructor.
541 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
542 E->arg_begin(), E->arg_end());
543}
544
Anders Carlssona00703d2009-05-31 01:40:14 +0000545llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000546 if (E->isArray()) {
547 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000548 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000549 }
550
551 QualType AllocType = E->getAllocatedType();
552 FunctionDecl *NewFD = E->getOperatorNew();
553 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
554
555 CallArgList NewArgs;
556
557 // The allocation size is the first argument.
558 QualType SizeTy = getContext().getSizeType();
559 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000560 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000561 getContext().getTypeSize(AllocType) / 8);
562
563 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
564
565 // Emit the rest of the arguments.
566 // FIXME: Ideally, this should just use EmitCallArgs.
567 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
568
569 // First, use the types from the function type.
570 // We start at 1 here because the first argument (the allocation size)
571 // has already been emitted.
572 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
573 QualType ArgType = NewFTy->getArgType(i);
574
575 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
576 getTypePtr() ==
577 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
578 "type mismatch in call argument!");
579
580 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
581 ArgType));
582
583 }
584
585 // Either we've emitted all the call args, or we have a call to a
586 // variadic function.
587 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
588 "Extra arguments in non-variadic function!");
589
590 // If we still have any arguments, emit them using the type of the argument.
591 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
592 NewArg != NewArgEnd; ++NewArg) {
593 QualType ArgType = NewArg->getType();
594 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
595 ArgType));
596 }
597
598 // Emit the call to new.
599 RValue RV =
600 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
601 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
602 NewArgs, NewFD);
603
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000604 // If an allocation function is declared with an empty exception specification
605 // it returns null to indicate failure to allocate storage. [expr.new]p13.
606 // (We don't need to check for null when there's no new initializer and
607 // we're allocating a POD type).
608 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
609 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000610
Anders Carlssonf1108532009-06-01 00:05:16 +0000611 llvm::BasicBlock *NewNull = 0;
612 llvm::BasicBlock *NewNotNull = 0;
613 llvm::BasicBlock *NewEnd = 0;
614
615 llvm::Value *NewPtr = RV.getScalarVal();
616
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000617 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000618 NewNull = createBasicBlock("new.null");
619 NewNotNull = createBasicBlock("new.notnull");
620 NewEnd = createBasicBlock("new.end");
621
622 llvm::Value *IsNull =
623 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000624 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000625 "isnull");
626
627 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
628 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000629 }
630
Anders Carlssonf1108532009-06-01 00:05:16 +0000631 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000632
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000633 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000634 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000635 assert(E->getNumConstructorArgs() == 1 &&
636 "Can only have one argument to initializer of POD type.");
637
638 const Expr *Init = E->getConstructorArg(0);
639
Anders Carlsson3923e952009-05-31 21:07:58 +0000640 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000641 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000642 else if (AllocType->isAnyComplexType())
643 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000644 else
645 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000646 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000647 } else {
648 // Call the constructor.
649 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000650
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000651 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
652 E->constructor_arg_begin(),
653 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000654 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000655
Anders Carlssonf1108532009-06-01 00:05:16 +0000656 if (NullCheckResult) {
657 Builder.CreateBr(NewEnd);
658 EmitBlock(NewNull);
659 Builder.CreateBr(NewEnd);
660 EmitBlock(NewEnd);
661
662 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
663 PHI->reserveOperandSpace(2);
664 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000665 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000666
667 NewPtr = PHI;
668 }
669
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000670 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000671}
672
Anders Carlsson60e282c2009-08-16 21:13:42 +0000673void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
674 if (E->isArrayForm()) {
675 ErrorUnsupported(E, "delete[] expression");
676 return;
677 };
678
679 QualType DeleteTy =
680 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
681
682 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
683
684 // Null check the pointer.
685 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
686 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
687
688 llvm::Value *IsNull =
689 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
690 "isnull");
691
692 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
693 EmitBlock(DeleteNotNull);
694
695 // Call the destructor if necessary.
696 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
698 if (!RD->hasTrivialDestructor()) {
699 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
700 if (Dtor->isVirtual()) {
701 ErrorUnsupported(E, "delete expression with virtual destructor");
702 return;
703 }
704
705 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
706 }
707 }
708 }
709
710 // Call delete.
711 FunctionDecl *DeleteFD = E->getOperatorDelete();
712 const FunctionProtoType *DeleteFTy =
713 DeleteFD->getType()->getAsFunctionProtoType();
714
715 CallArgList DeleteArgs;
716
717 QualType ArgTy = DeleteFTy->getArgType(0);
718 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
719 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
720
721 // Emit the call to delete.
722 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
723 DeleteArgs),
724 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
725 DeleteArgs, DeleteFD);
726
727 EmitBlock(DeleteEnd);
728}
729
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000730void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000731 EmitGlobal(GlobalDecl(D, Ctor_Complete));
732 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000733}
Anders Carlsson363c1842009-04-16 23:57:24 +0000734
Anders Carlsson27ae5362009-04-17 01:58:57 +0000735void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
736 CXXCtorType Type) {
737
738 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
739
740 CodeGenFunction(*this).GenerateCode(D, Fn);
741
742 SetFunctionDefinitionAttributes(D, Fn);
743 SetLLVMFunctionAttributesForDefinition(D, Fn);
744}
745
Anders Carlsson363c1842009-04-16 23:57:24 +0000746llvm::Function *
747CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
748 CXXCtorType Type) {
749 const llvm::FunctionType *FTy =
750 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
751
752 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000753 return cast<llvm::Function>(
754 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000755}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000756
757const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
758 CXXCtorType Type) {
759 llvm::SmallString<256> Name;
760 llvm::raw_svector_ostream Out(Name);
761 mangleCXXCtor(D, Type, Context, Out);
762
763 Name += '\0';
764 return UniqueMangledName(Name.begin(), Name.end());
765}
766
767void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000768 EmitCXXDestructor(D, Dtor_Complete);
769 EmitCXXDestructor(D, Dtor_Base);
770}
771
772void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
773 CXXDtorType Type) {
774 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
775
776 CodeGenFunction(*this).GenerateCode(D, Fn);
777
778 SetFunctionDefinitionAttributes(D, Fn);
779 SetLLVMFunctionAttributesForDefinition(D, Fn);
780}
781
782llvm::Function *
783CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
784 CXXDtorType Type) {
785 const llvm::FunctionType *FTy =
786 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
787
788 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000789 return cast<llvm::Function>(
790 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000791}
792
793const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
794 CXXDtorType Type) {
795 llvm::SmallString<256> Name;
796 llvm::raw_svector_ostream Out(Name);
797 mangleCXXDtor(D, Type, Context, Out);
798
799 Name += '\0';
800 return UniqueMangledName(Name.begin(), Name.end());
801}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000802
Mike Stump32f37012009-08-18 21:49:00 +0000803llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000804 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000805 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000806 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000807
808 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000809 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000810
811 llvm::SmallString<256> OutName;
812 llvm::raw_svector_ostream Out(OutName);
813 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000814 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000815 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000816 llvm::GlobalVariable::LinkageTypes linktype;
817 linktype = llvm::GlobalValue::WeakAnyLinkage;
818 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000819 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000820 // FIXME: descriptor
821 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000822 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000823 // FIXME: TS
824 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
825
826 llvm::Constant *C;
827 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
828 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000829 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000830 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000831 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
832 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000833}
834
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000835class VtableBuilder {
Mike Stumpf0070db2009-08-26 20:46:33 +0000836public:
837 /// Index_t - Vtable index type.
838 typedef uint64_t Index_t;
839private:
Mike Stump7c435fa2009-08-18 20:50:28 +0000840 std::vector<llvm::Constant *> &methods;
Mike Stump15a24e02009-08-28 23:22:54 +0000841 std::vector<llvm::Constant *> submethods;
Mike Stump7c435fa2009-08-18 20:50:28 +0000842 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000843 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000844 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000845 /// BLayout - Layout for the most derived class that this vtable is being
846 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000847 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000848 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000850 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000851 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000852 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-08-21 01:45:00 +0000853 /// Index - Maps a method decl into a vtable index. Useful for virtual
854 /// dispatch codegen.
Mike Stumpf0070db2009-08-26 20:46:33 +0000855 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stump15a24e02009-08-28 23:22:54 +0000856 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
857 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCallOffset;
858 std::vector<Index_t> VCalls;
Mike Stump552b2752009-08-18 22:04:08 +0000859 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumped032eb2009-09-04 18:27:16 +0000860 // FIXME: Linkage should follow vtable
861 const bool Extern;
Mike Stump7c435fa2009-08-18 20:50:28 +0000862public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000863 VtableBuilder(std::vector<llvm::Constant *> &meth,
864 const CXXRecordDecl *c,
865 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000866 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
867 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
Mike Stumped032eb2009-09-04 18:27:16 +0000868 CGM(cgm), Extern(true) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000869 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
870 }
Mike Stump32f37012009-08-18 21:49:00 +0000871
Mike Stumpf0070db2009-08-26 20:46:33 +0000872 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb46c92d2009-08-19 02:06:38 +0000873
Mike Stump15a24e02009-08-28 23:22:54 +0000874 llvm::Constant *wrap(Index_t i) {
875 llvm::Constant *m;
876 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
877 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stumpb46c92d2009-08-19 02:06:38 +0000878 }
879
Mike Stump15a24e02009-08-28 23:22:54 +0000880 llvm::Constant *wrap(llvm::Constant *m) {
881 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
Mike Stump80a0e322009-08-12 23:25:18 +0000882 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000883
Mike Stump7fa0d932009-08-20 02:11:48 +0000884 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000885 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000886 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
887 e = RD->bases_end(); i != e; ++i) {
888 const CXXRecordDecl *Base =
889 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
890 if (i->isVirtual() && !SeenVBase.count(Base)) {
891 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000892 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump15a24e02009-08-28 23:22:54 +0000893 llvm::Constant *m = wrap(BaseOffset);
894 m = wrap((0?700:0) + BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000895 offsets.push_back(m);
896 }
Mike Stumpb9837442009-08-20 07:22:17 +0000897 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000898 }
899 }
900
Mike Stumpb9871a22009-08-21 01:45:00 +0000901 void StartNewTable() {
902 SeenVBase.clear();
903 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000904
Mike Stump35191b62009-09-01 22:20:28 +0000905 bool OverrideMethod(const CXXMethodDecl *MD, llvm::Constant *m,
Mike Stumped032eb2009-09-04 18:27:16 +0000906 bool MorallyVirtual, Index_t Offset,
907 std::vector<llvm::Constant *> &submethods,
908 Index_t AddressPoint) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000909 typedef CXXMethodDecl::method_iterator meth_iter;
910
Mike Stumpb9871a22009-08-21 01:45:00 +0000911 // FIXME: Don't like the nested loops. For very large inheritance
912 // heirarchies we could have a table on the side with the final overridder
913 // and just replace each instance of an overridden method once. Would be
914 // nice to measure the cost/benefit on real code.
915
916 // If we can find a previously allocated slot for this, reuse it.
917 for (meth_iter mi = MD->begin_overridden_methods(),
918 e = MD->end_overridden_methods();
919 mi != e; ++mi) {
920 const CXXMethodDecl *OMD = *mi;
921 llvm::Constant *om;
922 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
923 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
924
Mike Stumped032eb2009-09-04 18:27:16 +0000925 for (Index_t i = AddressPoint, e = submethods.size();
Mike Stumpf0070db2009-08-26 20:46:33 +0000926 i != e; ++i) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000927 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stump15a24e02009-08-28 23:22:54 +0000928 if (submethods[i] == om) {
Mike Stumped032eb2009-09-04 18:27:16 +0000929 int64_t O = VCallOffset[OMD] - Offset/8;
Mike Stump15a24e02009-08-28 23:22:54 +0000930 // FIXME: thunks
Mike Stumped032eb2009-09-04 18:27:16 +0000931 if (O) {
932 submethods[i] = CGM.BuildThunk(MD, Extern, true, 0, O);
933 } else
934 submethods[i] = m;
935 // FIXME: audit
936 Index[MD] = i - AddressPoint;
Mike Stump15a24e02009-08-28 23:22:54 +0000937 if (MorallyVirtual) {
938 VCallOffset[MD] = Offset/8;
939 VCalls[VCall[OMD]] = Offset/8 - VCallOffset[OMD];
940 }
941 // submethods[VCall[OMD]] = wrap(Offset/8 - VCallOffset[OMD]);
Mike Stump35191b62009-09-01 22:20:28 +0000942 return true;
Mike Stumpb9871a22009-08-21 01:45:00 +0000943 }
Mike Stump65defe32009-08-18 21:03:28 +0000944 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000945 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000946
Mike Stump35191b62009-09-01 22:20:28 +0000947 return false;
948 }
949
Mike Stumpf9a883c2009-09-01 23:22:44 +0000950 void OverrideMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
951 bool MorallyVirtual, Index_t Offset) {
952 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
953 ++mi)
954 if (mi->isVirtual()) {
955 const CXXMethodDecl *MD = *mi;
956 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stumped032eb2009-09-04 18:27:16 +0000957 OverrideMethod(MD, m, MorallyVirtual, Offset, methods, AddressPoint);
Mike Stumpf9a883c2009-09-01 23:22:44 +0000958 }
959 }
960
Mike Stump35191b62009-09-01 22:20:28 +0000961 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint,
962 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf9a883c2009-09-01 23:22:44 +0000963 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stumped032eb2009-09-04 18:27:16 +0000964 if (OverrideMethod(MD, m, MorallyVirtual, Offset, submethods, 0))
Mike Stump35191b62009-09-01 22:20:28 +0000965 return;
966
Mike Stumpb9871a22009-08-21 01:45:00 +0000967 // else allocate a new slot.
Mike Stump15a24e02009-08-28 23:22:54 +0000968 Index[MD] = submethods.size();
969 // VCall[MD] = Offset;
970 if (MorallyVirtual) {
971 VCallOffset[MD] = Offset/8;
972 Index_t &idx = VCall[MD];
973 // Allocate the first one, after that, we reuse the previous one.
974 if (idx == 0) {
975 idx = VCalls.size()+1;
976 VCallOffset[MD] = Offset/8;
977 VCalls.push_back(0);
978 }
979 }
980 submethods.push_back(m);
Mike Stumpb9871a22009-08-21 01:45:00 +0000981 }
982
Mike Stumpf9a883c2009-09-01 23:22:44 +0000983 void AddMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
984 bool MorallyVirtual, Index_t Offset) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000985 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
986 ++mi)
987 if (mi->isVirtual())
Mike Stump15a24e02009-08-28 23:22:54 +0000988 AddMethod(*mi, AddressPoint, MorallyVirtual, Offset);
Mike Stumpbc16aea2009-08-12 23:00:59 +0000989 }
Mike Stump65defe32009-08-18 21:03:28 +0000990
Mike Stumpf9a883c2009-09-01 23:22:44 +0000991 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, bool forPrimary,
992 bool Bottom, bool MorallyVirtual,
993 int64_t Offset, bool ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +0000994 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +0000995 int64_t AddressPoint=0;
Mike Stump276b9f12009-08-16 01:46:26 +0000996
Mike Stump109b13d2009-08-18 21:30:21 +0000997 if (RD && !RD->isDynamicClass())
Mike Stump263b3522009-08-21 23:09:30 +0000998 return 0;
Mike Stump109b13d2009-08-18 21:30:21 +0000999
1000 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1001 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1002 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1003
Mike Stump15a24e02009-08-28 23:22:54 +00001004 std::vector<llvm::Constant *> offsets;
Mike Stump109b13d2009-08-18 21:30:21 +00001005 // FIXME: Audit, is this right?
Mike Stump15a24e02009-08-28 23:22:54 +00001006 if (Bottom && (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual
1007 || Bottom))
Mike Stumpb9837442009-08-20 07:22:17 +00001008 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001009
Mike Stump109b13d2009-08-18 21:30:21 +00001010 bool Top = true;
1011
1012 // vtables are composed from the chain of primaries.
1013 if (PrimaryBase) {
1014 if (PrimaryBaseWasVirtual)
1015 IndirectPrimary.insert(PrimaryBase);
1016 Top = false;
Mike Stump15a24e02009-08-28 23:22:54 +00001017 AddressPoint = GenerateVtableForBase(PrimaryBase, true, false,
1018 PrimaryBaseWasVirtual|MorallyVirtual,
Mike Stumpf0070db2009-08-26 20:46:33 +00001019 Offset, PrimaryBaseWasVirtual);
Mike Stump109b13d2009-08-18 21:30:21 +00001020 }
1021
Mike Stump15a24e02009-08-28 23:22:54 +00001022 // And add the virtuals for the class to the primary vtable.
Mike Stumpf9a883c2009-09-01 23:22:44 +00001023 AddMethods(RD, AddressPoint, MorallyVirtual, Offset);
Mike Stump15a24e02009-08-28 23:22:54 +00001024
1025 if (!Bottom)
1026 return AddressPoint;
1027
1028 StartNewTable();
1029 // FIXME: Cleanup.
1030 if (!ForVirtualBase) {
1031 // then virtual base offsets...
1032 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1033 e = offsets.rend(); i != e; ++i)
1034 methods.push_back(*i);
Mike Stump276b9f12009-08-16 01:46:26 +00001035 }
Mike Stump4ef98092009-08-13 22:53:07 +00001036
Mike Stump15a24e02009-08-28 23:22:54 +00001037 // The vcalls come first...
1038 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1039 i < e; ++i)
1040 methods.push_back(wrap((0?600:0) + *i));
1041 VCalls.clear();
1042
1043 if (ForVirtualBase) {
1044 // then virtual base offsets...
1045 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1046 e = offsets.rend(); i != e; ++i)
1047 methods.push_back(*i);
1048 }
1049
Mike Stumpf9a883c2009-09-01 23:22:44 +00001050 m = wrap(-(Offset/8));
Mike Stump15a24e02009-08-28 23:22:54 +00001051 methods.push_back(m);
1052 methods.push_back(rtti);
1053 AddressPoint = methods.size();
1054
1055 methods.insert(methods.end(), submethods.begin(), submethods.end());
1056 submethods.clear();
Mike Stump109b13d2009-08-18 21:30:21 +00001057
1058 // and then the non-virtual bases.
1059 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1060 e = RD->bases_end(); i != e; ++i) {
1061 if (i->isVirtual())
1062 continue;
1063 const CXXRecordDecl *Base =
1064 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1065 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1066 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001067 StartNewTable();
Mike Stumped032eb2009-09-04 18:27:16 +00001068 Index_t AP;
1069 AP = GenerateVtableForBase(Base, true, true, MorallyVirtual, o, false);
1070 OverrideMethods(RD, AP, MorallyVirtual, o);
Mike Stump109b13d2009-08-18 21:30:21 +00001071 }
1072 }
Mike Stump263b3522009-08-21 23:09:30 +00001073 return AddressPoint;
Mike Stump109b13d2009-08-18 21:30:21 +00001074 }
1075
1076 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001077 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001078 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1079 e = RD->bases_end(); i != e; ++i) {
1080 const CXXRecordDecl *Base =
1081 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1082 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1083 // Mark it so we don't output it twice.
1084 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001085 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001086 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumped032eb2009-09-04 18:27:16 +00001087 Index_t AP;
1088 AP = GenerateVtableForBase(Base, false, true, true, BaseOffset, true);
1089 OverrideMethods(RD, AP, true, BaseOffset);
Mike Stump109b13d2009-08-18 21:30:21 +00001090 }
1091 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001092 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001093 }
1094 }
Mike Stump109b13d2009-08-18 21:30:21 +00001095};
Mike Stump8a12b562009-08-06 15:50:11 +00001096
Mike Stumpf0070db2009-08-26 20:46:33 +00001097class VtableInfo {
1098public:
1099 typedef VtableBuilder::Index_t Index_t;
1100private:
1101 CodeGenModule &CGM; // Per-module state.
1102 /// Index_t - Vtable index type.
1103 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1104 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1105 // FIXME: Move to Context.
1106 static MapTy IndexFor;
1107public:
1108 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1109 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1110 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1111 // We own a copy of this, it will go away shortly.
1112 new ElTy (e);
1113 IndexFor[RD] = new ElTy (e);
1114 }
1115 Index_t lookup(const CXXMethodDecl *MD) {
1116 const CXXRecordDecl *RD = MD->getParent();
1117 MapTy::iterator I = IndexFor.find(RD);
1118 if (I == IndexFor.end()) {
1119 std::vector<llvm::Constant *> methods;
1120 VtableBuilder b(methods, RD, CGM);
Mike Stump15a24e02009-08-28 23:22:54 +00001121 b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stumpf0070db2009-08-26 20:46:33 +00001122 b.GenerateVtableForVBases(RD, RD);
1123 register_index(RD, b.getIndex());
1124 I = IndexFor.find(RD);
1125 }
1126 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1127 return (*I->second)[MD];
1128 }
1129};
1130
1131// FIXME: Move to Context.
1132VtableInfo::MapTy VtableInfo::IndexFor;
1133
Mike Stumpf1216772009-07-31 18:25:34 +00001134llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001135 llvm::SmallString<256> OutName;
1136 llvm::raw_svector_ostream Out(OutName);
1137 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001138 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001139 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001140 llvm::GlobalVariable::LinkageTypes linktype;
1141 linktype = llvm::GlobalValue::WeakAnyLinkage;
1142 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001143 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump263b3522009-08-21 23:09:30 +00001144 int64_t Offset;
Mike Stump6f376332009-08-05 22:37:18 +00001145
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001146 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001147
Mike Stump276b9f12009-08-16 01:46:26 +00001148 // First comes the vtables for all the non-virtual bases...
Mike Stump15a24e02009-08-28 23:22:54 +00001149 Offset = b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stump21538912009-08-14 01:44:03 +00001150
Mike Stump276b9f12009-08-16 01:46:26 +00001151 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001152 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001153
Mike Stump82b56962009-07-31 21:43:43 +00001154 llvm::Constant *C;
1155 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1156 C = llvm::ConstantArray::get(type, methods);
1157 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001158 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001159 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001160 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001161 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump263b3522009-08-21 23:09:30 +00001162 Offset*LLVMPointerWidth/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001163 return vtable;
1164}
1165
Mike Stumpf0070db2009-08-26 20:46:33 +00001166// FIXME: move to Context
1167static VtableInfo *vtableinfo;
1168
Mike Stumped032eb2009-09-04 18:27:16 +00001169llvm::Constant *CodeGenFunction::GenerateThunk(llvm::Function *Fn,
1170 const CXXMethodDecl *MD,
1171 bool Extern, bool Virtual,
1172 int64_t nv, int64_t v) {
1173 QualType R = MD->getType()->getAsFunctionType()->getResultType();
1174
1175 FunctionArgList Args;
1176 ImplicitParamDecl *ThisDecl =
1177 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
1178 MD->getThisType(getContext()));
1179 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
1180 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
1181 e = MD->param_end();
1182 i != e; ++i) {
1183 ParmVarDecl *D = *i;
1184 Args.push_back(std::make_pair(D, D->getType()));
1185 }
1186 IdentifierInfo *II
1187 = &CGM.getContext().Idents.get("__thunk_named_foo_");
1188 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1189 getContext().getTranslationUnitDecl(),
1190 SourceLocation(), II, R, 0,
1191 Extern
1192 ? FunctionDecl::Extern
1193 : FunctionDecl::Static,
1194 false, true);
1195 StartFunction(FD, R, Fn, Args, SourceLocation());
1196 // FIXME: generate body
1197 FinishFunction();
1198 return Fn;
1199}
1200
1201llvm::Constant *CodeGenModule::BuildThunk(const CXXMethodDecl *MD,
1202 bool Extern, bool Virtual, int64_t nv,
1203 int64_t v) {
1204 llvm::SmallString<256> OutName;
1205 llvm::raw_svector_ostream Out(OutName);
1206 mangleThunk(MD, Virtual, nv, v, getContext(), Out);
1207 llvm::GlobalVariable::LinkageTypes linktype;
1208 linktype = llvm::GlobalValue::WeakAnyLinkage;
1209 if (!Extern)
1210 linktype = llvm::GlobalValue::InternalLinkage;
1211 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1212 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1213 const llvm::FunctionType *FTy =
1214 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1215 FPT->isVariadic());
1216
1217 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(),
1218 &getModule());
1219 CodeGenFunction(*this).GenerateThunk(Fn, MD, Extern, Virtual, nv, v);
1220 // Fn = Builder.CreateBitCast(Fn, Ptr8Ty);
1221 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1222 return m;
1223}
1224
Mike Stumpf0070db2009-08-26 20:46:33 +00001225llvm::Value *
1226CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1227 const llvm::Type *Ty) {
1228 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1229
1230 // FIXME: move to Context
1231 if (vtableinfo == 0)
1232 vtableinfo = new VtableInfo(CGM);
1233
1234 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1235
1236 Ty = llvm::PointerType::get(Ty, 0);
1237 Ty = llvm::PointerType::get(Ty, 0);
1238 Ty = llvm::PointerType::get(Ty, 0);
1239 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1240 vtbl = Builder.CreateLoad(vtbl);
1241 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1242 Idx, "vfn");
1243 vfn = Builder.CreateLoad(vfn);
1244 return vfn;
1245}
1246
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001247/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1248/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1249/// copy or via a copy constructor call.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +00001250// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001251void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1252 llvm::Value *Src,
1253 const ArrayType *Array,
1254 const CXXRecordDecl *BaseClassDecl,
1255 QualType Ty) {
1256 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1257 assert(CA && "VLA cannot be copied over");
1258 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1259
1260 // Create a temporary for the loop index and initialize it with 0.
1261 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1262 "loop.index");
1263 llvm::Value* zeroConstant =
1264 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1265 Builder.CreateStore(zeroConstant, IndexPtr, false);
1266 // Start the loop with a block that tests the condition.
1267 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1268 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1269
1270 EmitBlock(CondBlock);
1271
1272 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1273 // Generate: if (loop-index < number-of-elements fall to the loop body,
1274 // otherwise, go to the block after the for-loop.
1275 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1276 llvm::Value * NumElementsPtr =
1277 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1278 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1279 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1280 "isless");
1281 // If the condition is true, execute the body.
1282 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1283
1284 EmitBlock(ForBody);
1285 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1286 // Inside the loop body, emit the constructor call on the array element.
1287 Counter = Builder.CreateLoad(IndexPtr);
1288 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1289 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1290 if (BitwiseCopy)
1291 EmitAggregateCopy(Dest, Src, Ty);
1292 else if (CXXConstructorDecl *BaseCopyCtor =
1293 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1294 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1295 Ctor_Complete);
1296 CallArgList CallArgs;
1297 // Push the this (Dest) ptr.
1298 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1299 BaseCopyCtor->getThisType(getContext())));
1300
1301 // Push the Src ptr.
1302 CallArgs.push_back(std::make_pair(RValue::get(Src),
1303 BaseCopyCtor->getParamDecl(0)->getType()));
1304 QualType ResultType =
1305 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1306 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1307 Callee, CallArgs, BaseCopyCtor);
1308 }
1309 EmitBlock(ContinueBlock);
1310
1311 // Emit the increment of the loop counter.
1312 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1313 Counter = Builder.CreateLoad(IndexPtr);
1314 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1315 Builder.CreateStore(NextVal, IndexPtr, false);
1316
1317 // Finally, branch back up to the condition for the next iteration.
1318 EmitBranch(CondBlock);
1319
1320 // Emit the fall-through block.
1321 EmitBlock(AfterFor, true);
1322}
1323
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001324/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1325/// array of objects from SrcValue to DestValue. Assignment can be either a
1326/// bitwise assignment or via a copy assignment operator function call.
1327/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1328void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1329 llvm::Value *Src,
1330 const ArrayType *Array,
1331 const CXXRecordDecl *BaseClassDecl,
1332 QualType Ty) {
1333 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1334 assert(CA && "VLA cannot be asssigned");
1335 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1336
1337 // Create a temporary for the loop index and initialize it with 0.
1338 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1339 "loop.index");
1340 llvm::Value* zeroConstant =
1341 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1342 Builder.CreateStore(zeroConstant, IndexPtr, false);
1343 // Start the loop with a block that tests the condition.
1344 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1345 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1346
1347 EmitBlock(CondBlock);
1348
1349 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1350 // Generate: if (loop-index < number-of-elements fall to the loop body,
1351 // otherwise, go to the block after the for-loop.
1352 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1353 llvm::Value * NumElementsPtr =
1354 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1355 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1356 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1357 "isless");
1358 // If the condition is true, execute the body.
1359 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1360
1361 EmitBlock(ForBody);
1362 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1363 // Inside the loop body, emit the assignment operator call on array element.
1364 Counter = Builder.CreateLoad(IndexPtr);
1365 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1366 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1367 const CXXMethodDecl *MD = 0;
1368 if (BitwiseAssign)
1369 EmitAggregateCopy(Dest, Src, Ty);
1370 else {
1371 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1372 MD);
1373 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1374 (void)hasCopyAssign;
1375 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1376 const llvm::Type *LTy =
1377 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1378 FPT->isVariadic());
1379 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1380
1381 CallArgList CallArgs;
1382 // Push the this (Dest) ptr.
1383 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1384 MD->getThisType(getContext())));
1385
1386 // Push the Src ptr.
1387 CallArgs.push_back(std::make_pair(RValue::get(Src),
1388 MD->getParamDecl(0)->getType()));
Mike Stumped032eb2009-09-04 18:27:16 +00001389 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001390 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1391 Callee, CallArgs, MD);
1392 }
1393 EmitBlock(ContinueBlock);
1394
1395 // Emit the increment of the loop counter.
1396 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1397 Counter = Builder.CreateLoad(IndexPtr);
1398 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1399 Builder.CreateStore(NextVal, IndexPtr, false);
1400
1401 // Finally, branch back up to the condition for the next iteration.
1402 EmitBranch(CondBlock);
1403
1404 // Emit the fall-through block.
1405 EmitBlock(AfterFor, true);
1406}
1407
Fariborz Jahanianca283612009-08-07 23:51:33 +00001408/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1409/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001410/// or via a copy constructor call.
Fariborz Jahanianca283612009-08-07 23:51:33 +00001411void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001412 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001413 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001414 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1415 if (ClassDecl) {
1416 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1417 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1418 }
1419 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1420 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001421 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001422 }
1423
Fariborz Jahanianca283612009-08-07 23:51:33 +00001424 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001425 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001426 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1427 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001428 CallArgList CallArgs;
1429 // Push the this (Dest) ptr.
1430 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1431 BaseCopyCtor->getThisType(getContext())));
1432
Fariborz Jahanianca283612009-08-07 23:51:33 +00001433 // Push the Src ptr.
1434 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001435 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001436 QualType ResultType =
1437 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1438 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1439 Callee, CallArgs, BaseCopyCtor);
1440 }
1441}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001442
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001443/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1444/// object from SrcValue to DestValue. Assignment can be either a bitwise
1445/// assignment of via an assignment operator call.
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001446// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001447void CodeGenFunction::EmitClassCopyAssignment(
1448 llvm::Value *Dest, llvm::Value *Src,
1449 const CXXRecordDecl *ClassDecl,
1450 const CXXRecordDecl *BaseClassDecl,
1451 QualType Ty) {
1452 if (ClassDecl) {
1453 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1454 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1455 }
1456 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1457 EmitAggregateCopy(Dest, Src, Ty);
1458 return;
1459 }
1460
1461 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001462 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1463 MD);
1464 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1465 (void)ConstCopyAssignOp;
1466
1467 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1468 const llvm::Type *LTy =
1469 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1470 FPT->isVariadic());
1471 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001472
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001473 CallArgList CallArgs;
1474 // Push the this (Dest) ptr.
1475 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1476 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001477
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001478 // Push the Src ptr.
1479 CallArgs.push_back(std::make_pair(RValue::get(Src),
1480 MD->getParamDecl(0)->getType()));
1481 QualType ResultType =
1482 MD->getType()->getAsFunctionType()->getResultType();
1483 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1484 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001485}
1486
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001487/// SynthesizeDefaultConstructor - synthesize a default constructor
1488void
1489CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1490 const FunctionDecl *FD,
1491 llvm::Function *Fn,
1492 const FunctionArgList &Args) {
1493 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1494 EmitCtorPrologue(CD);
1495 FinishFunction();
1496}
1497
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001498/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001499/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1500/// The implicitly-defined copy constructor for class X performs a memberwise
1501/// copy of its subobjects. The order of copying is the same as the order
1502/// of initialization of bases and members in a user-defined constructor
1503/// Each subobject is copied in the manner appropriate to its type:
1504/// if the subobject is of class type, the copy constructor for the class is
1505/// used;
1506/// if the subobject is an array, each element is copied, in the manner
1507/// appropriate to the element type;
1508/// if the subobject is of scalar type, the built-in assignment operator is
1509/// used.
1510/// Virtual base class subobjects shall be copied only once by the
1511/// implicitly-defined copy constructor
1512
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001513void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1514 const FunctionDecl *FD,
1515 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001516 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001517 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1518 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001519 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1520 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001521
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001522 FunctionArgList::const_iterator i = Args.begin();
1523 const VarDecl *ThisArg = i->first;
1524 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1525 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1526 const VarDecl *SrcArg = (i+1)->first;
1527 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1528 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1529
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001530 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1531 Base != ClassDecl->bases_end(); ++Base) {
1532 // FIXME. copy constrution of virtual base NYI
1533 if (Base->isVirtual())
1534 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001535
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001536 CXXRecordDecl *BaseClassDecl
1537 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001538 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1539 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001540 }
1541
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001542 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1543 FieldEnd = ClassDecl->field_end();
1544 Field != FieldEnd; ++Field) {
1545 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001546 const ConstantArrayType *Array =
1547 getContext().getAsConstantArrayType(FieldType);
1548 if (Array)
1549 FieldType = getContext().getBaseElementType(FieldType);
1550
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001551 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1552 CXXRecordDecl *FieldClassDecl
1553 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1554 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1555 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001556 if (Array) {
1557 const llvm::Type *BasePtr = ConvertType(FieldType);
1558 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1559 llvm::Value *DestBaseAddrPtr =
1560 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1561 llvm::Value *SrcBaseAddrPtr =
1562 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1563 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1564 FieldClassDecl, FieldType);
1565 }
1566 else
1567 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1568 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001569 continue;
1570 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001571 // Do a built-in assignment of scalar data members.
1572 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1573 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1574 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1575 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001576 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001577 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001578}
1579
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001580/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1581/// Before the implicitly-declared copy assignment operator for a class is
1582/// implicitly defined, all implicitly- declared copy assignment operators for
1583/// its direct base classes and its nonstatic data members shall have been
1584/// implicitly defined. [12.8-p12]
1585/// The implicitly-defined copy assignment operator for class X performs
1586/// memberwise assignment of its subob- jects. The direct base classes of X are
1587/// assigned first, in the order of their declaration in
1588/// the base-specifier-list, and then the immediate nonstatic data members of X
1589/// are assigned, in the order in which they were declared in the class
1590/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001591/// if the subobject is of class type, the copy assignment operator for the
1592/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001593/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001594///
1595/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001596/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001597///
1598/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001599/// used.
1600void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1601 const FunctionDecl *FD,
1602 llvm::Function *Fn,
1603 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001604
1605 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1606 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1607 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001608 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1609
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001610 FunctionArgList::const_iterator i = Args.begin();
1611 const VarDecl *ThisArg = i->first;
1612 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1613 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1614 const VarDecl *SrcArg = (i+1)->first;
1615 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1616 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1617
1618 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1619 Base != ClassDecl->bases_end(); ++Base) {
1620 // FIXME. copy assignment of virtual base NYI
1621 if (Base->isVirtual())
1622 continue;
1623
1624 CXXRecordDecl *BaseClassDecl
1625 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1626 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1627 Base->getType());
1628 }
1629
1630 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1631 FieldEnd = ClassDecl->field_end();
1632 Field != FieldEnd; ++Field) {
1633 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001634 const ConstantArrayType *Array =
1635 getContext().getAsConstantArrayType(FieldType);
1636 if (Array)
1637 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001638
1639 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1640 CXXRecordDecl *FieldClassDecl
1641 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1642 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1643 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001644 if (Array) {
1645 const llvm::Type *BasePtr = ConvertType(FieldType);
1646 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1647 llvm::Value *DestBaseAddrPtr =
1648 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1649 llvm::Value *SrcBaseAddrPtr =
1650 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1651 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1652 FieldClassDecl, FieldType);
1653 }
1654 else
1655 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1656 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001657 continue;
1658 }
1659 // Do a built-in assignment of scalar data members.
1660 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1661 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1662 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1663 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001664 }
1665
1666 // return *this;
1667 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001668
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001669 FinishFunction();
1670}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001671
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001672/// EmitCtorPrologue - This routine generates necessary code to initialize
1673/// base classes and non-static data members belonging to this constructor.
Anders Carlsson174754c2009-09-01 18:33:46 +00001674/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001675void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001676 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001677 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001678 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001679
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001680 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001681 E = CD->init_end();
1682 B != E; ++B) {
1683 CXXBaseOrMemberInitializer *Member = (*B);
1684 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001685 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001686 Type *BaseType = Member->getBaseClass();
1687 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001688 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001689 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1690 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001691 EmitCXXConstructorCall(Member->getConstructor(),
1692 Ctor_Complete, V,
1693 Member->const_arg_begin(),
1694 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001695 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001696 // non-static data member initilaizers.
1697 FieldDecl *Field = Member->getMember();
1698 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001699 const ConstantArrayType *Array =
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001700 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001701 if (Array)
1702 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001703
Mike Stumpf1216772009-07-31 18:25:34 +00001704 LoadOfThis = LoadCXXThis();
Eli Friedmane3a97db2009-08-29 20:58:20 +00001705 LValue LHS;
1706 if (FieldType->isReferenceType()) {
1707 // FIXME: This is really ugly; should be refactored somehow
1708 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1709 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1710 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1711 QualType::GCNone, FieldType.getAddressSpace());
1712 } else {
1713 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1714 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001715 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001716 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001717 assert(Member->getConstructor() &&
1718 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001719 if (Array) {
1720 const llvm::Type *BasePtr = ConvertType(FieldType);
1721 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1722 llvm::Value *BaseAddrPtr =
1723 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1724 EmitCXXAggrConstructorCall(Member->getConstructor(),
1725 Array, BaseAddrPtr);
1726 }
1727 else
1728 EmitCXXConstructorCall(Member->getConstructor(),
1729 Ctor_Complete, LHS.getAddress(),
1730 Member->const_arg_begin(),
1731 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001732 continue;
1733 }
1734 else {
1735 // Initializing an anonymous union data member.
1736 FieldDecl *anonMember = Member->getAnonUnionMember();
Anders Carlssonc186b8f2009-09-02 21:14:47 +00001737 LHS = EmitLValueForField(LHS.getAddress(), anonMember,
1738 /*IsUnion=*/true, 0);
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001739 FieldType = anonMember->getType();
1740 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001741 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001742
1743 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001744 Expr *RhsExpr = *Member->arg_begin();
Eli Friedmane3a97db2009-08-29 20:58:20 +00001745 RValue RHS;
1746 if (FieldType->isReferenceType())
1747 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1748 /*IsInitializer=*/true);
1749 else
1750 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1751 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001752 }
1753 }
Mike Stumpf1216772009-07-31 18:25:34 +00001754
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001755 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001756 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001757 // have bases classes and/or contain non-static data members which require
1758 // construction.
1759 for (CXXRecordDecl::base_class_const_iterator Base =
1760 ClassDecl->bases_begin();
1761 Base != ClassDecl->bases_end(); ++Base) {
1762 // FIXME. copy assignment of virtual base NYI
1763 if (Base->isVirtual())
1764 continue;
1765
1766 CXXRecordDecl *BaseClassDecl
1767 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1768 if (BaseClassDecl->hasTrivialConstructor())
1769 continue;
1770 if (CXXConstructorDecl *BaseCX =
1771 BaseClassDecl->getDefaultConstructor(getContext())) {
1772 LoadOfThis = LoadCXXThis();
1773 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1774 BaseClassDecl);
1775 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1776 }
1777 }
1778
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001779 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1780 FieldEnd = ClassDecl->field_end();
1781 Field != FieldEnd; ++Field) {
1782 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001783 const ConstantArrayType *Array =
1784 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001785 if (Array)
1786 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001787 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1788 continue;
1789 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001790 CXXRecordDecl *MemberClassDecl =
1791 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1792 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1793 continue;
1794 if (CXXConstructorDecl *MamberCX =
1795 MemberClassDecl->getDefaultConstructor(getContext())) {
1796 LoadOfThis = LoadCXXThis();
1797 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001798 if (Array) {
1799 const llvm::Type *BasePtr = ConvertType(FieldType);
1800 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1801 llvm::Value *BaseAddrPtr =
1802 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1803 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1804 }
1805 else
1806 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1807 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001808 }
1809 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001810 }
1811
Mike Stumpf1216772009-07-31 18:25:34 +00001812 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001813 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001814 if (!LoadOfThis)
1815 LoadOfThis = LoadCXXThis();
1816 llvm::Value *VtableField;
1817 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001818 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001819 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1820 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1821 llvm::Value *vtable = GenerateVtable(ClassDecl);
1822 Builder.CreateStore(vtable, VtableField);
1823 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001824}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001825
1826/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1827/// destructor. This is to call destructors on members and base classes
1828/// in reverse order of their construction.
Anders Carlsson174754c2009-09-01 18:33:46 +00001829/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001830void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1831 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
Anders Carlssonde738fe2009-09-01 21:12:16 +00001832 assert(!ClassDecl->getNumVBases() &&
1833 "FIXME: Destruction of virtual bases not supported");
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001834 (void)ClassDecl; // prevent warning.
1835
1836 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1837 *E = DD->destr_end(); B != E; ++B) {
1838 uintptr_t BaseOrMember = (*B);
1839 if (DD->isMemberToDestroy(BaseOrMember)) {
1840 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1841 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001842 const ConstantArrayType *Array =
1843 getContext().getAsConstantArrayType(FieldType);
1844 if (Array)
1845 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001846 const RecordType *RT = FieldType->getAs<RecordType>();
1847 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1848 if (FieldClassDecl->hasTrivialDestructor())
1849 continue;
1850 llvm::Value *LoadOfThis = LoadCXXThis();
1851 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001852 if (Array) {
1853 const llvm::Type *BasePtr = ConvertType(FieldType);
1854 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1855 llvm::Value *BaseAddrPtr =
1856 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1857 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1858 Array, BaseAddrPtr);
1859 }
1860 else
1861 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1862 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001863 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001864 const RecordType *RT =
1865 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1866 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1867 if (BaseClassDecl->hasTrivialDestructor())
1868 continue;
1869 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1870 ClassDecl,BaseClassDecl);
1871 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1872 Dtor_Complete, V);
1873 }
1874 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001875 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1876 return;
1877 // Case of destructor synthesis with fields and base classes
1878 // which have non-trivial destructors. They must be destructed in
1879 // reverse order of their construction.
1880 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1881
1882 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1883 FieldEnd = ClassDecl->field_end();
1884 Field != FieldEnd; ++Field) {
1885 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001886 if (getContext().getAsConstantArrayType(FieldType))
1887 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001888 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1889 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1890 if (FieldClassDecl->hasTrivialDestructor())
1891 continue;
1892 DestructedFields.push_back(*Field);
1893 }
1894 }
1895 if (!DestructedFields.empty())
1896 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1897 FieldDecl *Field = DestructedFields[i];
1898 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001899 const ConstantArrayType *Array =
1900 getContext().getAsConstantArrayType(FieldType);
1901 if (Array)
1902 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001903 const RecordType *RT = FieldType->getAs<RecordType>();
1904 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1905 llvm::Value *LoadOfThis = LoadCXXThis();
1906 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001907 if (Array) {
1908 const llvm::Type *BasePtr = ConvertType(FieldType);
1909 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1910 llvm::Value *BaseAddrPtr =
1911 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1912 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1913 Array, BaseAddrPtr);
1914 }
1915 else
1916 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1917 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001918 }
1919
1920 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1921 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1922 Base != ClassDecl->bases_end(); ++Base) {
1923 // FIXME. copy assignment of virtual base NYI
1924 if (Base->isVirtual())
1925 continue;
1926
1927 CXXRecordDecl *BaseClassDecl
1928 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1929 if (BaseClassDecl->hasTrivialDestructor())
1930 continue;
1931 DestructedBases.push_back(BaseClassDecl);
1932 }
1933 if (DestructedBases.empty())
1934 return;
1935 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1936 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1937 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1938 ClassDecl,BaseClassDecl);
1939 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1940 Dtor_Complete, V);
1941 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001942}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001943
1944void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1945 const FunctionDecl *FD,
1946 llvm::Function *Fn,
1947 const FunctionArgList &Args) {
1948
1949 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1950 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1951 "SynthesizeDefaultDestructor - destructor has user declaration");
1952 (void) ClassDecl;
1953
1954 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1955 EmitDtorEpilogue(CD);
1956 FinishFunction();
1957}