blob: 43eea15a69d8c7da9a256c99354111e2ce7d770a [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
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson774e7c62009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000200
Anders Carlssone9918d22009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000202
Anders Carlsson774e7c62009-04-03 22:50:24 +0000203 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000204 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
205 FPT->isVariadic());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000206 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000207
Anders Carlsson774e7c62009-04-03 22:50:24 +0000208 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000209 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000210 else {
211 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000212 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213 }
Mike Stumpf0070db2009-08-26 20:46:33 +0000214
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000215 // C++ [class.virtual]p12:
216 // Explicit qualification with the scope operator (5.1) suppresses the
217 // virtual call mechanism.
Mike Stumpf0070db2009-08-26 20:46:33 +0000218 llvm::Value *Callee;
Mike Stump63bb7c22009-08-26 23:38:08 +0000219 if (MD->isVirtual() && !isa<CXXQualifiedMemberExpr>(ME)) {
Mike Stumpf0070db2009-08-26 20:46:33 +0000220 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000221 } else
Mike Stumpf0070db2009-08-26 20:46:33 +0000222 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000223
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000224 return EmitCXXMemberCall(MD, Callee, This,
225 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000226}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000227
Anders Carlsson0f294632009-05-27 04:18:27 +0000228RValue
229CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
230 const CXXMethodDecl *MD) {
231 assert(MD->isInstance() &&
232 "Trying to emit a member call expr on a static method!");
233
Fariborz Jahanianad258832009-08-13 21:09:41 +0000234 if (MD->isCopyAssignment()) {
235 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
236 if (ClassDecl->hasTrivialCopyAssignment()) {
237 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
238 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
239 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
240 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
241 QualType Ty = E->getType();
242 EmitAggregateCopy(This, Src, Ty);
243 return RValue::get(This);
244 }
245 }
Anders Carlsson0f294632009-05-27 04:18:27 +0000246
247 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
248 const llvm::Type *Ty =
249 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
250 FPT->isVariadic());
251 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
252
253 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
254
255 return EmitCXXMemberCall(MD, Callee, This,
256 E->arg_begin() + 1, E->arg_end());
257}
258
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000259RValue
260CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
261 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
262 "EmitCXXFunctionalCastExpr - called with wrong cast");
263
264 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000265 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
266 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
267 " method decl");
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000268 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000269
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000270 const llvm::Type *Ty =
271 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
272 FPT->isVariadic());
273 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
274 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
275 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
276 if (RV.isAggregate())
277 RV = RValue::get(RV.getAggregateAddr());
278 return RV;
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000279}
280
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000281llvm::Value *CodeGenFunction::LoadCXXThis() {
282 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
283 "Must be in a C++ member function decl to load 'this'");
284 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
285 "Must be in a C++ member function decl to load 'this'");
286
287 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000288 // ans: See how CodeGenFunction::LoadObjCSelf() uses
289 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000290 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
291}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000292
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000293static bool
294GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
295 const CXXRecordDecl *ClassDecl,
296 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000297 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
298 e = ClassDecl->bases_end(); i != e; ++i) {
299 if (i->isVirtual())
300 continue;
301 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000302 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000303 if (Base == BaseClassDecl) {
304 NestedBasePaths.push_back(BaseClassDecl);
305 return true;
306 }
307 }
308 // BaseClassDecl not an immediate base of ClassDecl.
309 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
310 e = ClassDecl->bases_end(); i != e; ++i) {
311 if (i->isVirtual())
312 continue;
313 const CXXRecordDecl *Base =
314 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
315 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
316 NestedBasePaths.push_back(Base);
317 return true;
318 }
319 }
320 return false;
321}
322
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000323llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000324 const CXXRecordDecl *ClassDecl,
325 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000326 if (ClassDecl == BaseClassDecl)
327 return BaseValue;
328
Owen Anderson0032b272009-08-13 21:57:51 +0000329 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000330 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
331 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
332 assert(NestedBasePaths.size() > 0 &&
333 "AddressCXXOfBaseClass - inheritence path failed");
334 NestedBasePaths.push_back(ClassDecl);
335 uint64_t Offset = 0;
336
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000337 // Accessing a member of the base class. Must add delata to
338 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000339 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
340 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
341 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
342 const ASTRecordLayout &Layout =
343 getContext().getASTRecordLayout(DerivedClass);
344 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
345 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000346 llvm::Value *OffsetVal =
347 llvm::ConstantInt::get(
348 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000349 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
350 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
351 QualType BTy =
352 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000353 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000354 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000355 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000356 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
357 return BaseValue;
358}
359
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000360/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
361/// for-loop to call the default constructor on individual members of the
362/// array. 'Array' is the array type, 'This' is llvm pointer of the start
363/// of the array and 'D' is the default costructor Decl for elements of the
364/// array. It is assumed that all relevant checks have been made by the
365/// caller.
366void
367CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
368 const ArrayType *Array,
369 llvm::Value *This) {
370 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
371 assert(CA && "Do we support VLA for construction ?");
372
373 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000374 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000375 "loop.index");
376 llvm::Value* zeroConstant =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000377 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000378 Builder.CreateStore(zeroConstant, IndexPtr, false);
379
380 // Start the loop with a block that tests the condition.
381 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
382 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
383
384 EmitBlock(CondBlock);
385
386 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
387
388 // Generate: if (loop-index < number-of-elements fall to the loop body,
389 // otherwise, go to the block after the for-loop.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000390 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000391 llvm::Value * NumElementsPtr =
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000392 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000393 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
394 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
395 "isless");
396 // If the condition is true, execute the body.
397 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
398
399 EmitBlock(ForBody);
400
401 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000402 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000403 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000404 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
405 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000406
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000407 EmitBlock(ContinueBlock);
408
409 // Emit the increment of the loop counter.
410 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
411 Counter = Builder.CreateLoad(IndexPtr);
412 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
413 Builder.CreateStore(NextVal, IndexPtr, false);
414
415 // Finally, branch back up to the condition for the next iteration.
416 EmitBranch(CondBlock);
417
418 // Emit the fall-through block.
419 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000420}
421
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000422/// EmitCXXAggrDestructorCall - calls the default destructor on array
423/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000424void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000425CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
426 const ArrayType *Array,
427 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000428 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
429 assert(CA && "Do we support VLA for destruction ?");
430 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
431 1);
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000432 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000433 // Create a temporary for the loop index and initialize it with count of
434 // array elements.
435 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
436 "loop.index");
437 // Index = ElementCount;
438 llvm::Value* UpperCount =
439 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
440 Builder.CreateStore(UpperCount, IndexPtr, false);
441
442 // Start the loop with a block that tests the condition.
443 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
444 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
445
446 EmitBlock(CondBlock);
447
448 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
449
450 // Generate: if (loop-index != 0 fall to the loop body,
451 // otherwise, go to the block after the for-loop.
452 llvm::Value* zeroConstant =
453 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
454 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
455 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
456 "isne");
457 // If the condition is true, execute the body.
458 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
459
460 EmitBlock(ForBody);
461
462 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
463 // Inside the loop body, emit the constructor call on the array element.
464 Counter = Builder.CreateLoad(IndexPtr);
465 Counter = Builder.CreateSub(Counter, One);
466 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
467 EmitCXXDestructorCall(D, Dtor_Complete, Address);
468
469 EmitBlock(ContinueBlock);
470
471 // Emit the decrement of the loop counter.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One, "dec");
474 Builder.CreateStore(Counter, IndexPtr, false);
475
476 // Finally, branch back up to the condition for the next iteration.
477 EmitBranch(CondBlock);
478
479 // Emit the fall-through block.
480 EmitBlock(AfterFor, true);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000481}
482
483void
Anders Carlssonb14095a2009-04-17 00:06:03 +0000484CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
485 CXXCtorType Type,
486 llvm::Value *This,
487 CallExpr::const_arg_iterator ArgBeg,
488 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000489 if (D->isCopyConstructor(getContext())) {
490 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
491 if (ClassDecl->hasTrivialCopyConstructor()) {
492 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
493 "EmitCXXConstructorCall - user declared copy constructor");
494 const Expr *E = (*ArgBeg);
495 QualType Ty = E->getType();
496 llvm::Value *Src = EmitLValue(E).getAddress();
497 EmitAggregateCopy(This, Src, Ty);
498 return;
499 }
500 }
501
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000502 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
503
504 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000505}
506
Anders Carlsson7267c162009-05-29 21:03:38 +0000507void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
508 CXXDtorType Type,
509 llvm::Value *This) {
510 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, 0, 0);
513}
514
Anders Carlssonb14095a2009-04-17 00:06:03 +0000515void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000516CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
517 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000518 assert(Dest && "Must have a destination!");
519
520 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000521 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000522 if (RD->hasTrivialConstructor())
523 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000524
525 // Code gen optimization to eliminate copy constructor and return
526 // its first argument instead.
Anders Carlsson92f58222009-08-22 22:30:33 +0000527 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000528 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000529 EmitAggExpr((*i), Dest, false);
530 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000531 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000532 // Call the constructor.
533 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
534 E->arg_begin(), E->arg_end());
535}
536
Anders Carlssona00703d2009-05-31 01:40:14 +0000537llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000538 if (E->isArray()) {
539 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000540 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000541 }
542
543 QualType AllocType = E->getAllocatedType();
544 FunctionDecl *NewFD = E->getOperatorNew();
545 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
546
547 CallArgList NewArgs;
548
549 // The allocation size is the first argument.
550 QualType SizeTy = getContext().getSizeType();
551 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000552 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000553 getContext().getTypeSize(AllocType) / 8);
554
555 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
556
557 // Emit the rest of the arguments.
558 // FIXME: Ideally, this should just use EmitCallArgs.
559 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
560
561 // First, use the types from the function type.
562 // We start at 1 here because the first argument (the allocation size)
563 // has already been emitted.
564 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
565 QualType ArgType = NewFTy->getArgType(i);
566
567 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
568 getTypePtr() ==
569 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
570 "type mismatch in call argument!");
571
572 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
573 ArgType));
574
575 }
576
577 // Either we've emitted all the call args, or we have a call to a
578 // variadic function.
579 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
580 "Extra arguments in non-variadic function!");
581
582 // If we still have any arguments, emit them using the type of the argument.
583 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
584 NewArg != NewArgEnd; ++NewArg) {
585 QualType ArgType = NewArg->getType();
586 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
587 ArgType));
588 }
589
590 // Emit the call to new.
591 RValue RV =
592 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
593 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
594 NewArgs, NewFD);
595
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000596 // If an allocation function is declared with an empty exception specification
597 // it returns null to indicate failure to allocate storage. [expr.new]p13.
598 // (We don't need to check for null when there's no new initializer and
599 // we're allocating a POD type).
600 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
601 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000602
Anders Carlssonf1108532009-06-01 00:05:16 +0000603 llvm::BasicBlock *NewNull = 0;
604 llvm::BasicBlock *NewNotNull = 0;
605 llvm::BasicBlock *NewEnd = 0;
606
607 llvm::Value *NewPtr = RV.getScalarVal();
608
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000609 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000610 NewNull = createBasicBlock("new.null");
611 NewNotNull = createBasicBlock("new.notnull");
612 NewEnd = createBasicBlock("new.end");
613
614 llvm::Value *IsNull =
615 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000616 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000617 "isnull");
618
619 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
620 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000621 }
622
Anders Carlssonf1108532009-06-01 00:05:16 +0000623 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000624
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000625 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000626 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000627 assert(E->getNumConstructorArgs() == 1 &&
628 "Can only have one argument to initializer of POD type.");
629
630 const Expr *Init = E->getConstructorArg(0);
631
Anders Carlsson3923e952009-05-31 21:07:58 +0000632 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000633 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000634 else if (AllocType->isAnyComplexType())
635 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000636 else
637 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000638 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000639 } else {
640 // Call the constructor.
641 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000642
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000643 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
644 E->constructor_arg_begin(),
645 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000646 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000647
Anders Carlssonf1108532009-06-01 00:05:16 +0000648 if (NullCheckResult) {
649 Builder.CreateBr(NewEnd);
650 EmitBlock(NewNull);
651 Builder.CreateBr(NewEnd);
652 EmitBlock(NewEnd);
653
654 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
655 PHI->reserveOperandSpace(2);
656 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000657 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000658
659 NewPtr = PHI;
660 }
661
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000662 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000663}
664
Anders Carlsson60e282c2009-08-16 21:13:42 +0000665void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
666 if (E->isArrayForm()) {
667 ErrorUnsupported(E, "delete[] expression");
668 return;
669 };
670
671 QualType DeleteTy =
672 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
673
674 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
675
676 // Null check the pointer.
677 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
678 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
679
680 llvm::Value *IsNull =
681 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
682 "isnull");
683
684 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
685 EmitBlock(DeleteNotNull);
686
687 // Call the destructor if necessary.
688 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
689 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
690 if (!RD->hasTrivialDestructor()) {
691 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
692 if (Dtor->isVirtual()) {
693 ErrorUnsupported(E, "delete expression with virtual destructor");
694 return;
695 }
696
697 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
698 }
699 }
700 }
701
702 // Call delete.
703 FunctionDecl *DeleteFD = E->getOperatorDelete();
704 const FunctionProtoType *DeleteFTy =
705 DeleteFD->getType()->getAsFunctionProtoType();
706
707 CallArgList DeleteArgs;
708
709 QualType ArgTy = DeleteFTy->getArgType(0);
710 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
711 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
712
713 // Emit the call to delete.
714 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
715 DeleteArgs),
716 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
717 DeleteArgs, DeleteFD);
718
719 EmitBlock(DeleteEnd);
720}
721
Anders Carlsson27ae5362009-04-17 01:58:57 +0000722static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
723 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000724 // The class has base classes - we don't support that right now.
725 if (RD->getNumBases() > 0)
726 return false;
727
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000728 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
729 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000730 // We don't support ctors for fields that aren't POD.
731 if (!I->getType()->isPODType())
732 return false;
733 }
734
735 return true;
736}
737
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000738void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000739 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000740 ErrorUnsupported(D, "C++ constructor", true);
741 return;
742 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000743
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000744 EmitGlobal(GlobalDecl(D, Ctor_Complete));
745 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000746}
Anders Carlsson363c1842009-04-16 23:57:24 +0000747
Anders Carlsson27ae5362009-04-17 01:58:57 +0000748void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
749 CXXCtorType Type) {
750
751 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
752
753 CodeGenFunction(*this).GenerateCode(D, Fn);
754
755 SetFunctionDefinitionAttributes(D, Fn);
756 SetLLVMFunctionAttributesForDefinition(D, Fn);
757}
758
Anders Carlsson363c1842009-04-16 23:57:24 +0000759llvm::Function *
760CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
761 CXXCtorType Type) {
762 const llvm::FunctionType *FTy =
763 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
764
765 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000766 return cast<llvm::Function>(
767 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000768}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000769
770const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
771 CXXCtorType Type) {
772 llvm::SmallString<256> Name;
773 llvm::raw_svector_ostream Out(Name);
774 mangleCXXCtor(D, Type, Context, Out);
775
776 Name += '\0';
777 return UniqueMangledName(Name.begin(), Name.end());
778}
779
780void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
781 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
782 ErrorUnsupported(D, "C++ destructor", true);
783 return;
784 }
785
786 EmitCXXDestructor(D, Dtor_Complete);
787 EmitCXXDestructor(D, Dtor_Base);
788}
789
790void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
791 CXXDtorType Type) {
792 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
793
794 CodeGenFunction(*this).GenerateCode(D, Fn);
795
796 SetFunctionDefinitionAttributes(D, Fn);
797 SetLLVMFunctionAttributesForDefinition(D, Fn);
798}
799
800llvm::Function *
801CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
802 CXXDtorType Type) {
803 const llvm::FunctionType *FTy =
804 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
805
806 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000807 return cast<llvm::Function>(
808 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000809}
810
811const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
812 CXXDtorType Type) {
813 llvm::SmallString<256> Name;
814 llvm::raw_svector_ostream Out(Name);
815 mangleCXXDtor(D, Type, Context, Out);
816
817 Name += '\0';
818 return UniqueMangledName(Name.begin(), Name.end());
819}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000820
Mike Stump32f37012009-08-18 21:49:00 +0000821llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000822 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000823 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000824 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000825
826 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000827 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000828
829 llvm::SmallString<256> OutName;
830 llvm::raw_svector_ostream Out(OutName);
831 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000832 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000833 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000834 llvm::GlobalVariable::LinkageTypes linktype;
835 linktype = llvm::GlobalValue::WeakAnyLinkage;
836 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000837 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000838 // FIXME: descriptor
839 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000840 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000841 // FIXME: TS
842 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
843
844 llvm::Constant *C;
845 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
846 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000847 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000848 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000849 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
850 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000851}
852
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000853class VtableBuilder {
Mike Stumpf0070db2009-08-26 20:46:33 +0000854public:
855 /// Index_t - Vtable index type.
856 typedef uint64_t Index_t;
857private:
Mike Stump7c435fa2009-08-18 20:50:28 +0000858 std::vector<llvm::Constant *> &methods;
Mike Stump15a24e02009-08-28 23:22:54 +0000859 std::vector<llvm::Constant *> submethods;
Mike Stump7c435fa2009-08-18 20:50:28 +0000860 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000861 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000862 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000863 /// BLayout - Layout for the most derived class that this vtable is being
864 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000865 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000866 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000867 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000868 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000869 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000870 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-08-21 01:45:00 +0000871 /// Index - Maps a method decl into a vtable index. Useful for virtual
872 /// dispatch codegen.
Mike Stumpf0070db2009-08-26 20:46:33 +0000873 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stump15a24e02009-08-28 23:22:54 +0000874 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
875 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCallOffset;
876 std::vector<Index_t> VCalls;
Mike Stump552b2752009-08-18 22:04:08 +0000877 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000878public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000879 VtableBuilder(std::vector<llvm::Constant *> &meth,
880 const CXXRecordDecl *c,
881 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000882 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
883 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
884 CGM(cgm) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000885 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
886 }
Mike Stump32f37012009-08-18 21:49:00 +0000887
Mike Stumpf0070db2009-08-26 20:46:33 +0000888 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb46c92d2009-08-19 02:06:38 +0000889
Mike Stump15a24e02009-08-28 23:22:54 +0000890 llvm::Constant *wrap(Index_t i) {
891 llvm::Constant *m;
892 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
893 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stumpb46c92d2009-08-19 02:06:38 +0000894 }
895
Mike Stump15a24e02009-08-28 23:22:54 +0000896 llvm::Constant *wrap(llvm::Constant *m) {
897 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
Mike Stump80a0e322009-08-12 23:25:18 +0000898 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000899
Mike Stump7fa0d932009-08-20 02:11:48 +0000900 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000901 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000902 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
903 e = RD->bases_end(); i != e; ++i) {
904 const CXXRecordDecl *Base =
905 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
906 if (i->isVirtual() && !SeenVBase.count(Base)) {
907 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000908 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump15a24e02009-08-28 23:22:54 +0000909 llvm::Constant *m = wrap(BaseOffset);
910 m = wrap((0?700:0) + BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000911 offsets.push_back(m);
912 }
Mike Stumpb9837442009-08-20 07:22:17 +0000913 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000914 }
915 }
916
Mike Stumpb9871a22009-08-21 01:45:00 +0000917 void StartNewTable() {
918 SeenVBase.clear();
919 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000920
Mike Stump15a24e02009-08-28 23:22:54 +0000921 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint,
922 bool MorallyVirtual, Index_t Offset) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000923 typedef CXXMethodDecl::method_iterator meth_iter;
924
925 llvm::Constant *m;
Mike Stump15a24e02009-08-28 23:22:54 +0000926 m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stumpb9871a22009-08-21 01:45:00 +0000927
928 // FIXME: Don't like the nested loops. For very large inheritance
929 // heirarchies we could have a table on the side with the final overridder
930 // and just replace each instance of an overridden method once. Would be
931 // nice to measure the cost/benefit on real code.
932
933 // If we can find a previously allocated slot for this, reuse it.
934 for (meth_iter mi = MD->begin_overridden_methods(),
935 e = MD->end_overridden_methods();
936 mi != e; ++mi) {
937 const CXXMethodDecl *OMD = *mi;
938 llvm::Constant *om;
939 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
940 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
941
Mike Stump15a24e02009-08-28 23:22:54 +0000942 for (Index_t i = 0, e = submethods.size();
Mike Stumpf0070db2009-08-26 20:46:33 +0000943 i != e; ++i) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000944 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stump15a24e02009-08-28 23:22:54 +0000945 if (submethods[i] == om) {
946 // FIXME: thunks
947 submethods[i] = m;
948 Index[MD] = i;
949 if (MorallyVirtual) {
950 VCallOffset[MD] = Offset/8;
951 VCalls[VCall[OMD]] = Offset/8 - VCallOffset[OMD];
952 }
953 // submethods[VCall[OMD]] = wrap(Offset/8 - VCallOffset[OMD]);
Mike Stumpb9871a22009-08-21 01:45:00 +0000954 return;
955 }
Mike Stump65defe32009-08-18 21:03:28 +0000956 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000957 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000958
959 // else allocate a new slot.
Mike Stump15a24e02009-08-28 23:22:54 +0000960 Index[MD] = submethods.size();
961 // VCall[MD] = Offset;
962 if (MorallyVirtual) {
963 VCallOffset[MD] = Offset/8;
964 Index_t &idx = VCall[MD];
965 // Allocate the first one, after that, we reuse the previous one.
966 if (idx == 0) {
967 idx = VCalls.size()+1;
968 VCallOffset[MD] = Offset/8;
969 VCalls.push_back(0);
970 }
971 }
972 submethods.push_back(m);
Mike Stumpb9871a22009-08-21 01:45:00 +0000973 }
974
Mike Stump15a24e02009-08-28 23:22:54 +0000975 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
976 bool MorallyVirtual, Index_t Offset) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000977 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
978 ++mi)
979 if (mi->isVirtual())
Mike Stump15a24e02009-08-28 23:22:54 +0000980 AddMethod(*mi, AddressPoint, MorallyVirtual, Offset);
Mike Stumpbc16aea2009-08-12 23:00:59 +0000981 }
Mike Stump65defe32009-08-18 21:03:28 +0000982
Mike Stump263b3522009-08-21 23:09:30 +0000983 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stump15a24e02009-08-28 23:22:54 +0000984 bool forPrimary, bool Bottom,
985 bool MorallyVirtual,
Mike Stump263b3522009-08-21 23:09:30 +0000986 int64_t Offset,
Mike Stumpf0070db2009-08-26 20:46:33 +0000987 bool ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +0000988 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +0000989 int64_t AddressPoint=0;
Mike Stump276b9f12009-08-16 01:46:26 +0000990
Mike Stump109b13d2009-08-18 21:30:21 +0000991 if (RD && !RD->isDynamicClass())
Mike Stump263b3522009-08-21 23:09:30 +0000992 return 0;
Mike Stump109b13d2009-08-18 21:30:21 +0000993
994 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
995 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
996 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
997
Mike Stump15a24e02009-08-28 23:22:54 +0000998 std::vector<llvm::Constant *> offsets;
Mike Stump109b13d2009-08-18 21:30:21 +0000999 // FIXME: Audit, is this right?
Mike Stump15a24e02009-08-28 23:22:54 +00001000 if (Bottom && (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual
1001 || Bottom))
Mike Stumpb9837442009-08-20 07:22:17 +00001002 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001003
Mike Stump109b13d2009-08-18 21:30:21 +00001004 bool Top = true;
1005
1006 // vtables are composed from the chain of primaries.
1007 if (PrimaryBase) {
1008 if (PrimaryBaseWasVirtual)
1009 IndirectPrimary.insert(PrimaryBase);
1010 Top = false;
Mike Stump15a24e02009-08-28 23:22:54 +00001011 AddressPoint = GenerateVtableForBase(PrimaryBase, true, false,
1012 PrimaryBaseWasVirtual|MorallyVirtual,
Mike Stumpf0070db2009-08-26 20:46:33 +00001013 Offset, PrimaryBaseWasVirtual);
Mike Stump109b13d2009-08-18 21:30:21 +00001014 }
1015
Mike Stump15a24e02009-08-28 23:22:54 +00001016 // And add the virtuals for the class to the primary vtable.
1017 GenerateMethods(RD, AddressPoint, MorallyVirtual, Offset);
1018
1019 if (!Bottom)
1020 return AddressPoint;
1021
1022 StartNewTable();
1023 // FIXME: Cleanup.
1024 if (!ForVirtualBase) {
1025 // then virtual base offsets...
1026 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1027 e = offsets.rend(); i != e; ++i)
1028 methods.push_back(*i);
Mike Stump276b9f12009-08-16 01:46:26 +00001029 }
Mike Stump4ef98092009-08-13 22:53:07 +00001030
Mike Stump15a24e02009-08-28 23:22:54 +00001031 // The vcalls come first...
1032 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1033 i < e; ++i)
1034 methods.push_back(wrap((0?600:0) + *i));
1035 VCalls.clear();
1036
1037 if (ForVirtualBase) {
1038 // then virtual base offsets...
1039 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1040 e = offsets.rend(); i != e; ++i)
1041 methods.push_back(*i);
1042 }
1043
1044 int64_t BaseOffset;
1045 if (ForVirtualBase) {
1046 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1047 // FIXME: The above is redundant with the other case.
1048 assert(BaseOffset == -Offset/8);
1049 } else
1050 BaseOffset = -Offset/8;
1051 m = wrap(BaseOffset);
1052 methods.push_back(m);
1053 methods.push_back(rtti);
1054 AddressPoint = methods.size();
1055
1056 methods.insert(methods.end(), submethods.begin(), submethods.end());
1057 submethods.clear();
Mike Stump109b13d2009-08-18 21:30:21 +00001058
1059 // and then the non-virtual bases.
1060 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1061 e = RD->bases_end(); i != e; ++i) {
1062 if (i->isVirtual())
1063 continue;
1064 const CXXRecordDecl *Base =
1065 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1066 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1067 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001068 StartNewTable();
Mike Stump15a24e02009-08-28 23:22:54 +00001069 GenerateVtableForBase(Base, true, true, false, o, false);
Mike Stump109b13d2009-08-18 21:30:21 +00001070 }
1071 }
Mike Stump263b3522009-08-21 23:09:30 +00001072 return AddressPoint;
Mike Stump109b13d2009-08-18 21:30:21 +00001073 }
1074
1075 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001076 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001077 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1078 e = RD->bases_end(); i != e; ++i) {
1079 const CXXRecordDecl *Base =
1080 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1081 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1082 // Mark it so we don't output it twice.
1083 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001084 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001085 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump15a24e02009-08-28 23:22:54 +00001086 GenerateVtableForBase(Base, false, true, true, BaseOffset, true);
Mike Stump109b13d2009-08-18 21:30:21 +00001087 }
1088 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001089 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001090 }
1091 }
Mike Stump109b13d2009-08-18 21:30:21 +00001092};
Mike Stump8a12b562009-08-06 15:50:11 +00001093
Mike Stumpf0070db2009-08-26 20:46:33 +00001094class VtableInfo {
1095public:
1096 typedef VtableBuilder::Index_t Index_t;
1097private:
1098 CodeGenModule &CGM; // Per-module state.
1099 /// Index_t - Vtable index type.
1100 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1101 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1102 // FIXME: Move to Context.
1103 static MapTy IndexFor;
1104public:
1105 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1106 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1107 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1108 // We own a copy of this, it will go away shortly.
1109 new ElTy (e);
1110 IndexFor[RD] = new ElTy (e);
1111 }
1112 Index_t lookup(const CXXMethodDecl *MD) {
1113 const CXXRecordDecl *RD = MD->getParent();
1114 MapTy::iterator I = IndexFor.find(RD);
1115 if (I == IndexFor.end()) {
1116 std::vector<llvm::Constant *> methods;
1117 VtableBuilder b(methods, RD, CGM);
Mike Stump15a24e02009-08-28 23:22:54 +00001118 b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stumpf0070db2009-08-26 20:46:33 +00001119 b.GenerateVtableForVBases(RD, RD);
1120 register_index(RD, b.getIndex());
1121 I = IndexFor.find(RD);
1122 }
1123 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1124 return (*I->second)[MD];
1125 }
1126};
1127
1128// FIXME: Move to Context.
1129VtableInfo::MapTy VtableInfo::IndexFor;
1130
Mike Stumpf1216772009-07-31 18:25:34 +00001131llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001132 llvm::SmallString<256> OutName;
1133 llvm::raw_svector_ostream Out(OutName);
1134 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001135 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001136 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001137 llvm::GlobalVariable::LinkageTypes linktype;
1138 linktype = llvm::GlobalValue::WeakAnyLinkage;
1139 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001140 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump263b3522009-08-21 23:09:30 +00001141 int64_t Offset;
Mike Stump6f376332009-08-05 22:37:18 +00001142
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001143 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001144
Mike Stump276b9f12009-08-16 01:46:26 +00001145 // First comes the vtables for all the non-virtual bases...
Mike Stump15a24e02009-08-28 23:22:54 +00001146 Offset = b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stump21538912009-08-14 01:44:03 +00001147
Mike Stump276b9f12009-08-16 01:46:26 +00001148 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001149 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001150
Mike Stump82b56962009-07-31 21:43:43 +00001151 llvm::Constant *C;
1152 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1153 C = llvm::ConstantArray::get(type, methods);
1154 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001155 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001156 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001157 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001158 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump263b3522009-08-21 23:09:30 +00001159 Offset*LLVMPointerWidth/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001160 return vtable;
1161}
1162
Mike Stumpf0070db2009-08-26 20:46:33 +00001163// FIXME: move to Context
1164static VtableInfo *vtableinfo;
1165
1166llvm::Value *
1167CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1168 const llvm::Type *Ty) {
1169 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1170
1171 // FIXME: move to Context
1172 if (vtableinfo == 0)
1173 vtableinfo = new VtableInfo(CGM);
1174
1175 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1176
1177 Ty = llvm::PointerType::get(Ty, 0);
1178 Ty = llvm::PointerType::get(Ty, 0);
1179 Ty = llvm::PointerType::get(Ty, 0);
1180 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1181 vtbl = Builder.CreateLoad(vtbl);
1182 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1183 Idx, "vfn");
1184 vfn = Builder.CreateLoad(vfn);
1185 return vfn;
1186}
1187
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001188/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1189/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1190/// copy or via a copy constructor call.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +00001191// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001192void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1193 llvm::Value *Src,
1194 const ArrayType *Array,
1195 const CXXRecordDecl *BaseClassDecl,
1196 QualType Ty) {
1197 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1198 assert(CA && "VLA cannot be copied over");
1199 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1200
1201 // Create a temporary for the loop index and initialize it with 0.
1202 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1203 "loop.index");
1204 llvm::Value* zeroConstant =
1205 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1206 Builder.CreateStore(zeroConstant, IndexPtr, false);
1207 // Start the loop with a block that tests the condition.
1208 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1209 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1210
1211 EmitBlock(CondBlock);
1212
1213 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1214 // Generate: if (loop-index < number-of-elements fall to the loop body,
1215 // otherwise, go to the block after the for-loop.
1216 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1217 llvm::Value * NumElementsPtr =
1218 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1219 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1220 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1221 "isless");
1222 // If the condition is true, execute the body.
1223 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1224
1225 EmitBlock(ForBody);
1226 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1227 // Inside the loop body, emit the constructor call on the array element.
1228 Counter = Builder.CreateLoad(IndexPtr);
1229 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1230 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1231 if (BitwiseCopy)
1232 EmitAggregateCopy(Dest, Src, Ty);
1233 else if (CXXConstructorDecl *BaseCopyCtor =
1234 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1235 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1236 Ctor_Complete);
1237 CallArgList CallArgs;
1238 // Push the this (Dest) ptr.
1239 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1240 BaseCopyCtor->getThisType(getContext())));
1241
1242 // Push the Src ptr.
1243 CallArgs.push_back(std::make_pair(RValue::get(Src),
1244 BaseCopyCtor->getParamDecl(0)->getType()));
1245 QualType ResultType =
1246 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1247 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1248 Callee, CallArgs, BaseCopyCtor);
1249 }
1250 EmitBlock(ContinueBlock);
1251
1252 // Emit the increment of the loop counter.
1253 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1254 Counter = Builder.CreateLoad(IndexPtr);
1255 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1256 Builder.CreateStore(NextVal, IndexPtr, false);
1257
1258 // Finally, branch back up to the condition for the next iteration.
1259 EmitBranch(CondBlock);
1260
1261 // Emit the fall-through block.
1262 EmitBlock(AfterFor, true);
1263}
1264
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001265/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1266/// array of objects from SrcValue to DestValue. Assignment can be either a
1267/// bitwise assignment or via a copy assignment operator function call.
1268/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1269void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1270 llvm::Value *Src,
1271 const ArrayType *Array,
1272 const CXXRecordDecl *BaseClassDecl,
1273 QualType Ty) {
1274 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1275 assert(CA && "VLA cannot be asssigned");
1276 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1277
1278 // Create a temporary for the loop index and initialize it with 0.
1279 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1280 "loop.index");
1281 llvm::Value* zeroConstant =
1282 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1283 Builder.CreateStore(zeroConstant, IndexPtr, false);
1284 // Start the loop with a block that tests the condition.
1285 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1286 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1287
1288 EmitBlock(CondBlock);
1289
1290 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1291 // Generate: if (loop-index < number-of-elements fall to the loop body,
1292 // otherwise, go to the block after the for-loop.
1293 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1294 llvm::Value * NumElementsPtr =
1295 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1296 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1297 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1298 "isless");
1299 // If the condition is true, execute the body.
1300 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1301
1302 EmitBlock(ForBody);
1303 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1304 // Inside the loop body, emit the assignment operator call on array element.
1305 Counter = Builder.CreateLoad(IndexPtr);
1306 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1307 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1308 const CXXMethodDecl *MD = 0;
1309 if (BitwiseAssign)
1310 EmitAggregateCopy(Dest, Src, Ty);
1311 else {
1312 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1313 MD);
1314 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1315 (void)hasCopyAssign;
1316 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1317 const llvm::Type *LTy =
1318 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1319 FPT->isVariadic());
1320 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1321
1322 CallArgList CallArgs;
1323 // Push the this (Dest) ptr.
1324 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1325 MD->getThisType(getContext())));
1326
1327 // Push the Src ptr.
1328 CallArgs.push_back(std::make_pair(RValue::get(Src),
1329 MD->getParamDecl(0)->getType()));
1330 QualType ResultType =
1331 MD->getType()->getAsFunctionType()->getResultType();
1332 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1333 Callee, CallArgs, MD);
1334 }
1335 EmitBlock(ContinueBlock);
1336
1337 // Emit the increment of the loop counter.
1338 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1339 Counter = Builder.CreateLoad(IndexPtr);
1340 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1341 Builder.CreateStore(NextVal, IndexPtr, false);
1342
1343 // Finally, branch back up to the condition for the next iteration.
1344 EmitBranch(CondBlock);
1345
1346 // Emit the fall-through block.
1347 EmitBlock(AfterFor, true);
1348}
1349
Fariborz Jahanianca283612009-08-07 23:51:33 +00001350/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1351/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001352/// or via a copy constructor call.
Fariborz Jahanianca283612009-08-07 23:51:33 +00001353void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001354 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001355 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001356 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1357 if (ClassDecl) {
1358 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1359 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1360 }
1361 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1362 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001363 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001364 }
1365
Fariborz Jahanianca283612009-08-07 23:51:33 +00001366 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001367 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001368 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1369 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001370 CallArgList CallArgs;
1371 // Push the this (Dest) ptr.
1372 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1373 BaseCopyCtor->getThisType(getContext())));
1374
Fariborz Jahanianca283612009-08-07 23:51:33 +00001375 // Push the Src ptr.
1376 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001377 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001378 QualType ResultType =
1379 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1380 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1381 Callee, CallArgs, BaseCopyCtor);
1382 }
1383}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001384
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001385/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1386/// object from SrcValue to DestValue. Assignment can be either a bitwise
1387/// assignment of via an assignment operator call.
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001388// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001389void CodeGenFunction::EmitClassCopyAssignment(
1390 llvm::Value *Dest, llvm::Value *Src,
1391 const CXXRecordDecl *ClassDecl,
1392 const CXXRecordDecl *BaseClassDecl,
1393 QualType Ty) {
1394 if (ClassDecl) {
1395 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1396 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1397 }
1398 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1399 EmitAggregateCopy(Dest, Src, Ty);
1400 return;
1401 }
1402
1403 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001404 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1405 MD);
1406 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1407 (void)ConstCopyAssignOp;
1408
1409 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1410 const llvm::Type *LTy =
1411 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1412 FPT->isVariadic());
1413 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001414
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001415 CallArgList CallArgs;
1416 // Push the this (Dest) ptr.
1417 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1418 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001419
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001420 // Push the Src ptr.
1421 CallArgs.push_back(std::make_pair(RValue::get(Src),
1422 MD->getParamDecl(0)->getType()));
1423 QualType ResultType =
1424 MD->getType()->getAsFunctionType()->getResultType();
1425 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1426 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001427}
1428
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001429/// SynthesizeDefaultConstructor - synthesize a default constructor
1430void
1431CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1432 const FunctionDecl *FD,
1433 llvm::Function *Fn,
1434 const FunctionArgList &Args) {
1435 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1436 EmitCtorPrologue(CD);
1437 FinishFunction();
1438}
1439
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001440/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001441/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1442/// The implicitly-defined copy constructor for class X performs a memberwise
1443/// copy of its subobjects. The order of copying is the same as the order
1444/// of initialization of bases and members in a user-defined constructor
1445/// Each subobject is copied in the manner appropriate to its type:
1446/// if the subobject is of class type, the copy constructor for the class is
1447/// used;
1448/// if the subobject is an array, each element is copied, in the manner
1449/// appropriate to the element type;
1450/// if the subobject is of scalar type, the built-in assignment operator is
1451/// used.
1452/// Virtual base class subobjects shall be copied only once by the
1453/// implicitly-defined copy constructor
1454
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001455void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1456 const FunctionDecl *FD,
1457 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001458 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001459 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1460 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001461 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1462 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001463
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001464 FunctionArgList::const_iterator i = Args.begin();
1465 const VarDecl *ThisArg = i->first;
1466 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1467 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1468 const VarDecl *SrcArg = (i+1)->first;
1469 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1470 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1471
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001472 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1473 Base != ClassDecl->bases_end(); ++Base) {
1474 // FIXME. copy constrution of virtual base NYI
1475 if (Base->isVirtual())
1476 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001477
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001478 CXXRecordDecl *BaseClassDecl
1479 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001480 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1481 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001482 }
1483
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001484 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1485 FieldEnd = ClassDecl->field_end();
1486 Field != FieldEnd; ++Field) {
1487 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001488 const ConstantArrayType *Array =
1489 getContext().getAsConstantArrayType(FieldType);
1490 if (Array)
1491 FieldType = getContext().getBaseElementType(FieldType);
1492
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001493 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1494 CXXRecordDecl *FieldClassDecl
1495 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1496 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1497 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001498 if (Array) {
1499 const llvm::Type *BasePtr = ConvertType(FieldType);
1500 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1501 llvm::Value *DestBaseAddrPtr =
1502 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1503 llvm::Value *SrcBaseAddrPtr =
1504 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1505 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1506 FieldClassDecl, FieldType);
1507 }
1508 else
1509 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1510 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001511 continue;
1512 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001513 // Do a built-in assignment of scalar data members.
1514 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1515 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1516 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1517 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001518 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001519 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001520}
1521
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001522/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1523/// Before the implicitly-declared copy assignment operator for a class is
1524/// implicitly defined, all implicitly- declared copy assignment operators for
1525/// its direct base classes and its nonstatic data members shall have been
1526/// implicitly defined. [12.8-p12]
1527/// The implicitly-defined copy assignment operator for class X performs
1528/// memberwise assignment of its subob- jects. The direct base classes of X are
1529/// assigned first, in the order of their declaration in
1530/// the base-specifier-list, and then the immediate nonstatic data members of X
1531/// are assigned, in the order in which they were declared in the class
1532/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001533/// if the subobject is of class type, the copy assignment operator for the
1534/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001535/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001536///
1537/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001538/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001539///
1540/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001541/// used.
1542void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1543 const FunctionDecl *FD,
1544 llvm::Function *Fn,
1545 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001546
1547 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1548 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1549 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001550 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1551
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001552 FunctionArgList::const_iterator i = Args.begin();
1553 const VarDecl *ThisArg = i->first;
1554 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1555 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1556 const VarDecl *SrcArg = (i+1)->first;
1557 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1558 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1559
1560 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1561 Base != ClassDecl->bases_end(); ++Base) {
1562 // FIXME. copy assignment of virtual base NYI
1563 if (Base->isVirtual())
1564 continue;
1565
1566 CXXRecordDecl *BaseClassDecl
1567 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1568 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1569 Base->getType());
1570 }
1571
1572 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1573 FieldEnd = ClassDecl->field_end();
1574 Field != FieldEnd; ++Field) {
1575 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001576 const ConstantArrayType *Array =
1577 getContext().getAsConstantArrayType(FieldType);
1578 if (Array)
1579 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001580
1581 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1582 CXXRecordDecl *FieldClassDecl
1583 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1584 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1585 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001586 if (Array) {
1587 const llvm::Type *BasePtr = ConvertType(FieldType);
1588 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1589 llvm::Value *DestBaseAddrPtr =
1590 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1591 llvm::Value *SrcBaseAddrPtr =
1592 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1593 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1594 FieldClassDecl, FieldType);
1595 }
1596 else
1597 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1598 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001599 continue;
1600 }
1601 // Do a built-in assignment of scalar data members.
1602 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1603 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1604 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1605 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001606 }
1607
1608 // return *this;
1609 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001610
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001611 FinishFunction();
1612}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001613
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001614/// EmitCtorPrologue - This routine generates necessary code to initialize
1615/// base classes and non-static data members belonging to this constructor.
1616void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001617 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001618 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001619 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001620
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001621 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001622 E = CD->init_end();
1623 B != E; ++B) {
1624 CXXBaseOrMemberInitializer *Member = (*B);
1625 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001626 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001627 Type *BaseType = Member->getBaseClass();
1628 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001629 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001630 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1631 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001632 EmitCXXConstructorCall(Member->getConstructor(),
1633 Ctor_Complete, V,
1634 Member->const_arg_begin(),
1635 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001636 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001637 // non-static data member initilaizers.
1638 FieldDecl *Field = Member->getMember();
1639 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001640 const ConstantArrayType *Array =
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001641 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001642 if (Array)
1643 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001644
Mike Stumpf1216772009-07-31 18:25:34 +00001645 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001646 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001647 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001648 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001649 assert(Member->getConstructor() &&
1650 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001651 if (Array) {
1652 const llvm::Type *BasePtr = ConvertType(FieldType);
1653 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1654 llvm::Value *BaseAddrPtr =
1655 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1656 EmitCXXAggrConstructorCall(Member->getConstructor(),
1657 Array, BaseAddrPtr);
1658 }
1659 else
1660 EmitCXXConstructorCall(Member->getConstructor(),
1661 Ctor_Complete, LHS.getAddress(),
1662 Member->const_arg_begin(),
1663 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001664 continue;
1665 }
1666 else {
1667 // Initializing an anonymous union data member.
1668 FieldDecl *anonMember = Member->getAnonUnionMember();
1669 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1670 FieldType = anonMember->getType();
1671 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001672 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001673
1674 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001675 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001676 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001677 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001678 }
1679 }
Mike Stumpf1216772009-07-31 18:25:34 +00001680
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001681 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001682 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001683 // have bases classes and/or contain non-static data members which require
1684 // construction.
1685 for (CXXRecordDecl::base_class_const_iterator Base =
1686 ClassDecl->bases_begin();
1687 Base != ClassDecl->bases_end(); ++Base) {
1688 // FIXME. copy assignment of virtual base NYI
1689 if (Base->isVirtual())
1690 continue;
1691
1692 CXXRecordDecl *BaseClassDecl
1693 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1694 if (BaseClassDecl->hasTrivialConstructor())
1695 continue;
1696 if (CXXConstructorDecl *BaseCX =
1697 BaseClassDecl->getDefaultConstructor(getContext())) {
1698 LoadOfThis = LoadCXXThis();
1699 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1700 BaseClassDecl);
1701 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1702 }
1703 }
1704
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001705 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1706 FieldEnd = ClassDecl->field_end();
1707 Field != FieldEnd; ++Field) {
1708 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001709 const ConstantArrayType *Array =
1710 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001711 if (Array)
1712 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001713 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1714 continue;
1715 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001716 CXXRecordDecl *MemberClassDecl =
1717 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1718 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1719 continue;
1720 if (CXXConstructorDecl *MamberCX =
1721 MemberClassDecl->getDefaultConstructor(getContext())) {
1722 LoadOfThis = LoadCXXThis();
1723 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001724 if (Array) {
1725 const llvm::Type *BasePtr = ConvertType(FieldType);
1726 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1727 llvm::Value *BaseAddrPtr =
1728 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1729 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1730 }
1731 else
1732 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1733 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001734 }
1735 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001736 }
1737
Mike Stumpf1216772009-07-31 18:25:34 +00001738 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001739 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001740 if (!LoadOfThis)
1741 LoadOfThis = LoadCXXThis();
1742 llvm::Value *VtableField;
1743 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001744 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001745 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1746 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1747 llvm::Value *vtable = GenerateVtable(ClassDecl);
1748 Builder.CreateStore(vtable, VtableField);
1749 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001750}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001751
1752/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1753/// destructor. This is to call destructors on members and base classes
1754/// in reverse order of their construction.
1755void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1756 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1757 assert(!ClassDecl->isPolymorphic() &&
1758 "FIXME. polymorphic destruction not supported");
1759 (void)ClassDecl; // prevent warning.
1760
1761 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1762 *E = DD->destr_end(); B != E; ++B) {
1763 uintptr_t BaseOrMember = (*B);
1764 if (DD->isMemberToDestroy(BaseOrMember)) {
1765 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1766 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001767 const ConstantArrayType *Array =
1768 getContext().getAsConstantArrayType(FieldType);
1769 if (Array)
1770 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001771 const RecordType *RT = FieldType->getAs<RecordType>();
1772 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1773 if (FieldClassDecl->hasTrivialDestructor())
1774 continue;
1775 llvm::Value *LoadOfThis = LoadCXXThis();
1776 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001777 if (Array) {
1778 const llvm::Type *BasePtr = ConvertType(FieldType);
1779 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1780 llvm::Value *BaseAddrPtr =
1781 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1782 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1783 Array, BaseAddrPtr);
1784 }
1785 else
1786 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1787 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001788 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001789 const RecordType *RT =
1790 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1791 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1792 if (BaseClassDecl->hasTrivialDestructor())
1793 continue;
1794 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1795 ClassDecl,BaseClassDecl);
1796 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1797 Dtor_Complete, V);
1798 }
1799 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001800 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1801 return;
1802 // Case of destructor synthesis with fields and base classes
1803 // which have non-trivial destructors. They must be destructed in
1804 // reverse order of their construction.
1805 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1806
1807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1808 FieldEnd = ClassDecl->field_end();
1809 Field != FieldEnd; ++Field) {
1810 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001811 if (getContext().getAsConstantArrayType(FieldType))
1812 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001813 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1814 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1815 if (FieldClassDecl->hasTrivialDestructor())
1816 continue;
1817 DestructedFields.push_back(*Field);
1818 }
1819 }
1820 if (!DestructedFields.empty())
1821 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1822 FieldDecl *Field = DestructedFields[i];
1823 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001824 const ConstantArrayType *Array =
1825 getContext().getAsConstantArrayType(FieldType);
1826 if (Array)
1827 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001828 const RecordType *RT = FieldType->getAs<RecordType>();
1829 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1830 llvm::Value *LoadOfThis = LoadCXXThis();
1831 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001832 if (Array) {
1833 const llvm::Type *BasePtr = ConvertType(FieldType);
1834 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1835 llvm::Value *BaseAddrPtr =
1836 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1837 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1838 Array, BaseAddrPtr);
1839 }
1840 else
1841 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1842 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001843 }
1844
1845 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1846 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1847 Base != ClassDecl->bases_end(); ++Base) {
1848 // FIXME. copy assignment of virtual base NYI
1849 if (Base->isVirtual())
1850 continue;
1851
1852 CXXRecordDecl *BaseClassDecl
1853 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1854 if (BaseClassDecl->hasTrivialDestructor())
1855 continue;
1856 DestructedBases.push_back(BaseClassDecl);
1857 }
1858 if (DestructedBases.empty())
1859 return;
1860 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1861 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1862 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1863 ClassDecl,BaseClassDecl);
1864 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1865 Dtor_Complete, V);
1866 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001867}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001868
1869void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1870 const FunctionDecl *FD,
1871 llvm::Function *Fn,
1872 const FunctionArgList &Args) {
1873
1874 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1875 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1876 "SynthesizeDefaultDestructor - destructor has user declaration");
1877 (void) ClassDecl;
1878
1879 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1880 EmitDtorEpilogue(CD);
1881 FinishFunction();
1882}