blob: 1298feb2fd0d53aedb15ee0ef265a56531e1b6be [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
Mike Stumpf1216772009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stump7116da12009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson774e7c62009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000211
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213
Anders Carlsson774e7c62009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000219 }
220
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000223}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000224
Anders Carlsson0f294632009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
Fariborz Jahanianad258832009-08-13 21:09:41 +0000231 if (MD->isCopyAssignment()) {
232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
237 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
238 QualType Ty = E->getType();
239 EmitAggregateCopy(This, Src, Ty);
240 return RValue::get(This);
241 }
242 }
Anders Carlsson0f294632009-05-27 04:18:27 +0000243
244 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
245 const llvm::Type *Ty =
246 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
247 FPT->isVariadic());
248 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
249
250 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
251
252 return EmitCXXMemberCall(MD, Callee, This,
253 E->arg_begin() + 1, E->arg_end());
254}
255
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000256llvm::Value *CodeGenFunction::LoadCXXThis() {
257 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
258 "Must be in a C++ member function decl to load 'this'");
259 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
260 "Must be in a C++ member function decl to load 'this'");
261
262 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000267
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000278 if (Base == BaseClassDecl) {
279 NestedBasePaths.push_back(BaseClassDecl);
280 return true;
281 }
282 }
283 // BaseClassDecl not an immediate base of ClassDecl.
284 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
285 e = ClassDecl->bases_end(); i != e; ++i) {
286 if (i->isVirtual())
287 continue;
288 const CXXRecordDecl *Base =
289 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
290 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
291 NestedBasePaths.push_back(Base);
292 return true;
293 }
294 }
295 return false;
296}
297
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson0032b272009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000305 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
306 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
307 assert(NestedBasePaths.size() > 0 &&
308 "AddressCXXOfBaseClass - inheritence path failed");
309 NestedBasePaths.push_back(ClassDecl);
310 uint64_t Offset = 0;
311
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000314 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
315 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
316 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
317 const ASTRecordLayout &Layout =
318 getContext().getASTRecordLayout(DerivedClass);
319 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
320 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000324 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
325 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
326 QualType BTy =
327 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000335/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
336/// for-loop to call the default constructor on individual members of the
337/// array. 'Array' is the array type, 'This' is llvm pointer of the start
338/// of the array and 'D' is the default costructor Decl for elements of the
339/// array. It is assumed that all relevant checks have been made by the
340/// caller.
341void
342CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
343 const ArrayType *Array,
344 llvm::Value *This) {
345 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
346 assert(CA && "Do we support VLA for construction ?");
347
348 // Create a temporary for the loop index and initialize it with 0.
349 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
350 "loop.index");
351 llvm::Value* zeroConstant =
352 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
353 Builder.CreateStore(zeroConstant, IndexPtr, false);
354
355 // Start the loop with a block that tests the condition.
356 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
357 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
358
359 EmitBlock(CondBlock);
360
361 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
362
363 // Generate: if (loop-index < number-of-elements fall to the loop body,
364 // otherwise, go to the block after the for-loop.
365 uint64_t NumElements = CA->getSize().getZExtValue();
366 llvm::Value * NumElementsPtr =
367 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), NumElements);
368 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
369 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
370 "isless");
371 // If the condition is true, execute the body.
372 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
373
374 EmitBlock(ForBody);
375
376 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000378 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000379 if (const ConstantArrayType *CAT =
380 dyn_cast<ConstantArrayType>(Array->getElementType())) {
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000381 uint32_t delta = 1;
382 const ConstantArrayType *CAW = CAT;
383 do {
384 delta *= CAW->getSize().getZExtValue();
385 CAW = dyn_cast<ConstantArrayType>(CAW->getElementType());
386 } while (CAW);
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000387 // Address = This + delta*Counter for current loop iteration.
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000388 llvm::Value *DeltaPtr =
389 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), delta);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000390 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
391 llvm::Value *Address =
392 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000393 EmitCXXAggrConstructorCall(D, CAT, Address);
394 }
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000395 else {
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000396 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000397 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000398 }
399
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000400 EmitBlock(ContinueBlock);
401
402 // Emit the increment of the loop counter.
403 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
404 Counter = Builder.CreateLoad(IndexPtr);
405 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
406 Builder.CreateStore(NextVal, IndexPtr, false);
407
408 // Finally, branch back up to the condition for the next iteration.
409 EmitBranch(CondBlock);
410
411 // Emit the fall-through block.
412 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000413}
414
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000415/// EmitCXXAggrDestructorCall - calls the default destructor on array
416/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000417void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000418CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
419 const ArrayType *Array,
420 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000421 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
422 assert(CA && "Do we support VLA for destruction ?");
423 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
424 1);
425 uint64_t ElementCount = 1;
426 const ConstantArrayType *CAW = CA;
427 do {
428 ElementCount *= CAW->getSize().getZExtValue();
429 CAW = dyn_cast<ConstantArrayType>(CAW->getElementType());
430 } while (CAW);
431 // Create a temporary for the loop index and initialize it with count of
432 // array elements.
433 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
434 "loop.index");
435 // Index = ElementCount;
436 llvm::Value* UpperCount =
437 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
438 Builder.CreateStore(UpperCount, IndexPtr, false);
439
440 // Start the loop with a block that tests the condition.
441 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
442 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
443
444 EmitBlock(CondBlock);
445
446 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
447
448 // Generate: if (loop-index != 0 fall to the loop body,
449 // otherwise, go to the block after the for-loop.
450 llvm::Value* zeroConstant =
451 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
452 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
453 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
454 "isne");
455 // If the condition is true, execute the body.
456 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
457
458 EmitBlock(ForBody);
459
460 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
461 // Inside the loop body, emit the constructor call on the array element.
462 Counter = Builder.CreateLoad(IndexPtr);
463 Counter = Builder.CreateSub(Counter, One);
464 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
465 EmitCXXDestructorCall(D, Dtor_Complete, Address);
466
467 EmitBlock(ContinueBlock);
468
469 // Emit the decrement of the loop counter.
470 Counter = Builder.CreateLoad(IndexPtr);
471 Counter = Builder.CreateSub(Counter, One, "dec");
472 Builder.CreateStore(Counter, IndexPtr, false);
473
474 // Finally, branch back up to the condition for the next iteration.
475 EmitBranch(CondBlock);
476
477 // Emit the fall-through block.
478 EmitBlock(AfterFor, true);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000479}
480
481void
Anders Carlssonb14095a2009-04-17 00:06:03 +0000482CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
483 CXXCtorType Type,
484 llvm::Value *This,
485 CallExpr::const_arg_iterator ArgBeg,
486 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000487 if (D->isCopyConstructor(getContext())) {
488 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
489 if (ClassDecl->hasTrivialCopyConstructor()) {
490 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
491 "EmitCXXConstructorCall - user declared copy constructor");
492 const Expr *E = (*ArgBeg);
493 QualType Ty = E->getType();
494 llvm::Value *Src = EmitLValue(E).getAddress();
495 EmitAggregateCopy(This, Src, Ty);
496 return;
497 }
498 }
499
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000500 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
501
502 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000503}
504
Anders Carlsson7267c162009-05-29 21:03:38 +0000505void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
506 CXXDtorType Type,
507 llvm::Value *This) {
508 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
509
510 EmitCXXMemberCall(D, Callee, This, 0, 0);
511}
512
Anders Carlssonb14095a2009-04-17 00:06:03 +0000513void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000514CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
515 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000516 assert(Dest && "Must have a destination!");
517
518 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000519 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000520 if (RD->hasTrivialConstructor())
521 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000522
523 // Code gen optimization to eliminate copy constructor and return
524 // its first argument instead.
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000525 if (E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000526 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000527 EmitAggExpr((*i), Dest, false);
528 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000529 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000530 // Call the constructor.
531 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
532 E->arg_begin(), E->arg_end());
533}
534
Anders Carlssona00703d2009-05-31 01:40:14 +0000535llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000536 if (E->isArray()) {
537 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000538 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000539 }
540
541 QualType AllocType = E->getAllocatedType();
542 FunctionDecl *NewFD = E->getOperatorNew();
543 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
544
545 CallArgList NewArgs;
546
547 // The allocation size is the first argument.
548 QualType SizeTy = getContext().getSizeType();
549 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000550 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000551 getContext().getTypeSize(AllocType) / 8);
552
553 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
554
555 // Emit the rest of the arguments.
556 // FIXME: Ideally, this should just use EmitCallArgs.
557 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
558
559 // First, use the types from the function type.
560 // We start at 1 here because the first argument (the allocation size)
561 // has already been emitted.
562 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
563 QualType ArgType = NewFTy->getArgType(i);
564
565 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
566 getTypePtr() ==
567 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
568 "type mismatch in call argument!");
569
570 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
571 ArgType));
572
573 }
574
575 // Either we've emitted all the call args, or we have a call to a
576 // variadic function.
577 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
578 "Extra arguments in non-variadic function!");
579
580 // If we still have any arguments, emit them using the type of the argument.
581 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
582 NewArg != NewArgEnd; ++NewArg) {
583 QualType ArgType = NewArg->getType();
584 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
585 ArgType));
586 }
587
588 // Emit the call to new.
589 RValue RV =
590 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
591 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
592 NewArgs, NewFD);
593
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000594 // If an allocation function is declared with an empty exception specification
595 // it returns null to indicate failure to allocate storage. [expr.new]p13.
596 // (We don't need to check for null when there's no new initializer and
597 // we're allocating a POD type).
598 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
599 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000600
Anders Carlssonf1108532009-06-01 00:05:16 +0000601 llvm::BasicBlock *NewNull = 0;
602 llvm::BasicBlock *NewNotNull = 0;
603 llvm::BasicBlock *NewEnd = 0;
604
605 llvm::Value *NewPtr = RV.getScalarVal();
606
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000607 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000608 NewNull = createBasicBlock("new.null");
609 NewNotNull = createBasicBlock("new.notnull");
610 NewEnd = createBasicBlock("new.end");
611
612 llvm::Value *IsNull =
613 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000614 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000615 "isnull");
616
617 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
618 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000619 }
620
Anders Carlssonf1108532009-06-01 00:05:16 +0000621 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000622
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000623 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000624 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000625 assert(E->getNumConstructorArgs() == 1 &&
626 "Can only have one argument to initializer of POD type.");
627
628 const Expr *Init = E->getConstructorArg(0);
629
Anders Carlsson3923e952009-05-31 21:07:58 +0000630 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000631 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000632 else if (AllocType->isAnyComplexType())
633 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000634 else
635 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000636 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000637 } else {
638 // Call the constructor.
639 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000640
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000641 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
642 E->constructor_arg_begin(),
643 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000644 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000645
Anders Carlssonf1108532009-06-01 00:05:16 +0000646 if (NullCheckResult) {
647 Builder.CreateBr(NewEnd);
648 EmitBlock(NewNull);
649 Builder.CreateBr(NewEnd);
650 EmitBlock(NewEnd);
651
652 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
653 PHI->reserveOperandSpace(2);
654 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000655 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000656
657 NewPtr = PHI;
658 }
659
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000660 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000661}
662
Anders Carlsson60e282c2009-08-16 21:13:42 +0000663void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
664 if (E->isArrayForm()) {
665 ErrorUnsupported(E, "delete[] expression");
666 return;
667 };
668
669 QualType DeleteTy =
670 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
671
672 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
673
674 // Null check the pointer.
675 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
676 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
677
678 llvm::Value *IsNull =
679 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
680 "isnull");
681
682 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
683 EmitBlock(DeleteNotNull);
684
685 // Call the destructor if necessary.
686 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
687 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
688 if (!RD->hasTrivialDestructor()) {
689 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
690 if (Dtor->isVirtual()) {
691 ErrorUnsupported(E, "delete expression with virtual destructor");
692 return;
693 }
694
695 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
696 }
697 }
698 }
699
700 // Call delete.
701 FunctionDecl *DeleteFD = E->getOperatorDelete();
702 const FunctionProtoType *DeleteFTy =
703 DeleteFD->getType()->getAsFunctionProtoType();
704
705 CallArgList DeleteArgs;
706
707 QualType ArgTy = DeleteFTy->getArgType(0);
708 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
709 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
710
711 // Emit the call to delete.
712 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
713 DeleteArgs),
714 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
715 DeleteArgs, DeleteFD);
716
717 EmitBlock(DeleteEnd);
718}
719
Anders Carlsson27ae5362009-04-17 01:58:57 +0000720static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
721 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000722 // The class has base classes - we don't support that right now.
723 if (RD->getNumBases() > 0)
724 return false;
725
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000726 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
727 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000728 // We don't support ctors for fields that aren't POD.
729 if (!I->getType()->isPODType())
730 return false;
731 }
732
733 return true;
734}
735
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000736void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000737 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000738 ErrorUnsupported(D, "C++ constructor", true);
739 return;
740 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000741
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000742 EmitGlobal(GlobalDecl(D, Ctor_Complete));
743 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000744}
Anders Carlsson363c1842009-04-16 23:57:24 +0000745
Anders Carlsson27ae5362009-04-17 01:58:57 +0000746void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
747 CXXCtorType Type) {
748
749 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
750
751 CodeGenFunction(*this).GenerateCode(D, Fn);
752
753 SetFunctionDefinitionAttributes(D, Fn);
754 SetLLVMFunctionAttributesForDefinition(D, Fn);
755}
756
Anders Carlsson363c1842009-04-16 23:57:24 +0000757llvm::Function *
758CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
759 CXXCtorType Type) {
760 const llvm::FunctionType *FTy =
761 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
762
763 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000764 return cast<llvm::Function>(
765 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000766}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000767
768const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
769 CXXCtorType Type) {
770 llvm::SmallString<256> Name;
771 llvm::raw_svector_ostream Out(Name);
772 mangleCXXCtor(D, Type, Context, Out);
773
774 Name += '\0';
775 return UniqueMangledName(Name.begin(), Name.end());
776}
777
778void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
779 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
780 ErrorUnsupported(D, "C++ destructor", true);
781 return;
782 }
783
784 EmitCXXDestructor(D, Dtor_Complete);
785 EmitCXXDestructor(D, Dtor_Base);
786}
787
788void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
789 CXXDtorType Type) {
790 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
791
792 CodeGenFunction(*this).GenerateCode(D, Fn);
793
794 SetFunctionDefinitionAttributes(D, Fn);
795 SetLLVMFunctionAttributesForDefinition(D, Fn);
796}
797
798llvm::Function *
799CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
800 CXXDtorType Type) {
801 const llvm::FunctionType *FTy =
802 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
803
804 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000805 return cast<llvm::Function>(
806 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000807}
808
809const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
810 CXXDtorType Type) {
811 llvm::SmallString<256> Name;
812 llvm::raw_svector_ostream Out(Name);
813 mangleCXXDtor(D, Type, Context, Out);
814
815 Name += '\0';
816 return UniqueMangledName(Name.begin(), Name.end());
817}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000818
Mike Stump32f37012009-08-18 21:49:00 +0000819llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000820 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000821 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000822 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000823
824 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000825 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000826
827 llvm::SmallString<256> OutName;
828 llvm::raw_svector_ostream Out(OutName);
829 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000830 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000831 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000832 llvm::GlobalVariable::LinkageTypes linktype;
833 linktype = llvm::GlobalValue::WeakAnyLinkage;
834 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000835 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000836 // FIXME: descriptor
837 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000838 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000839 // FIXME: TS
840 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
841
842 llvm::Constant *C;
843 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
844 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000845 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000846 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000847 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
848 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000849}
850
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000851class VtableBuilder {
Mike Stump7c435fa2009-08-18 20:50:28 +0000852 std::vector<llvm::Constant *> &methods;
853 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000854 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000855 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000856 /// BLayout - Layout for the most derived class that this vtable is being
857 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000858 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000859 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000860 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000861 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000862 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000863 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-08-21 01:45:00 +0000864 /// Index - Maps a method decl into a vtable index. Useful for virtual
865 /// dispatch codegen.
866 llvm::DenseMap<const CXXMethodDecl *, int32_t> Index;
Mike Stump552b2752009-08-18 22:04:08 +0000867 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000868public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000869 VtableBuilder(std::vector<llvm::Constant *> &meth,
870 const CXXRecordDecl *c,
871 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000872 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
873 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
874 CGM(cgm) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000875 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
876 }
Mike Stump32f37012009-08-18 21:49:00 +0000877
Mike Stumpb46c92d2009-08-19 02:06:38 +0000878 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
879 const CXXRecordDecl *RD,
880 bool VBoundary,
881 bool SecondaryVirtual) {
882 llvm::Constant *m = 0;
883
884 // FIXME: vcall: offset for virtual base for this function
885 if (SecondaryVirtual || VBoundary)
886 m = llvm::Constant::getNullValue(Ptr8Ty);
887 return m;
888 }
889
890 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
891 bool SecondaryVirtual) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000892 llvm::Constant *m;
Mike Stump80a0e322009-08-12 23:25:18 +0000893
Mike Stump552b2752009-08-18 22:04:08 +0000894 for (method_iter mi = RD->method_begin(),
Mike Stump7c435fa2009-08-18 20:50:28 +0000895 me = RD->method_end(); mi != me; ++mi) {
896 if (mi->isVirtual()) {
Mike Stumpb46c92d2009-08-19 02:06:38 +0000897 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
898 if (m)
899 methods.push_back(m);
Mike Stump7c435fa2009-08-18 20:50:28 +0000900 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000901 }
Mike Stump80a0e322009-08-12 23:25:18 +0000902 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000903
Mike Stump7fa0d932009-08-20 02:11:48 +0000904 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000905 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000906 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
907 e = RD->bases_end(); i != e; ++i) {
908 const CXXRecordDecl *Base =
909 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
910 if (i->isVirtual() && !SeenVBase.count(Base)) {
911 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000912 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump7fa0d932009-08-20 02:11:48 +0000913 llvm::Constant *m;
Mike Stumpb9837442009-08-20 07:22:17 +0000914 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000915 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
916 offsets.push_back(m);
917 }
Mike Stumpb9837442009-08-20 07:22:17 +0000918 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000919 }
920 }
921
Mike Stumpb9871a22009-08-21 01:45:00 +0000922 void StartNewTable() {
923 SeenVBase.clear();
924 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000925
Mike Stumpb9871a22009-08-21 01:45:00 +0000926 inline uint32_t nottoobig(uint64_t t) {
927 assert(t < (uint32_t)-1ULL || "vtable too big");
928 return t;
929 }
930#if 0
931 inline uint32_t nottoobig(uint32_t t) {
932 return t;
933 }
934#endif
935
936 void AddMethod(const CXXMethodDecl *MD, int32_t FirstIndex) {
937 typedef CXXMethodDecl::method_iterator meth_iter;
938
939 llvm::Constant *m;
940 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
941 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
942
943 // FIXME: Don't like the nested loops. For very large inheritance
944 // heirarchies we could have a table on the side with the final overridder
945 // and just replace each instance of an overridden method once. Would be
946 // nice to measure the cost/benefit on real code.
947
948 // If we can find a previously allocated slot for this, reuse it.
949 for (meth_iter mi = MD->begin_overridden_methods(),
950 e = MD->end_overridden_methods();
951 mi != e; ++mi) {
952 const CXXMethodDecl *OMD = *mi;
953 llvm::Constant *om;
954 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
955 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
956
957 for (int32_t i = FirstIndex, e = nottoobig(methods.size()); i != e; ++i) {
958 // FIXME: begin_overridden_methods might be too lax, covariance */
959 if (methods[i] == om) {
960 methods[i] = m;
961 Index[MD] = i;
962 return;
963 }
Mike Stump65defe32009-08-18 21:03:28 +0000964 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000965 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000966
967 // else allocate a new slot.
968 Index[MD] = methods.size();
969 methods.push_back(m);
970 }
971
972 void GenerateMethods(const CXXRecordDecl *RD, int32_t FirstIndex) {
973 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
974 ++mi)
975 if (mi->isVirtual())
976 AddMethod(*mi, FirstIndex);
Mike Stumpbc16aea2009-08-12 23:00:59 +0000977 }
Mike Stump65defe32009-08-18 21:03:28 +0000978
Mike Stump109b13d2009-08-18 21:30:21 +0000979 void GenerateVtableForBase(const CXXRecordDecl *RD,
980 bool forPrimary,
Mike Stumpb46c92d2009-08-19 02:06:38 +0000981 bool VBoundary,
Mike Stump109b13d2009-08-18 21:30:21 +0000982 int64_t Offset,
Mike Stumpb9871a22009-08-21 01:45:00 +0000983 bool ForVirtualBase,
984 int32_t FirstIndex) {
Mike Stump109b13d2009-08-18 21:30:21 +0000985 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump276b9f12009-08-16 01:46:26 +0000986
Mike Stump109b13d2009-08-18 21:30:21 +0000987 if (RD && !RD->isDynamicClass())
988 return;
989
990 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
991 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
992 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
993
Mike Stumpb46c92d2009-08-19 02:06:38 +0000994 if (VBoundary || forPrimary || ForVirtualBase) {
995 // then comes the the vcall offsets for all our functions...
996 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
997 }
998
Mike Stump109b13d2009-08-18 21:30:21 +0000999 // The virtual base offsets come first...
1000 // FIXME: Audit, is this right?
Mike Stump09765ec2009-08-19 02:53:08 +00001001 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump109b13d2009-08-18 21:30:21 +00001002 std::vector<llvm::Constant *> offsets;
Mike Stumpb9837442009-08-20 07:22:17 +00001003 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001004 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1005 e = offsets.rend(); i != e; ++i)
1006 methods.push_back(*i);
1007 }
1008
Mike Stump109b13d2009-08-18 21:30:21 +00001009 bool Top = true;
1010
1011 // vtables are composed from the chain of primaries.
1012 if (PrimaryBase) {
1013 if (PrimaryBaseWasVirtual)
1014 IndirectPrimary.insert(PrimaryBase);
1015 Top = false;
Mike Stumpb46c92d2009-08-19 02:06:38 +00001016 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpb9871a22009-08-21 01:45:00 +00001017 Offset, PrimaryBaseWasVirtual, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001018 }
1019
1020 if (Top) {
1021 int64_t BaseOffset;
1022 if (ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001023 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1024 } else
1025 BaseOffset = -Offset/8;
Mike Stump276b9f12009-08-16 01:46:26 +00001026 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1027 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1028 methods.push_back(m);
Mike Stump109b13d2009-08-18 21:30:21 +00001029 methods.push_back(rtti);
Mike Stump276b9f12009-08-16 01:46:26 +00001030 }
Mike Stump4ef98092009-08-13 22:53:07 +00001031
Mike Stump109b13d2009-08-18 21:30:21 +00001032 // And add the virtuals for the class to the primary vtable.
Mike Stumpb9871a22009-08-21 01:45:00 +00001033 GenerateMethods(RD, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001034
1035 // and then the non-virtual bases.
1036 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1037 e = RD->bases_end(); i != e; ++i) {
1038 if (i->isVirtual())
1039 continue;
1040 const CXXRecordDecl *Base =
1041 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1042 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1043 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001044 StartNewTable();
1045 FirstIndex = methods.size();
1046 GenerateVtableForBase(Base, true, false, o, false, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001047 }
1048 }
1049 }
1050
1051 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001052 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001053 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1054 e = RD->bases_end(); i != e; ++i) {
1055 const CXXRecordDecl *Base =
1056 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1057 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1058 // Mark it so we don't output it twice.
1059 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001060 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001061 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001062 int32_t FirstIndex = methods.size();
1063 GenerateVtableForBase(Base, false, true, BaseOffset, true, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001064 }
1065 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001066 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001067 }
1068 }
Mike Stump109b13d2009-08-18 21:30:21 +00001069};
Mike Stump8a12b562009-08-06 15:50:11 +00001070
Mike Stumpf1216772009-07-31 18:25:34 +00001071llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001072 llvm::SmallString<256> OutName;
1073 llvm::raw_svector_ostream Out(OutName);
1074 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001075 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001076 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001077 llvm::GlobalVariable::LinkageTypes linktype;
1078 linktype = llvm::GlobalValue::WeakAnyLinkage;
1079 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001080 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump6f376332009-08-05 22:37:18 +00001081 int64_t Offset = 0;
Mike Stumpe1be2b12009-08-06 21:49:36 +00001082
1083 Offset += LLVMPointerWidth;
1084 Offset += LLVMPointerWidth;
Mike Stump6f376332009-08-05 22:37:18 +00001085
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001086 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001087
Mike Stump276b9f12009-08-16 01:46:26 +00001088 // First comes the vtables for all the non-virtual bases...
Mike Stumpb9871a22009-08-21 01:45:00 +00001089 b.GenerateVtableForBase(RD, true, false, 0, false, 0);
Mike Stump21538912009-08-14 01:44:03 +00001090
Mike Stump276b9f12009-08-16 01:46:26 +00001091 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001092 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001093
Mike Stump82b56962009-07-31 21:43:43 +00001094 llvm::Constant *C;
1095 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1096 C = llvm::ConstantArray::get(type, methods);
1097 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001098 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001099 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001100 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001101 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump6f376332009-08-05 22:37:18 +00001102 Offset/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001103 return vtable;
1104}
1105
Fariborz Jahanianca283612009-08-07 23:51:33 +00001106/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1107/// object from SrcValue to DestValue. Copying can be either a bitwise copy
1108/// of via a copy constructor call.
1109void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001110 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001111 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001112 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1113 if (ClassDecl) {
1114 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1115 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1116 }
1117 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1118 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001119 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001120 }
1121
Fariborz Jahanianca283612009-08-07 23:51:33 +00001122 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001123 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001124 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1125 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001126 CallArgList CallArgs;
1127 // Push the this (Dest) ptr.
1128 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1129 BaseCopyCtor->getThisType(getContext())));
1130
Fariborz Jahanianca283612009-08-07 23:51:33 +00001131 // Push the Src ptr.
1132 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001133 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001134 QualType ResultType =
1135 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1136 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1137 Callee, CallArgs, BaseCopyCtor);
1138 }
1139}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001140
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001141/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1142/// object from SrcValue to DestValue. Assignment can be either a bitwise
1143/// assignment of via an assignment operator call.
1144void CodeGenFunction::EmitClassCopyAssignment(
1145 llvm::Value *Dest, llvm::Value *Src,
1146 const CXXRecordDecl *ClassDecl,
1147 const CXXRecordDecl *BaseClassDecl,
1148 QualType Ty) {
1149 if (ClassDecl) {
1150 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1151 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1152 }
1153 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1154 EmitAggregateCopy(Dest, Src, Ty);
1155 return;
1156 }
1157
1158 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001159 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1160 MD);
1161 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1162 (void)ConstCopyAssignOp;
1163
1164 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1165 const llvm::Type *LTy =
1166 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1167 FPT->isVariadic());
1168 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001169
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001170 CallArgList CallArgs;
1171 // Push the this (Dest) ptr.
1172 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1173 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001174
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001175 // Push the Src ptr.
1176 CallArgs.push_back(std::make_pair(RValue::get(Src),
1177 MD->getParamDecl(0)->getType()));
1178 QualType ResultType =
1179 MD->getType()->getAsFunctionType()->getResultType();
1180 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1181 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001182}
1183
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001184/// SynthesizeDefaultConstructor - synthesize a default constructor
1185void
1186CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1187 const FunctionDecl *FD,
1188 llvm::Function *Fn,
1189 const FunctionArgList &Args) {
1190 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1191 EmitCtorPrologue(CD);
1192 FinishFunction();
1193}
1194
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001195/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001196/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1197/// The implicitly-defined copy constructor for class X performs a memberwise
1198/// copy of its subobjects. The order of copying is the same as the order
1199/// of initialization of bases and members in a user-defined constructor
1200/// Each subobject is copied in the manner appropriate to its type:
1201/// if the subobject is of class type, the copy constructor for the class is
1202/// used;
1203/// if the subobject is an array, each element is copied, in the manner
1204/// appropriate to the element type;
1205/// if the subobject is of scalar type, the built-in assignment operator is
1206/// used.
1207/// Virtual base class subobjects shall be copied only once by the
1208/// implicitly-defined copy constructor
1209
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001210void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1211 const FunctionDecl *FD,
1212 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001213 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001214 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1215 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001216 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1217 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001218
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001219 FunctionArgList::const_iterator i = Args.begin();
1220 const VarDecl *ThisArg = i->first;
1221 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1222 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1223 const VarDecl *SrcArg = (i+1)->first;
1224 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1225 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1226
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001227 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1228 Base != ClassDecl->bases_end(); ++Base) {
1229 // FIXME. copy constrution of virtual base NYI
1230 if (Base->isVirtual())
1231 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001232
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001233 CXXRecordDecl *BaseClassDecl
1234 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001235 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1236 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001237 }
1238
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001239 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1240 FieldEnd = ClassDecl->field_end();
1241 Field != FieldEnd; ++Field) {
1242 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1243
1244 // FIXME. How about copying arrays!
1245 assert(!getContext().getAsArrayType(FieldType) &&
1246 "FIXME. Copying arrays NYI");
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001247
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001248 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1249 CXXRecordDecl *FieldClassDecl
1250 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1251 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1252 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001253
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001254 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001255 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001256 continue;
1257 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001258 // Do a built-in assignment of scalar data members.
1259 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1260 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1261 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1262 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001263 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001264 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001265}
1266
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001267/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1268/// Before the implicitly-declared copy assignment operator for a class is
1269/// implicitly defined, all implicitly- declared copy assignment operators for
1270/// its direct base classes and its nonstatic data members shall have been
1271/// implicitly defined. [12.8-p12]
1272/// The implicitly-defined copy assignment operator for class X performs
1273/// memberwise assignment of its subob- jects. The direct base classes of X are
1274/// assigned first, in the order of their declaration in
1275/// the base-specifier-list, and then the immediate nonstatic data members of X
1276/// are assigned, in the order in which they were declared in the class
1277/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001278/// if the subobject is of class type, the copy assignment operator for the
1279/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001280/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001281///
1282/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001283/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001284///
1285/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001286/// used.
1287void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1288 const FunctionDecl *FD,
1289 llvm::Function *Fn,
1290 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001291
1292 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1293 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1294 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001295 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1296
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001297 FunctionArgList::const_iterator i = Args.begin();
1298 const VarDecl *ThisArg = i->first;
1299 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1300 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1301 const VarDecl *SrcArg = (i+1)->first;
1302 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1303 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1304
1305 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1306 Base != ClassDecl->bases_end(); ++Base) {
1307 // FIXME. copy assignment of virtual base NYI
1308 if (Base->isVirtual())
1309 continue;
1310
1311 CXXRecordDecl *BaseClassDecl
1312 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1313 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1314 Base->getType());
1315 }
1316
1317 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1318 FieldEnd = ClassDecl->field_end();
1319 Field != FieldEnd; ++Field) {
1320 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1321
1322 // FIXME. How about copy assignment of arrays!
1323 assert(!getContext().getAsArrayType(FieldType) &&
1324 "FIXME. Copy assignment of arrays NYI");
1325
1326 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1327 CXXRecordDecl *FieldClassDecl
1328 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1329 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1330 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1331
1332 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1333 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1334 continue;
1335 }
1336 // Do a built-in assignment of scalar data members.
1337 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1338 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1339 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1340 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001341 }
1342
1343 // return *this;
1344 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001345
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001346 FinishFunction();
1347}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001348
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001349/// EmitCtorPrologue - This routine generates necessary code to initialize
1350/// base classes and non-static data members belonging to this constructor.
1351void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001352 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001353 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001354 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001355
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001356 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001357 E = CD->init_end();
1358 B != E; ++B) {
1359 CXXBaseOrMemberInitializer *Member = (*B);
1360 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001361 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001362 Type *BaseType = Member->getBaseClass();
1363 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001365 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1366 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001367 EmitCXXConstructorCall(Member->getConstructor(),
1368 Ctor_Complete, V,
1369 Member->const_arg_begin(),
1370 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001371 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001372 // non-static data member initilaizers.
1373 FieldDecl *Field = Member->getMember();
1374 QualType FieldType = getContext().getCanonicalType((Field)->getType());
1375 assert(!getContext().getAsArrayType(FieldType)
1376 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001377
Mike Stumpf1216772009-07-31 18:25:34 +00001378 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001379 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001380 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001381 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001382 assert(Member->getConstructor() &&
1383 "EmitCtorPrologue - no constructor to initialize member");
1384 EmitCXXConstructorCall(Member->getConstructor(),
1385 Ctor_Complete, LHS.getAddress(),
1386 Member->const_arg_begin(),
1387 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001388 continue;
1389 }
1390 else {
1391 // Initializing an anonymous union data member.
1392 FieldDecl *anonMember = Member->getAnonUnionMember();
1393 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1394 FieldType = anonMember->getType();
1395 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001396 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001397
1398 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001399 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001400 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001401 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001402 }
1403 }
Mike Stumpf1216772009-07-31 18:25:34 +00001404
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001405 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001406 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001407 // have bases classes and/or contain non-static data members which require
1408 // construction.
1409 for (CXXRecordDecl::base_class_const_iterator Base =
1410 ClassDecl->bases_begin();
1411 Base != ClassDecl->bases_end(); ++Base) {
1412 // FIXME. copy assignment of virtual base NYI
1413 if (Base->isVirtual())
1414 continue;
1415
1416 CXXRecordDecl *BaseClassDecl
1417 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1418 if (BaseClassDecl->hasTrivialConstructor())
1419 continue;
1420 if (CXXConstructorDecl *BaseCX =
1421 BaseClassDecl->getDefaultConstructor(getContext())) {
1422 LoadOfThis = LoadCXXThis();
1423 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1424 BaseClassDecl);
1425 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1426 }
1427 }
1428
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001429 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1430 FieldEnd = ClassDecl->field_end();
1431 Field != FieldEnd; ++Field) {
1432 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001433 const ConstantArrayType *Array =
1434 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001435 if (Array)
1436 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001437 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1438 continue;
1439 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001440 CXXRecordDecl *MemberClassDecl =
1441 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1442 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1443 continue;
1444 if (CXXConstructorDecl *MamberCX =
1445 MemberClassDecl->getDefaultConstructor(getContext())) {
1446 LoadOfThis = LoadCXXThis();
1447 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001448 if (Array) {
1449 const llvm::Type *BasePtr = ConvertType(FieldType);
1450 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1451 llvm::Value *BaseAddrPtr =
1452 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1453 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1454 }
1455 else
1456 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1457 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001458 }
1459 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001460 }
1461
Mike Stumpf1216772009-07-31 18:25:34 +00001462 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001463 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001464 if (!LoadOfThis)
1465 LoadOfThis = LoadCXXThis();
1466 llvm::Value *VtableField;
1467 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001468 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001469 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1470 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1471 llvm::Value *vtable = GenerateVtable(ClassDecl);
1472 Builder.CreateStore(vtable, VtableField);
1473 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001474}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001475
1476/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1477/// destructor. This is to call destructors on members and base classes
1478/// in reverse order of their construction.
1479void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1480 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1481 assert(!ClassDecl->isPolymorphic() &&
1482 "FIXME. polymorphic destruction not supported");
1483 (void)ClassDecl; // prevent warning.
1484
1485 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1486 *E = DD->destr_end(); B != E; ++B) {
1487 uintptr_t BaseOrMember = (*B);
1488 if (DD->isMemberToDestroy(BaseOrMember)) {
1489 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1490 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001491 const ConstantArrayType *Array =
1492 getContext().getAsConstantArrayType(FieldType);
1493 if (Array)
1494 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001495 const RecordType *RT = FieldType->getAs<RecordType>();
1496 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1497 if (FieldClassDecl->hasTrivialDestructor())
1498 continue;
1499 llvm::Value *LoadOfThis = LoadCXXThis();
1500 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001501 if (Array) {
1502 const llvm::Type *BasePtr = ConvertType(FieldType);
1503 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1504 llvm::Value *BaseAddrPtr =
1505 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1506 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1507 Array, BaseAddrPtr);
1508 }
1509 else
1510 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1511 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001512 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001513 const RecordType *RT =
1514 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1515 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1516 if (BaseClassDecl->hasTrivialDestructor())
1517 continue;
1518 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1519 ClassDecl,BaseClassDecl);
1520 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1521 Dtor_Complete, V);
1522 }
1523 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001524 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1525 return;
1526 // Case of destructor synthesis with fields and base classes
1527 // which have non-trivial destructors. They must be destructed in
1528 // reverse order of their construction.
1529 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1530
1531 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1532 FieldEnd = ClassDecl->field_end();
1533 Field != FieldEnd; ++Field) {
1534 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001535 if (getContext().getAsConstantArrayType(FieldType))
1536 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001537 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1538 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1539 if (FieldClassDecl->hasTrivialDestructor())
1540 continue;
1541 DestructedFields.push_back(*Field);
1542 }
1543 }
1544 if (!DestructedFields.empty())
1545 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1546 FieldDecl *Field = DestructedFields[i];
1547 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001548 const ConstantArrayType *Array =
1549 getContext().getAsConstantArrayType(FieldType);
1550 if (Array)
1551 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001552 const RecordType *RT = FieldType->getAs<RecordType>();
1553 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1554 llvm::Value *LoadOfThis = LoadCXXThis();
1555 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001556 if (Array) {
1557 const llvm::Type *BasePtr = ConvertType(FieldType);
1558 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1559 llvm::Value *BaseAddrPtr =
1560 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1561 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1562 Array, BaseAddrPtr);
1563 }
1564 else
1565 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1566 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001567 }
1568
1569 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1570 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1571 Base != ClassDecl->bases_end(); ++Base) {
1572 // FIXME. copy assignment of virtual base NYI
1573 if (Base->isVirtual())
1574 continue;
1575
1576 CXXRecordDecl *BaseClassDecl
1577 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1578 if (BaseClassDecl->hasTrivialDestructor())
1579 continue;
1580 DestructedBases.push_back(BaseClassDecl);
1581 }
1582 if (DestructedBases.empty())
1583 return;
1584 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1585 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1586 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1587 ClassDecl,BaseClassDecl);
1588 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1589 Dtor_Complete, V);
1590 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001591}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001592
1593void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1594 const FunctionDecl *FD,
1595 llvm::Function *Fn,
1596 const FunctionArgList &Args) {
1597
1598 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1599 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1600 "SynthesizeDefaultDestructor - destructor has user declaration");
1601 (void) ClassDecl;
1602
1603 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1604 EmitDtorEpilogue(CD);
1605 FinishFunction();
1606}