blob: c72eca278cb4b0c7174ebb6dcfb27f31b21a6cac [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;
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000219 if (MD->isVirtual() && !isa<CXXQualifiedMemberExpr>(CE)) {
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();
265 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
266 llvm::Constant *Callee;
267 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD))
268 Callee = CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
269 else {
270 const llvm::Type *Ty =
271 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
272 FPT->isVariadic());
273 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
274 }
275 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
276
277 return EmitCXXMemberCall(MD, Callee, This, 0, 0);
278}
279
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000280llvm::Value *CodeGenFunction::LoadCXXThis() {
281 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
282 "Must be in a C++ member function decl to load 'this'");
283 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
284 "Must be in a C++ member function decl to load 'this'");
285
286 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000287 // ans: See how CodeGenFunction::LoadObjCSelf() uses
288 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000289 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
290}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000291
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000292static bool
293GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
294 const CXXRecordDecl *ClassDecl,
295 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000296 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
297 e = ClassDecl->bases_end(); i != e; ++i) {
298 if (i->isVirtual())
299 continue;
300 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000301 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000302 if (Base == BaseClassDecl) {
303 NestedBasePaths.push_back(BaseClassDecl);
304 return true;
305 }
306 }
307 // BaseClassDecl not an immediate base of ClassDecl.
308 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
309 e = ClassDecl->bases_end(); i != e; ++i) {
310 if (i->isVirtual())
311 continue;
312 const CXXRecordDecl *Base =
313 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
314 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
315 NestedBasePaths.push_back(Base);
316 return true;
317 }
318 }
319 return false;
320}
321
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000322llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000323 const CXXRecordDecl *ClassDecl,
324 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000325 if (ClassDecl == BaseClassDecl)
326 return BaseValue;
327
Owen Anderson0032b272009-08-13 21:57:51 +0000328 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000329 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
330 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
331 assert(NestedBasePaths.size() > 0 &&
332 "AddressCXXOfBaseClass - inheritence path failed");
333 NestedBasePaths.push_back(ClassDecl);
334 uint64_t Offset = 0;
335
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000336 // Accessing a member of the base class. Must add delata to
337 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000338 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
339 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
340 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
341 const ASTRecordLayout &Layout =
342 getContext().getASTRecordLayout(DerivedClass);
343 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
344 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000345 llvm::Value *OffsetVal =
346 llvm::ConstantInt::get(
347 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000348 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
349 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
350 QualType BTy =
351 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000352 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000353 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000354 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000355 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
356 return BaseValue;
357}
358
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000359/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
360/// for-loop to call the default constructor on individual members of the
361/// array. 'Array' is the array type, 'This' is llvm pointer of the start
362/// of the array and 'D' is the default costructor Decl for elements of the
363/// array. It is assumed that all relevant checks have been made by the
364/// caller.
365void
366CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
367 const ArrayType *Array,
368 llvm::Value *This) {
369 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
370 assert(CA && "Do we support VLA for construction ?");
371
372 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000373 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000374 "loop.index");
375 llvm::Value* zeroConstant =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000376 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000377 Builder.CreateStore(zeroConstant, IndexPtr, false);
378
379 // Start the loop with a block that tests the condition.
380 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
381 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
382
383 EmitBlock(CondBlock);
384
385 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
386
387 // Generate: if (loop-index < number-of-elements fall to the loop body,
388 // otherwise, go to the block after the for-loop.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000389 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000390 llvm::Value * NumElementsPtr =
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000391 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000392 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
393 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
394 "isless");
395 // If the condition is true, execute the body.
396 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
397
398 EmitBlock(ForBody);
399
400 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000401 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000402 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000403 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
404 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000405
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000406 EmitBlock(ContinueBlock);
407
408 // Emit the increment of the loop counter.
409 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
410 Counter = Builder.CreateLoad(IndexPtr);
411 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
412 Builder.CreateStore(NextVal, IndexPtr, false);
413
414 // Finally, branch back up to the condition for the next iteration.
415 EmitBranch(CondBlock);
416
417 // Emit the fall-through block.
418 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000419}
420
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000421/// EmitCXXAggrDestructorCall - calls the default destructor on array
422/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000423void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000424CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
425 const ArrayType *Array,
426 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000427 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
428 assert(CA && "Do we support VLA for destruction ?");
429 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
430 1);
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000431 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000432 // Create a temporary for the loop index and initialize it with count of
433 // array elements.
434 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
435 "loop.index");
436 // Index = ElementCount;
437 llvm::Value* UpperCount =
438 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
439 Builder.CreateStore(UpperCount, IndexPtr, false);
440
441 // Start the loop with a block that tests the condition.
442 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
443 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
444
445 EmitBlock(CondBlock);
446
447 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
448
449 // Generate: if (loop-index != 0 fall to the loop body,
450 // otherwise, go to the block after the for-loop.
451 llvm::Value* zeroConstant =
452 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
453 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
454 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
455 "isne");
456 // If the condition is true, execute the body.
457 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
458
459 EmitBlock(ForBody);
460
461 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
462 // Inside the loop body, emit the constructor call on the array element.
463 Counter = Builder.CreateLoad(IndexPtr);
464 Counter = Builder.CreateSub(Counter, One);
465 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
466 EmitCXXDestructorCall(D, Dtor_Complete, Address);
467
468 EmitBlock(ContinueBlock);
469
470 // Emit the decrement of the loop counter.
471 Counter = Builder.CreateLoad(IndexPtr);
472 Counter = Builder.CreateSub(Counter, One, "dec");
473 Builder.CreateStore(Counter, IndexPtr, false);
474
475 // Finally, branch back up to the condition for the next iteration.
476 EmitBranch(CondBlock);
477
478 // Emit the fall-through block.
479 EmitBlock(AfterFor, true);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000480}
481
482void
Anders Carlssonb14095a2009-04-17 00:06:03 +0000483CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
484 CXXCtorType Type,
485 llvm::Value *This,
486 CallExpr::const_arg_iterator ArgBeg,
487 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000488 if (D->isCopyConstructor(getContext())) {
489 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
490 if (ClassDecl->hasTrivialCopyConstructor()) {
491 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
492 "EmitCXXConstructorCall - user declared copy constructor");
493 const Expr *E = (*ArgBeg);
494 QualType Ty = E->getType();
495 llvm::Value *Src = EmitLValue(E).getAddress();
496 EmitAggregateCopy(This, Src, Ty);
497 return;
498 }
499 }
500
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000501 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
502
503 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000504}
505
Anders Carlsson7267c162009-05-29 21:03:38 +0000506void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
507 CXXDtorType Type,
508 llvm::Value *This) {
509 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
510
511 EmitCXXMemberCall(D, Callee, This, 0, 0);
512}
513
Anders Carlssonb14095a2009-04-17 00:06:03 +0000514void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000515CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
516 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000517 assert(Dest && "Must have a destination!");
518
519 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000520 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000521 if (RD->hasTrivialConstructor())
522 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000523
524 // Code gen optimization to eliminate copy constructor and return
525 // its first argument instead.
Anders Carlsson92f58222009-08-22 22:30:33 +0000526 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000527 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000528 EmitAggExpr((*i), Dest, false);
529 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000530 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000531 // Call the constructor.
532 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
533 E->arg_begin(), E->arg_end());
534}
535
Anders Carlssona00703d2009-05-31 01:40:14 +0000536llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000537 if (E->isArray()) {
538 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000539 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000540 }
541
542 QualType AllocType = E->getAllocatedType();
543 FunctionDecl *NewFD = E->getOperatorNew();
544 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
545
546 CallArgList NewArgs;
547
548 // The allocation size is the first argument.
549 QualType SizeTy = getContext().getSizeType();
550 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000551 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000552 getContext().getTypeSize(AllocType) / 8);
553
554 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
555
556 // Emit the rest of the arguments.
557 // FIXME: Ideally, this should just use EmitCallArgs.
558 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
559
560 // First, use the types from the function type.
561 // We start at 1 here because the first argument (the allocation size)
562 // has already been emitted.
563 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
564 QualType ArgType = NewFTy->getArgType(i);
565
566 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
567 getTypePtr() ==
568 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
569 "type mismatch in call argument!");
570
571 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
572 ArgType));
573
574 }
575
576 // Either we've emitted all the call args, or we have a call to a
577 // variadic function.
578 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
579 "Extra arguments in non-variadic function!");
580
581 // If we still have any arguments, emit them using the type of the argument.
582 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
583 NewArg != NewArgEnd; ++NewArg) {
584 QualType ArgType = NewArg->getType();
585 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
586 ArgType));
587 }
588
589 // Emit the call to new.
590 RValue RV =
591 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
592 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
593 NewArgs, NewFD);
594
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000595 // If an allocation function is declared with an empty exception specification
596 // it returns null to indicate failure to allocate storage. [expr.new]p13.
597 // (We don't need to check for null when there's no new initializer and
598 // we're allocating a POD type).
599 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
600 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000601
Anders Carlssonf1108532009-06-01 00:05:16 +0000602 llvm::BasicBlock *NewNull = 0;
603 llvm::BasicBlock *NewNotNull = 0;
604 llvm::BasicBlock *NewEnd = 0;
605
606 llvm::Value *NewPtr = RV.getScalarVal();
607
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000608 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000609 NewNull = createBasicBlock("new.null");
610 NewNotNull = createBasicBlock("new.notnull");
611 NewEnd = createBasicBlock("new.end");
612
613 llvm::Value *IsNull =
614 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000615 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000616 "isnull");
617
618 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
619 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000620 }
621
Anders Carlssonf1108532009-06-01 00:05:16 +0000622 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000623
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000624 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000625 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000626 assert(E->getNumConstructorArgs() == 1 &&
627 "Can only have one argument to initializer of POD type.");
628
629 const Expr *Init = E->getConstructorArg(0);
630
Anders Carlsson3923e952009-05-31 21:07:58 +0000631 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000632 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000633 else if (AllocType->isAnyComplexType())
634 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000635 else
636 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000637 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000638 } else {
639 // Call the constructor.
640 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000641
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000642 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
643 E->constructor_arg_begin(),
644 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000645 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000646
Anders Carlssonf1108532009-06-01 00:05:16 +0000647 if (NullCheckResult) {
648 Builder.CreateBr(NewEnd);
649 EmitBlock(NewNull);
650 Builder.CreateBr(NewEnd);
651 EmitBlock(NewEnd);
652
653 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
654 PHI->reserveOperandSpace(2);
655 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000656 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000657
658 NewPtr = PHI;
659 }
660
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000661 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000662}
663
Anders Carlsson60e282c2009-08-16 21:13:42 +0000664void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
665 if (E->isArrayForm()) {
666 ErrorUnsupported(E, "delete[] expression");
667 return;
668 };
669
670 QualType DeleteTy =
671 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
672
673 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
674
675 // Null check the pointer.
676 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
677 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
678
679 llvm::Value *IsNull =
680 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
681 "isnull");
682
683 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
684 EmitBlock(DeleteNotNull);
685
686 // Call the destructor if necessary.
687 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
688 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
689 if (!RD->hasTrivialDestructor()) {
690 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
691 if (Dtor->isVirtual()) {
692 ErrorUnsupported(E, "delete expression with virtual destructor");
693 return;
694 }
695
696 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
697 }
698 }
699 }
700
701 // Call delete.
702 FunctionDecl *DeleteFD = E->getOperatorDelete();
703 const FunctionProtoType *DeleteFTy =
704 DeleteFD->getType()->getAsFunctionProtoType();
705
706 CallArgList DeleteArgs;
707
708 QualType ArgTy = DeleteFTy->getArgType(0);
709 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
710 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
711
712 // Emit the call to delete.
713 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
714 DeleteArgs),
715 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
716 DeleteArgs, DeleteFD);
717
718 EmitBlock(DeleteEnd);
719}
720
Anders Carlsson27ae5362009-04-17 01:58:57 +0000721static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
722 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000723 // The class has base classes - we don't support that right now.
724 if (RD->getNumBases() > 0)
725 return false;
726
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000727 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
728 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000729 // We don't support ctors for fields that aren't POD.
730 if (!I->getType()->isPODType())
731 return false;
732 }
733
734 return true;
735}
736
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000737void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000738 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000739 ErrorUnsupported(D, "C++ constructor", true);
740 return;
741 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000742
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000743 EmitGlobal(GlobalDecl(D, Ctor_Complete));
744 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000745}
Anders Carlsson363c1842009-04-16 23:57:24 +0000746
Anders Carlsson27ae5362009-04-17 01:58:57 +0000747void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
748 CXXCtorType Type) {
749
750 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
751
752 CodeGenFunction(*this).GenerateCode(D, Fn);
753
754 SetFunctionDefinitionAttributes(D, Fn);
755 SetLLVMFunctionAttributesForDefinition(D, Fn);
756}
757
Anders Carlsson363c1842009-04-16 23:57:24 +0000758llvm::Function *
759CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
760 CXXCtorType Type) {
761 const llvm::FunctionType *FTy =
762 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
763
764 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000765 return cast<llvm::Function>(
766 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000767}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000768
769const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
770 CXXCtorType Type) {
771 llvm::SmallString<256> Name;
772 llvm::raw_svector_ostream Out(Name);
773 mangleCXXCtor(D, Type, Context, Out);
774
775 Name += '\0';
776 return UniqueMangledName(Name.begin(), Name.end());
777}
778
779void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
780 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
781 ErrorUnsupported(D, "C++ destructor", true);
782 return;
783 }
784
785 EmitCXXDestructor(D, Dtor_Complete);
786 EmitCXXDestructor(D, Dtor_Base);
787}
788
789void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
790 CXXDtorType Type) {
791 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
792
793 CodeGenFunction(*this).GenerateCode(D, Fn);
794
795 SetFunctionDefinitionAttributes(D, Fn);
796 SetLLVMFunctionAttributesForDefinition(D, Fn);
797}
798
799llvm::Function *
800CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
801 CXXDtorType Type) {
802 const llvm::FunctionType *FTy =
803 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
804
805 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000806 return cast<llvm::Function>(
807 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000808}
809
810const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
811 CXXDtorType Type) {
812 llvm::SmallString<256> Name;
813 llvm::raw_svector_ostream Out(Name);
814 mangleCXXDtor(D, Type, Context, Out);
815
816 Name += '\0';
817 return UniqueMangledName(Name.begin(), Name.end());
818}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000819
Mike Stump32f37012009-08-18 21:49:00 +0000820llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000821 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000822 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000823 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000824
825 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000826 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000827
828 llvm::SmallString<256> OutName;
829 llvm::raw_svector_ostream Out(OutName);
830 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000831 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000832 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000833 llvm::GlobalVariable::LinkageTypes linktype;
834 linktype = llvm::GlobalValue::WeakAnyLinkage;
835 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000836 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000837 // FIXME: descriptor
838 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000839 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000840 // FIXME: TS
841 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
842
843 llvm::Constant *C;
844 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
845 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000846 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000847 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000848 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
849 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000850}
851
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000852class VtableBuilder {
Mike Stumpf0070db2009-08-26 20:46:33 +0000853public:
854 /// Index_t - Vtable index type.
855 typedef uint64_t Index_t;
856private:
Mike Stump7c435fa2009-08-18 20:50:28 +0000857 std::vector<llvm::Constant *> &methods;
858 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000859 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000860 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000861 /// BLayout - Layout for the most derived class that this vtable is being
862 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000863 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000864 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000865 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000866 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000867 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000868 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-08-21 01:45:00 +0000869 /// Index - Maps a method decl into a vtable index. Useful for virtual
870 /// dispatch codegen.
Mike Stumpf0070db2009-08-26 20:46:33 +0000871 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stump552b2752009-08-18 22:04:08 +0000872 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000873public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000874 VtableBuilder(std::vector<llvm::Constant *> &meth,
875 const CXXRecordDecl *c,
876 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000877 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
878 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
879 CGM(cgm) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000880 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
881 }
Mike Stump32f37012009-08-18 21:49:00 +0000882
Mike Stumpf0070db2009-08-26 20:46:33 +0000883 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb46c92d2009-08-19 02:06:38 +0000884 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
885 const CXXRecordDecl *RD,
886 bool VBoundary,
887 bool SecondaryVirtual) {
Mike Stump263b3522009-08-21 23:09:30 +0000888 typedef CXXMethodDecl::method_iterator meth_iter;
889 // No vcall for methods that don't override in primary vtables.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000890 llvm::Constant *m = 0;
891
Mike Stumpb46c92d2009-08-19 02:06:38 +0000892 if (SecondaryVirtual || VBoundary)
893 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +0000894
895 int64_t Offset = 0;
896 int64_t BaseOffset = 0;
897 for (meth_iter mi = MD->begin_overridden_methods(),
898 me = MD->end_overridden_methods();
899 mi != me; ++mi) {
900 const CXXRecordDecl *DefBase = (*mi)->getParent();
901 // FIXME: vcall: offset for virtual base for this function
902 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
903 // m = llvm::Constant::getNullValue(Ptr8Ty);
904 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
905 e = RD->bases_end(); i != e; ++i) {
906 const CXXRecordDecl *Base =
907 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
908 if (DefBase == Base) {
909 if (!i->isVirtual())
910 break;
911
912 // FIXME: drop the 700-, just for debugging
913 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
914 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
915 BaseOffset);
916 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
917 break;
918 } else {
919 // FIXME: more searching.
920 (void)Offset;
921 }
922 }
923 }
924
Mike Stumpb46c92d2009-08-19 02:06:38 +0000925 return m;
926 }
927
928 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
929 bool SecondaryVirtual) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000930 llvm::Constant *m;
Mike Stump80a0e322009-08-12 23:25:18 +0000931
Mike Stump552b2752009-08-18 22:04:08 +0000932 for (method_iter mi = RD->method_begin(),
Mike Stump7c435fa2009-08-18 20:50:28 +0000933 me = RD->method_end(); mi != me; ++mi) {
934 if (mi->isVirtual()) {
Mike Stumpb46c92d2009-08-19 02:06:38 +0000935 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
936 if (m)
937 methods.push_back(m);
Mike Stump7c435fa2009-08-18 20:50:28 +0000938 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000939 }
Mike Stump80a0e322009-08-12 23:25:18 +0000940 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000941
Mike Stump7fa0d932009-08-20 02:11:48 +0000942 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000943 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000944 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
945 e = RD->bases_end(); i != e; ++i) {
946 const CXXRecordDecl *Base =
947 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
948 if (i->isVirtual() && !SeenVBase.count(Base)) {
949 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000950 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump7fa0d932009-08-20 02:11:48 +0000951 llvm::Constant *m;
Mike Stumpb9837442009-08-20 07:22:17 +0000952 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000953 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
954 offsets.push_back(m);
955 }
Mike Stumpb9837442009-08-20 07:22:17 +0000956 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000957 }
958 }
959
Mike Stumpb9871a22009-08-21 01:45:00 +0000960 void StartNewTable() {
961 SeenVBase.clear();
962 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000963
Mike Stumpf0070db2009-08-26 20:46:33 +0000964 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000965 typedef CXXMethodDecl::method_iterator meth_iter;
966
967 llvm::Constant *m;
968 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
969 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
970
971 // FIXME: Don't like the nested loops. For very large inheritance
972 // heirarchies we could have a table on the side with the final overridder
973 // and just replace each instance of an overridden method once. Would be
974 // nice to measure the cost/benefit on real code.
975
976 // If we can find a previously allocated slot for this, reuse it.
977 for (meth_iter mi = MD->begin_overridden_methods(),
978 e = MD->end_overridden_methods();
979 mi != e; ++mi) {
980 const CXXMethodDecl *OMD = *mi;
981 llvm::Constant *om;
982 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
983 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
984
Mike Stumpf0070db2009-08-26 20:46:33 +0000985 for (Index_t i = AddressPoint, e = methods.size();
986 i != e; ++i) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000987 // FIXME: begin_overridden_methods might be too lax, covariance */
988 if (methods[i] == om) {
989 methods[i] = m;
Mike Stumpf0070db2009-08-26 20:46:33 +0000990 Index[MD] = i - AddressPoint;
Mike Stumpb9871a22009-08-21 01:45:00 +0000991 return;
992 }
Mike Stump65defe32009-08-18 21:03:28 +0000993 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000994 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000995
996 // else allocate a new slot.
Mike Stumpf0070db2009-08-26 20:46:33 +0000997 Index[MD] = methods.size() - AddressPoint;
Mike Stumpb9871a22009-08-21 01:45:00 +0000998 methods.push_back(m);
999 }
1000
Mike Stumpf0070db2009-08-26 20:46:33 +00001001 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint) {
Mike Stumpb9871a22009-08-21 01:45:00 +00001002 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
1003 ++mi)
1004 if (mi->isVirtual())
Mike Stumpf0070db2009-08-26 20:46:33 +00001005 AddMethod(*mi, AddressPoint);
Mike Stumpbc16aea2009-08-12 23:00:59 +00001006 }
Mike Stump65defe32009-08-18 21:03:28 +00001007
Mike Stump263b3522009-08-21 23:09:30 +00001008 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
1009 bool forPrimary,
1010 bool VBoundary,
1011 int64_t Offset,
Mike Stumpf0070db2009-08-26 20:46:33 +00001012 bool ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001013 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +00001014 int64_t AddressPoint=0;
Mike Stump276b9f12009-08-16 01:46:26 +00001015
Mike Stump109b13d2009-08-18 21:30:21 +00001016 if (RD && !RD->isDynamicClass())
Mike Stump263b3522009-08-21 23:09:30 +00001017 return 0;
Mike Stump109b13d2009-08-18 21:30:21 +00001018
1019 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1020 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1021 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1022
Mike Stumpb46c92d2009-08-19 02:06:38 +00001023 if (VBoundary || forPrimary || ForVirtualBase) {
1024 // then comes the the vcall offsets for all our functions...
1025 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1026 }
1027
Mike Stump109b13d2009-08-18 21:30:21 +00001028 // The virtual base offsets come first...
1029 // FIXME: Audit, is this right?
Mike Stump09765ec2009-08-19 02:53:08 +00001030 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump109b13d2009-08-18 21:30:21 +00001031 std::vector<llvm::Constant *> offsets;
Mike Stumpb9837442009-08-20 07:22:17 +00001032 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001033 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1034 e = offsets.rend(); i != e; ++i)
1035 methods.push_back(*i);
1036 }
1037
Mike Stump109b13d2009-08-18 21:30:21 +00001038 bool Top = true;
1039
1040 // vtables are composed from the chain of primaries.
1041 if (PrimaryBase) {
1042 if (PrimaryBaseWasVirtual)
1043 IndirectPrimary.insert(PrimaryBase);
1044 Top = false;
Mike Stumpf0070db2009-08-26 20:46:33 +00001045 AddressPoint = GenerateVtableForBase(PrimaryBase, true,
1046 PrimaryBaseWasVirtual|VBoundary,
1047 Offset, PrimaryBaseWasVirtual);
Mike Stump109b13d2009-08-18 21:30:21 +00001048 }
1049
1050 if (Top) {
1051 int64_t BaseOffset;
1052 if (ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001053 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1054 } else
1055 BaseOffset = -Offset/8;
Mike Stump276b9f12009-08-16 01:46:26 +00001056 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1057 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1058 methods.push_back(m);
Mike Stump109b13d2009-08-18 21:30:21 +00001059 methods.push_back(rtti);
Mike Stump263b3522009-08-21 23:09:30 +00001060 AddressPoint = methods.size();
Mike Stump276b9f12009-08-16 01:46:26 +00001061 }
Mike Stump4ef98092009-08-13 22:53:07 +00001062
Mike Stump109b13d2009-08-18 21:30:21 +00001063 // And add the virtuals for the class to the primary vtable.
Mike Stumpf0070db2009-08-26 20:46:33 +00001064 GenerateMethods(RD, AddressPoint);
Mike Stump109b13d2009-08-18 21:30:21 +00001065
1066 // and then the non-virtual bases.
1067 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1068 e = RD->bases_end(); i != e; ++i) {
1069 if (i->isVirtual())
1070 continue;
1071 const CXXRecordDecl *Base =
1072 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1073 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1074 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001075 StartNewTable();
Mike Stumpf0070db2009-08-26 20:46:33 +00001076 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump109b13d2009-08-18 21:30:21 +00001077 }
1078 }
Mike Stump263b3522009-08-21 23:09:30 +00001079 return AddressPoint;
Mike Stump109b13d2009-08-18 21:30:21 +00001080 }
1081
1082 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001083 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001084 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1085 e = RD->bases_end(); i != e; ++i) {
1086 const CXXRecordDecl *Base =
1087 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1088 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1089 // Mark it so we don't output it twice.
1090 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001091 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001092 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf0070db2009-08-26 20:46:33 +00001093 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump109b13d2009-08-18 21:30:21 +00001094 }
1095 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001096 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001097 }
1098 }
Mike Stump109b13d2009-08-18 21:30:21 +00001099};
Mike Stump8a12b562009-08-06 15:50:11 +00001100
Mike Stumpf0070db2009-08-26 20:46:33 +00001101class VtableInfo {
1102public:
1103 typedef VtableBuilder::Index_t Index_t;
1104private:
1105 CodeGenModule &CGM; // Per-module state.
1106 /// Index_t - Vtable index type.
1107 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1108 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1109 // FIXME: Move to Context.
1110 static MapTy IndexFor;
1111public:
1112 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1113 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1114 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1115 // We own a copy of this, it will go away shortly.
1116 new ElTy (e);
1117 IndexFor[RD] = new ElTy (e);
1118 }
1119 Index_t lookup(const CXXMethodDecl *MD) {
1120 const CXXRecordDecl *RD = MD->getParent();
1121 MapTy::iterator I = IndexFor.find(RD);
1122 if (I == IndexFor.end()) {
1123 std::vector<llvm::Constant *> methods;
1124 VtableBuilder b(methods, RD, CGM);
1125 b.GenerateVtableForBase(RD, true, false, 0, false);
1126 b.GenerateVtableForVBases(RD, RD);
1127 register_index(RD, b.getIndex());
1128 I = IndexFor.find(RD);
1129 }
1130 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1131 return (*I->second)[MD];
1132 }
1133};
1134
1135// FIXME: Move to Context.
1136VtableInfo::MapTy VtableInfo::IndexFor;
1137
Mike Stumpf1216772009-07-31 18:25:34 +00001138llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001139 llvm::SmallString<256> OutName;
1140 llvm::raw_svector_ostream Out(OutName);
1141 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001142 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001143 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001144 llvm::GlobalVariable::LinkageTypes linktype;
1145 linktype = llvm::GlobalValue::WeakAnyLinkage;
1146 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001147 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump263b3522009-08-21 23:09:30 +00001148 int64_t Offset;
Mike Stump6f376332009-08-05 22:37:18 +00001149
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001150 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001151
Mike Stump276b9f12009-08-16 01:46:26 +00001152 // First comes the vtables for all the non-virtual bases...
Mike Stumpf0070db2009-08-26 20:46:33 +00001153 Offset = b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump21538912009-08-14 01:44:03 +00001154
Mike Stump276b9f12009-08-16 01:46:26 +00001155 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001156 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001157
Mike Stump82b56962009-07-31 21:43:43 +00001158 llvm::Constant *C;
1159 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1160 C = llvm::ConstantArray::get(type, methods);
1161 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001162 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001163 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001164 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001165 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump263b3522009-08-21 23:09:30 +00001166 Offset*LLVMPointerWidth/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001167 return vtable;
1168}
1169
Mike Stumpf0070db2009-08-26 20:46:33 +00001170// FIXME: move to Context
1171static VtableInfo *vtableinfo;
1172
1173llvm::Value *
1174CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1175 const llvm::Type *Ty) {
1176 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1177
1178 // FIXME: move to Context
1179 if (vtableinfo == 0)
1180 vtableinfo = new VtableInfo(CGM);
1181
1182 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1183
1184 Ty = llvm::PointerType::get(Ty, 0);
1185 Ty = llvm::PointerType::get(Ty, 0);
1186 Ty = llvm::PointerType::get(Ty, 0);
1187 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1188 vtbl = Builder.CreateLoad(vtbl);
1189 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1190 Idx, "vfn");
1191 vfn = Builder.CreateLoad(vfn);
1192 return vfn;
1193}
1194
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001195/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1196/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1197/// copy or via a copy constructor call.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +00001198// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001199void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1200 llvm::Value *Src,
1201 const ArrayType *Array,
1202 const CXXRecordDecl *BaseClassDecl,
1203 QualType Ty) {
1204 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1205 assert(CA && "VLA cannot be copied over");
1206 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1207
1208 // Create a temporary for the loop index and initialize it with 0.
1209 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1210 "loop.index");
1211 llvm::Value* zeroConstant =
1212 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1213 Builder.CreateStore(zeroConstant, IndexPtr, false);
1214 // Start the loop with a block that tests the condition.
1215 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1216 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1217
1218 EmitBlock(CondBlock);
1219
1220 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1221 // Generate: if (loop-index < number-of-elements fall to the loop body,
1222 // otherwise, go to the block after the for-loop.
1223 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1224 llvm::Value * NumElementsPtr =
1225 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1226 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1227 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1228 "isless");
1229 // If the condition is true, execute the body.
1230 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1231
1232 EmitBlock(ForBody);
1233 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1234 // Inside the loop body, emit the constructor call on the array element.
1235 Counter = Builder.CreateLoad(IndexPtr);
1236 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1237 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1238 if (BitwiseCopy)
1239 EmitAggregateCopy(Dest, Src, Ty);
1240 else if (CXXConstructorDecl *BaseCopyCtor =
1241 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1242 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1243 Ctor_Complete);
1244 CallArgList CallArgs;
1245 // Push the this (Dest) ptr.
1246 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1247 BaseCopyCtor->getThisType(getContext())));
1248
1249 // Push the Src ptr.
1250 CallArgs.push_back(std::make_pair(RValue::get(Src),
1251 BaseCopyCtor->getParamDecl(0)->getType()));
1252 QualType ResultType =
1253 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1254 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1255 Callee, CallArgs, BaseCopyCtor);
1256 }
1257 EmitBlock(ContinueBlock);
1258
1259 // Emit the increment of the loop counter.
1260 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1261 Counter = Builder.CreateLoad(IndexPtr);
1262 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1263 Builder.CreateStore(NextVal, IndexPtr, false);
1264
1265 // Finally, branch back up to the condition for the next iteration.
1266 EmitBranch(CondBlock);
1267
1268 // Emit the fall-through block.
1269 EmitBlock(AfterFor, true);
1270}
1271
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001272/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1273/// array of objects from SrcValue to DestValue. Assignment can be either a
1274/// bitwise assignment or via a copy assignment operator function call.
1275/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1276void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1277 llvm::Value *Src,
1278 const ArrayType *Array,
1279 const CXXRecordDecl *BaseClassDecl,
1280 QualType Ty) {
1281 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1282 assert(CA && "VLA cannot be asssigned");
1283 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1284
1285 // Create a temporary for the loop index and initialize it with 0.
1286 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1287 "loop.index");
1288 llvm::Value* zeroConstant =
1289 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1290 Builder.CreateStore(zeroConstant, IndexPtr, false);
1291 // Start the loop with a block that tests the condition.
1292 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1293 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1294
1295 EmitBlock(CondBlock);
1296
1297 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1298 // Generate: if (loop-index < number-of-elements fall to the loop body,
1299 // otherwise, go to the block after the for-loop.
1300 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1301 llvm::Value * NumElementsPtr =
1302 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1303 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1304 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1305 "isless");
1306 // If the condition is true, execute the body.
1307 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1308
1309 EmitBlock(ForBody);
1310 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1311 // Inside the loop body, emit the assignment operator call on array element.
1312 Counter = Builder.CreateLoad(IndexPtr);
1313 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1314 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1315 const CXXMethodDecl *MD = 0;
1316 if (BitwiseAssign)
1317 EmitAggregateCopy(Dest, Src, Ty);
1318 else {
1319 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1320 MD);
1321 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1322 (void)hasCopyAssign;
1323 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1324 const llvm::Type *LTy =
1325 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1326 FPT->isVariadic());
1327 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1328
1329 CallArgList CallArgs;
1330 // Push the this (Dest) ptr.
1331 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1332 MD->getThisType(getContext())));
1333
1334 // Push the Src ptr.
1335 CallArgs.push_back(std::make_pair(RValue::get(Src),
1336 MD->getParamDecl(0)->getType()));
1337 QualType ResultType =
1338 MD->getType()->getAsFunctionType()->getResultType();
1339 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1340 Callee, CallArgs, MD);
1341 }
1342 EmitBlock(ContinueBlock);
1343
1344 // Emit the increment of the loop counter.
1345 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1346 Counter = Builder.CreateLoad(IndexPtr);
1347 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1348 Builder.CreateStore(NextVal, IndexPtr, false);
1349
1350 // Finally, branch back up to the condition for the next iteration.
1351 EmitBranch(CondBlock);
1352
1353 // Emit the fall-through block.
1354 EmitBlock(AfterFor, true);
1355}
1356
Fariborz Jahanianca283612009-08-07 23:51:33 +00001357/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1358/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001359/// or via a copy constructor call.
Fariborz Jahanianca283612009-08-07 23:51:33 +00001360void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001361 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001362 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001363 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1364 if (ClassDecl) {
1365 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1366 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1367 }
1368 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1369 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001370 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001371 }
1372
Fariborz Jahanianca283612009-08-07 23:51:33 +00001373 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001374 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001375 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1376 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001377 CallArgList CallArgs;
1378 // Push the this (Dest) ptr.
1379 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1380 BaseCopyCtor->getThisType(getContext())));
1381
Fariborz Jahanianca283612009-08-07 23:51:33 +00001382 // Push the Src ptr.
1383 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001384 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001385 QualType ResultType =
1386 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1387 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1388 Callee, CallArgs, BaseCopyCtor);
1389 }
1390}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001391
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001392/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1393/// object from SrcValue to DestValue. Assignment can be either a bitwise
1394/// assignment of via an assignment operator call.
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001395// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001396void CodeGenFunction::EmitClassCopyAssignment(
1397 llvm::Value *Dest, llvm::Value *Src,
1398 const CXXRecordDecl *ClassDecl,
1399 const CXXRecordDecl *BaseClassDecl,
1400 QualType Ty) {
1401 if (ClassDecl) {
1402 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1403 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1404 }
1405 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1406 EmitAggregateCopy(Dest, Src, Ty);
1407 return;
1408 }
1409
1410 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001411 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1412 MD);
1413 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1414 (void)ConstCopyAssignOp;
1415
1416 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1417 const llvm::Type *LTy =
1418 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1419 FPT->isVariadic());
1420 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001421
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001422 CallArgList CallArgs;
1423 // Push the this (Dest) ptr.
1424 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1425 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001426
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001427 // Push the Src ptr.
1428 CallArgs.push_back(std::make_pair(RValue::get(Src),
1429 MD->getParamDecl(0)->getType()));
1430 QualType ResultType =
1431 MD->getType()->getAsFunctionType()->getResultType();
1432 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1433 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001434}
1435
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001436/// SynthesizeDefaultConstructor - synthesize a default constructor
1437void
1438CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1439 const FunctionDecl *FD,
1440 llvm::Function *Fn,
1441 const FunctionArgList &Args) {
1442 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1443 EmitCtorPrologue(CD);
1444 FinishFunction();
1445}
1446
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001447/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001448/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1449/// The implicitly-defined copy constructor for class X performs a memberwise
1450/// copy of its subobjects. The order of copying is the same as the order
1451/// of initialization of bases and members in a user-defined constructor
1452/// Each subobject is copied in the manner appropriate to its type:
1453/// if the subobject is of class type, the copy constructor for the class is
1454/// used;
1455/// if the subobject is an array, each element is copied, in the manner
1456/// appropriate to the element type;
1457/// if the subobject is of scalar type, the built-in assignment operator is
1458/// used.
1459/// Virtual base class subobjects shall be copied only once by the
1460/// implicitly-defined copy constructor
1461
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001462void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1463 const FunctionDecl *FD,
1464 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001465 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001466 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1467 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001468 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1469 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001470
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001471 FunctionArgList::const_iterator i = Args.begin();
1472 const VarDecl *ThisArg = i->first;
1473 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1474 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1475 const VarDecl *SrcArg = (i+1)->first;
1476 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1477 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1478
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001479 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1480 Base != ClassDecl->bases_end(); ++Base) {
1481 // FIXME. copy constrution of virtual base NYI
1482 if (Base->isVirtual())
1483 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001484
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001485 CXXRecordDecl *BaseClassDecl
1486 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001487 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1488 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001489 }
1490
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001491 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1492 FieldEnd = ClassDecl->field_end();
1493 Field != FieldEnd; ++Field) {
1494 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001495 const ConstantArrayType *Array =
1496 getContext().getAsConstantArrayType(FieldType);
1497 if (Array)
1498 FieldType = getContext().getBaseElementType(FieldType);
1499
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001500 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1501 CXXRecordDecl *FieldClassDecl
1502 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1503 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1504 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001505 if (Array) {
1506 const llvm::Type *BasePtr = ConvertType(FieldType);
1507 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1508 llvm::Value *DestBaseAddrPtr =
1509 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1510 llvm::Value *SrcBaseAddrPtr =
1511 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1512 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1513 FieldClassDecl, FieldType);
1514 }
1515 else
1516 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1517 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001518 continue;
1519 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001520 // Do a built-in assignment of scalar data members.
1521 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1522 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1523 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1524 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001525 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001526 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001527}
1528
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001529/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1530/// Before the implicitly-declared copy assignment operator for a class is
1531/// implicitly defined, all implicitly- declared copy assignment operators for
1532/// its direct base classes and its nonstatic data members shall have been
1533/// implicitly defined. [12.8-p12]
1534/// The implicitly-defined copy assignment operator for class X performs
1535/// memberwise assignment of its subob- jects. The direct base classes of X are
1536/// assigned first, in the order of their declaration in
1537/// the base-specifier-list, and then the immediate nonstatic data members of X
1538/// are assigned, in the order in which they were declared in the class
1539/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001540/// if the subobject is of class type, the copy assignment operator for the
1541/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001542/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001543///
1544/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001545/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001546///
1547/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001548/// used.
1549void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1550 const FunctionDecl *FD,
1551 llvm::Function *Fn,
1552 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001553
1554 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1555 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1556 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001557 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1558
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001559 FunctionArgList::const_iterator i = Args.begin();
1560 const VarDecl *ThisArg = i->first;
1561 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1562 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1563 const VarDecl *SrcArg = (i+1)->first;
1564 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1565 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1566
1567 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1568 Base != ClassDecl->bases_end(); ++Base) {
1569 // FIXME. copy assignment of virtual base NYI
1570 if (Base->isVirtual())
1571 continue;
1572
1573 CXXRecordDecl *BaseClassDecl
1574 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1575 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1576 Base->getType());
1577 }
1578
1579 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1580 FieldEnd = ClassDecl->field_end();
1581 Field != FieldEnd; ++Field) {
1582 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001583 const ConstantArrayType *Array =
1584 getContext().getAsConstantArrayType(FieldType);
1585 if (Array)
1586 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001587
1588 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1589 CXXRecordDecl *FieldClassDecl
1590 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1591 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1592 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001593 if (Array) {
1594 const llvm::Type *BasePtr = ConvertType(FieldType);
1595 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1596 llvm::Value *DestBaseAddrPtr =
1597 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1598 llvm::Value *SrcBaseAddrPtr =
1599 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1600 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1601 FieldClassDecl, FieldType);
1602 }
1603 else
1604 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1605 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001606 continue;
1607 }
1608 // Do a built-in assignment of scalar data members.
1609 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1610 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1611 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1612 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001613 }
1614
1615 // return *this;
1616 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001617
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001618 FinishFunction();
1619}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001620
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001621/// EmitCtorPrologue - This routine generates necessary code to initialize
1622/// base classes and non-static data members belonging to this constructor.
1623void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001624 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001625 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001626 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001627
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001628 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001629 E = CD->init_end();
1630 B != E; ++B) {
1631 CXXBaseOrMemberInitializer *Member = (*B);
1632 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001633 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001634 Type *BaseType = Member->getBaseClass();
1635 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001636 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001637 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1638 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001639 EmitCXXConstructorCall(Member->getConstructor(),
1640 Ctor_Complete, V,
1641 Member->const_arg_begin(),
1642 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001643 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001644 // non-static data member initilaizers.
1645 FieldDecl *Field = Member->getMember();
1646 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001647 const ConstantArrayType *Array =
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001648 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001649 if (Array)
1650 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001651
Mike Stumpf1216772009-07-31 18:25:34 +00001652 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001653 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001654 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001655 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001656 assert(Member->getConstructor() &&
1657 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001658 if (Array) {
1659 const llvm::Type *BasePtr = ConvertType(FieldType);
1660 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1661 llvm::Value *BaseAddrPtr =
1662 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1663 EmitCXXAggrConstructorCall(Member->getConstructor(),
1664 Array, BaseAddrPtr);
1665 }
1666 else
1667 EmitCXXConstructorCall(Member->getConstructor(),
1668 Ctor_Complete, LHS.getAddress(),
1669 Member->const_arg_begin(),
1670 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001671 continue;
1672 }
1673 else {
1674 // Initializing an anonymous union data member.
1675 FieldDecl *anonMember = Member->getAnonUnionMember();
1676 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1677 FieldType = anonMember->getType();
1678 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001679 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001680
1681 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001682 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001683 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001684 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001685 }
1686 }
Mike Stumpf1216772009-07-31 18:25:34 +00001687
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001688 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001689 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001690 // have bases classes and/or contain non-static data members which require
1691 // construction.
1692 for (CXXRecordDecl::base_class_const_iterator Base =
1693 ClassDecl->bases_begin();
1694 Base != ClassDecl->bases_end(); ++Base) {
1695 // FIXME. copy assignment of virtual base NYI
1696 if (Base->isVirtual())
1697 continue;
1698
1699 CXXRecordDecl *BaseClassDecl
1700 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1701 if (BaseClassDecl->hasTrivialConstructor())
1702 continue;
1703 if (CXXConstructorDecl *BaseCX =
1704 BaseClassDecl->getDefaultConstructor(getContext())) {
1705 LoadOfThis = LoadCXXThis();
1706 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1707 BaseClassDecl);
1708 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1709 }
1710 }
1711
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001712 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1713 FieldEnd = ClassDecl->field_end();
1714 Field != FieldEnd; ++Field) {
1715 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001716 const ConstantArrayType *Array =
1717 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001718 if (Array)
1719 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001720 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1721 continue;
1722 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001723 CXXRecordDecl *MemberClassDecl =
1724 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1725 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1726 continue;
1727 if (CXXConstructorDecl *MamberCX =
1728 MemberClassDecl->getDefaultConstructor(getContext())) {
1729 LoadOfThis = LoadCXXThis();
1730 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001731 if (Array) {
1732 const llvm::Type *BasePtr = ConvertType(FieldType);
1733 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1734 llvm::Value *BaseAddrPtr =
1735 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1736 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1737 }
1738 else
1739 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1740 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001741 }
1742 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001743 }
1744
Mike Stumpf1216772009-07-31 18:25:34 +00001745 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001746 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001747 if (!LoadOfThis)
1748 LoadOfThis = LoadCXXThis();
1749 llvm::Value *VtableField;
1750 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001751 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001752 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1753 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1754 llvm::Value *vtable = GenerateVtable(ClassDecl);
1755 Builder.CreateStore(vtable, VtableField);
1756 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001757}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001758
1759/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1760/// destructor. This is to call destructors on members and base classes
1761/// in reverse order of their construction.
1762void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1763 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1764 assert(!ClassDecl->isPolymorphic() &&
1765 "FIXME. polymorphic destruction not supported");
1766 (void)ClassDecl; // prevent warning.
1767
1768 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1769 *E = DD->destr_end(); B != E; ++B) {
1770 uintptr_t BaseOrMember = (*B);
1771 if (DD->isMemberToDestroy(BaseOrMember)) {
1772 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1773 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001774 const ConstantArrayType *Array =
1775 getContext().getAsConstantArrayType(FieldType);
1776 if (Array)
1777 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001778 const RecordType *RT = FieldType->getAs<RecordType>();
1779 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1780 if (FieldClassDecl->hasTrivialDestructor())
1781 continue;
1782 llvm::Value *LoadOfThis = LoadCXXThis();
1783 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001784 if (Array) {
1785 const llvm::Type *BasePtr = ConvertType(FieldType);
1786 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1787 llvm::Value *BaseAddrPtr =
1788 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1789 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1790 Array, BaseAddrPtr);
1791 }
1792 else
1793 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1794 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001795 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001796 const RecordType *RT =
1797 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1798 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1799 if (BaseClassDecl->hasTrivialDestructor())
1800 continue;
1801 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1802 ClassDecl,BaseClassDecl);
1803 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1804 Dtor_Complete, V);
1805 }
1806 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001807 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1808 return;
1809 // Case of destructor synthesis with fields and base classes
1810 // which have non-trivial destructors. They must be destructed in
1811 // reverse order of their construction.
1812 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1813
1814 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1815 FieldEnd = ClassDecl->field_end();
1816 Field != FieldEnd; ++Field) {
1817 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001818 if (getContext().getAsConstantArrayType(FieldType))
1819 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001820 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1821 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1822 if (FieldClassDecl->hasTrivialDestructor())
1823 continue;
1824 DestructedFields.push_back(*Field);
1825 }
1826 }
1827 if (!DestructedFields.empty())
1828 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1829 FieldDecl *Field = DestructedFields[i];
1830 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001831 const ConstantArrayType *Array =
1832 getContext().getAsConstantArrayType(FieldType);
1833 if (Array)
1834 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001835 const RecordType *RT = FieldType->getAs<RecordType>();
1836 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1837 llvm::Value *LoadOfThis = LoadCXXThis();
1838 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001839 if (Array) {
1840 const llvm::Type *BasePtr = ConvertType(FieldType);
1841 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1842 llvm::Value *BaseAddrPtr =
1843 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1844 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1845 Array, BaseAddrPtr);
1846 }
1847 else
1848 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1849 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001850 }
1851
1852 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1853 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1854 Base != ClassDecl->bases_end(); ++Base) {
1855 // FIXME. copy assignment of virtual base NYI
1856 if (Base->isVirtual())
1857 continue;
1858
1859 CXXRecordDecl *BaseClassDecl
1860 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1861 if (BaseClassDecl->hasTrivialDestructor())
1862 continue;
1863 DestructedBases.push_back(BaseClassDecl);
1864 }
1865 if (DestructedBases.empty())
1866 return;
1867 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1868 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1869 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1870 ClassDecl,BaseClassDecl);
1871 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1872 Dtor_Complete, V);
1873 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001874}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001875
1876void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1877 const FunctionDecl *FD,
1878 llvm::Function *Fn,
1879 const FunctionArgList &Args) {
1880
1881 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1882 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1883 "SynthesizeDefaultDestructor - destructor has user declaration");
1884 (void) ClassDecl;
1885
1886 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1887 EmitDtorEpilogue(CD);
1888 FinishFunction();
1889}