blob: 9389af62d6f841d7017b80ac0e9c70aed71c6113 [file] [log] [blame]
Anders Carlssonc9f8ccd2008-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 Carlsson33e65e52009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniana0107de2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson7a9b2982009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson4715ebb2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbardea59212009-02-25 19:24:29 +000028void
Anders Carlssonf2a022a2009-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 Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonf2a022a2009-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 Anderson3f5cc0a2009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf2a022a2009-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 Carlssonf49ffa92009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf2a022a2009-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 Carlssoncde4a862009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlssoncde4a862009-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 Kramer3c1fe262009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlssoncde4a862009-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 Carlssonf2a022a2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbardea59212009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000136
Anders Carlsson33e65e52009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar0433a022009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar72f96552008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssonc9f8ccd2008-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 Carlssonf2a022a2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-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 Carlsson7a9b2982009-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 Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Mike Stump7e8c9932009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stumpc37c8812009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattner80f39cc2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000211
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000219 }
220
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000224
Anders Carlsson85eca6f2009-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 Jahanian9da58e42009-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 Carlsson85eca6f2009-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 Carlsson49d4a572009-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 Stumpba2cb0e2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson652951a2009-04-15 15:55:24 +0000267
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-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 Stumpf3371782009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-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 Jahaniand3f67282009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-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 Jahaniand3f67282009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanian5fe7f472009-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 Jahanian83a46ed2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-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 Jahanian70277012009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian2f4b91b2009-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.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000349 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000350 "loop.index");
351 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000352 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000353 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 =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000367 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000368 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 Jahanian2f4b91b2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000378 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000379 if (const ConstantArrayType *CAT =
380 dyn_cast<ConstantArrayType>(Array->getElementType())) {
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000381 uint64_t delta = getContext().getConstantArrayElementCount(CAT);
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000382 // Address = This + delta*Counter for current loop iteration.
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000383 llvm::Value *DeltaPtr =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000384 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), delta);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000385 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
386 llvm::Value *Address =
387 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000388 EmitCXXAggrConstructorCall(D, CAT, Address);
389 }
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000390 else {
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000391 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000392 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000393 }
394
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000395 EmitBlock(ContinueBlock);
396
397 // Emit the increment of the loop counter.
398 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
399 Counter = Builder.CreateLoad(IndexPtr);
400 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
401 Builder.CreateStore(NextVal, IndexPtr, false);
402
403 // Finally, branch back up to the condition for the next iteration.
404 EmitBranch(CondBlock);
405
406 // Emit the fall-through block.
407 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000408}
409
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000410/// EmitCXXAggrDestructorCall - calls the default destructor on array
411/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000412void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000413CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
414 const ArrayType *Array,
415 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000416 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
417 assert(CA && "Do we support VLA for destruction ?");
418 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
419 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000420 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000421 // Create a temporary for the loop index and initialize it with count of
422 // array elements.
423 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
424 "loop.index");
425 // Index = ElementCount;
426 llvm::Value* UpperCount =
427 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
428 Builder.CreateStore(UpperCount, IndexPtr, false);
429
430 // Start the loop with a block that tests the condition.
431 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
432 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
433
434 EmitBlock(CondBlock);
435
436 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
437
438 // Generate: if (loop-index != 0 fall to the loop body,
439 // otherwise, go to the block after the for-loop.
440 llvm::Value* zeroConstant =
441 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
442 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
443 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
444 "isne");
445 // If the condition is true, execute the body.
446 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
447
448 EmitBlock(ForBody);
449
450 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
451 // Inside the loop body, emit the constructor call on the array element.
452 Counter = Builder.CreateLoad(IndexPtr);
453 Counter = Builder.CreateSub(Counter, One);
454 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
455 EmitCXXDestructorCall(D, Dtor_Complete, Address);
456
457 EmitBlock(ContinueBlock);
458
459 // Emit the decrement of the loop counter.
460 Counter = Builder.CreateLoad(IndexPtr);
461 Counter = Builder.CreateSub(Counter, One, "dec");
462 Builder.CreateStore(Counter, IndexPtr, false);
463
464 // Finally, branch back up to the condition for the next iteration.
465 EmitBranch(CondBlock);
466
467 // Emit the fall-through block.
468 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000469}
470
471void
Anders Carlsson72f48292009-04-17 00:06:03 +0000472CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
473 CXXCtorType Type,
474 llvm::Value *This,
475 CallExpr::const_arg_iterator ArgBeg,
476 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000477 if (D->isCopyConstructor(getContext())) {
478 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
479 if (ClassDecl->hasTrivialCopyConstructor()) {
480 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
481 "EmitCXXConstructorCall - user declared copy constructor");
482 const Expr *E = (*ArgBeg);
483 QualType Ty = E->getType();
484 llvm::Value *Src = EmitLValue(E).getAddress();
485 EmitAggregateCopy(This, Src, Ty);
486 return;
487 }
488 }
489
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000490 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
491
492 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000493}
494
Anders Carlssond3f6b162009-05-29 21:03:38 +0000495void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
496 CXXDtorType Type,
497 llvm::Value *This) {
498 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
499
500 EmitCXXMemberCall(D, Callee, This, 0, 0);
501}
502
Anders Carlsson72f48292009-04-17 00:06:03 +0000503void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000504CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
505 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000506 assert(Dest && "Must have a destination!");
507
508 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000509 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000510 if (RD->hasTrivialConstructor())
511 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000512
513 // Code gen optimization to eliminate copy constructor and return
514 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000515 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000516 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000517 EmitAggExpr((*i), Dest, false);
518 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000519 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000520 // Call the constructor.
521 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
522 E->arg_begin(), E->arg_end());
523}
524
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000525llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000526 if (E->isArray()) {
527 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000528 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000529 }
530
531 QualType AllocType = E->getAllocatedType();
532 FunctionDecl *NewFD = E->getOperatorNew();
533 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
534
535 CallArgList NewArgs;
536
537 // The allocation size is the first argument.
538 QualType SizeTy = getContext().getSizeType();
539 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000540 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000541 getContext().getTypeSize(AllocType) / 8);
542
543 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
544
545 // Emit the rest of the arguments.
546 // FIXME: Ideally, this should just use EmitCallArgs.
547 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
548
549 // First, use the types from the function type.
550 // We start at 1 here because the first argument (the allocation size)
551 // has already been emitted.
552 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
553 QualType ArgType = NewFTy->getArgType(i);
554
555 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
556 getTypePtr() ==
557 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
558 "type mismatch in call argument!");
559
560 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
561 ArgType));
562
563 }
564
565 // Either we've emitted all the call args, or we have a call to a
566 // variadic function.
567 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
568 "Extra arguments in non-variadic function!");
569
570 // If we still have any arguments, emit them using the type of the argument.
571 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
572 NewArg != NewArgEnd; ++NewArg) {
573 QualType ArgType = NewArg->getType();
574 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
575 ArgType));
576 }
577
578 // Emit the call to new.
579 RValue RV =
580 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
581 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
582 NewArgs, NewFD);
583
Anders Carlsson11269042009-05-31 21:53:59 +0000584 // If an allocation function is declared with an empty exception specification
585 // it returns null to indicate failure to allocate storage. [expr.new]p13.
586 // (We don't need to check for null when there's no new initializer and
587 // we're allocating a POD type).
588 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
589 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000590
Anders Carlssondbee9a52009-06-01 00:05:16 +0000591 llvm::BasicBlock *NewNull = 0;
592 llvm::BasicBlock *NewNotNull = 0;
593 llvm::BasicBlock *NewEnd = 0;
594
595 llvm::Value *NewPtr = RV.getScalarVal();
596
Anders Carlsson11269042009-05-31 21:53:59 +0000597 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000598 NewNull = createBasicBlock("new.null");
599 NewNotNull = createBasicBlock("new.notnull");
600 NewEnd = createBasicBlock("new.end");
601
602 llvm::Value *IsNull =
603 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000604 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000605 "isnull");
606
607 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
608 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000609 }
610
Anders Carlssondbee9a52009-06-01 00:05:16 +0000611 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000612
Anders Carlsson7c294782009-05-31 20:56:36 +0000613 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000614 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000615 assert(E->getNumConstructorArgs() == 1 &&
616 "Can only have one argument to initializer of POD type.");
617
618 const Expr *Init = E->getConstructorArg(0);
619
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000620 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000621 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000622 else if (AllocType->isAnyComplexType())
623 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000624 else
625 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000626 }
Anders Carlsson11269042009-05-31 21:53:59 +0000627 } else {
628 // Call the constructor.
629 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000630
Anders Carlsson11269042009-05-31 21:53:59 +0000631 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
632 E->constructor_arg_begin(),
633 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000634 }
Anders Carlsson11269042009-05-31 21:53:59 +0000635
Anders Carlssondbee9a52009-06-01 00:05:16 +0000636 if (NullCheckResult) {
637 Builder.CreateBr(NewEnd);
638 EmitBlock(NewNull);
639 Builder.CreateBr(NewEnd);
640 EmitBlock(NewEnd);
641
642 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
643 PHI->reserveOperandSpace(2);
644 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000645 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000646
647 NewPtr = PHI;
648 }
649
Anders Carlsson11269042009-05-31 21:53:59 +0000650 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000651}
652
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000653void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
654 if (E->isArrayForm()) {
655 ErrorUnsupported(E, "delete[] expression");
656 return;
657 };
658
659 QualType DeleteTy =
660 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
661
662 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
663
664 // Null check the pointer.
665 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
666 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
667
668 llvm::Value *IsNull =
669 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
670 "isnull");
671
672 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
673 EmitBlock(DeleteNotNull);
674
675 // Call the destructor if necessary.
676 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
677 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
678 if (!RD->hasTrivialDestructor()) {
679 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
680 if (Dtor->isVirtual()) {
681 ErrorUnsupported(E, "delete expression with virtual destructor");
682 return;
683 }
684
685 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
686 }
687 }
688 }
689
690 // Call delete.
691 FunctionDecl *DeleteFD = E->getOperatorDelete();
692 const FunctionProtoType *DeleteFTy =
693 DeleteFD->getType()->getAsFunctionProtoType();
694
695 CallArgList DeleteArgs;
696
697 QualType ArgTy = DeleteFTy->getArgType(0);
698 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
699 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
700
701 // Emit the call to delete.
702 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
703 DeleteArgs),
704 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
705 DeleteArgs, DeleteFD);
706
707 EmitBlock(DeleteEnd);
708}
709
Anders Carlsson4811c302009-04-17 01:58:57 +0000710static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
711 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000712 // The class has base classes - we don't support that right now.
713 if (RD->getNumBases() > 0)
714 return false;
715
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000716 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
717 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000718 // We don't support ctors for fields that aren't POD.
719 if (!I->getType()->isPODType())
720 return false;
721 }
722
723 return true;
724}
725
Anders Carlsson652951a2009-04-15 15:55:24 +0000726void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000727 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000728 ErrorUnsupported(D, "C++ constructor", true);
729 return;
730 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000731
Anders Carlsson1764af42009-05-05 04:44:02 +0000732 EmitGlobal(GlobalDecl(D, Ctor_Complete));
733 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000734}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000735
Anders Carlsson4811c302009-04-17 01:58:57 +0000736void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
737 CXXCtorType Type) {
738
739 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
740
741 CodeGenFunction(*this).GenerateCode(D, Fn);
742
743 SetFunctionDefinitionAttributes(D, Fn);
744 SetLLVMFunctionAttributesForDefinition(D, Fn);
745}
746
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000747llvm::Function *
748CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
749 CXXCtorType Type) {
750 const llvm::FunctionType *FTy =
751 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
752
753 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000754 return cast<llvm::Function>(
755 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000756}
Anders Carlsson4811c302009-04-17 01:58:57 +0000757
758const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
759 CXXCtorType Type) {
760 llvm::SmallString<256> Name;
761 llvm::raw_svector_ostream Out(Name);
762 mangleCXXCtor(D, Type, Context, Out);
763
764 Name += '\0';
765 return UniqueMangledName(Name.begin(), Name.end());
766}
767
768void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
769 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
770 ErrorUnsupported(D, "C++ destructor", true);
771 return;
772 }
773
774 EmitCXXDestructor(D, Dtor_Complete);
775 EmitCXXDestructor(D, Dtor_Base);
776}
777
778void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
779 CXXDtorType Type) {
780 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
781
782 CodeGenFunction(*this).GenerateCode(D, Fn);
783
784 SetFunctionDefinitionAttributes(D, Fn);
785 SetLLVMFunctionAttributesForDefinition(D, Fn);
786}
787
788llvm::Function *
789CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
790 CXXDtorType Type) {
791 const llvm::FunctionType *FTy =
792 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
793
794 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000795 return cast<llvm::Function>(
796 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000797}
798
799const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
800 CXXDtorType Type) {
801 llvm::SmallString<256> Name;
802 llvm::raw_svector_ostream Out(Name);
803 mangleCXXDtor(D, Type, Context, Out);
804
805 Name += '\0';
806 return UniqueMangledName(Name.begin(), Name.end());
807}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000808
Mike Stumpdca5e512009-08-18 21:49:00 +0000809llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000810 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000811 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000812 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000813
814 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000815 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000816
817 llvm::SmallString<256> OutName;
818 llvm::raw_svector_ostream Out(OutName);
819 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000820 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000821 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000822 llvm::GlobalVariable::LinkageTypes linktype;
823 linktype = llvm::GlobalValue::WeakAnyLinkage;
824 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000825 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000826 // FIXME: descriptor
827 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000828 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000829 // FIXME: TS
830 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
831
832 llvm::Constant *C;
833 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
834 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000835 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000836 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000837 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
838 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000839}
840
Mike Stump86a859e2009-08-19 18:10:47 +0000841class VtableBuilder {
Mike Stumpad734d12009-08-18 20:50:28 +0000842 std::vector<llvm::Constant *> &methods;
843 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000844 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000845 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000846 /// BLayout - Layout for the most derived class that this vtable is being
847 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000848 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000850 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000851 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000852 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000853 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000854 /// Index - Maps a method decl into a vtable index. Useful for virtual
855 /// dispatch codegen.
856 llvm::DenseMap<const CXXMethodDecl *, int32_t> Index;
Mike Stumpd75d3232009-08-18 22:04:08 +0000857 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000858public:
Mike Stump86a859e2009-08-19 18:10:47 +0000859 VtableBuilder(std::vector<llvm::Constant *> &meth,
860 const CXXRecordDecl *c,
861 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000862 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
863 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
864 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000865 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
866 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000867
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000868 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
869 const CXXRecordDecl *RD,
870 bool VBoundary,
871 bool SecondaryVirtual) {
872 llvm::Constant *m = 0;
873
874 // FIXME: vcall: offset for virtual base for this function
875 if (SecondaryVirtual || VBoundary)
876 m = llvm::Constant::getNullValue(Ptr8Ty);
877 return m;
878 }
879
880 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
881 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000882 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000883
Mike Stumpd75d3232009-08-18 22:04:08 +0000884 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000885 me = RD->method_end(); mi != me; ++mi) {
886 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000887 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
888 if (m)
889 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000890 }
Mike Stumpf640de52009-08-12 23:14:12 +0000891 }
Mike Stump23b238e2009-08-12 23:25:18 +0000892 }
Mike Stumpf640de52009-08-12 23:14:12 +0000893
Mike Stump2b9ba612009-08-20 02:11:48 +0000894 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000895 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000896 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
897 e = RD->bases_end(); i != e; ++i) {
898 const CXXRecordDecl *Base =
899 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
900 if (i->isVirtual() && !SeenVBase.count(Base)) {
901 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000902 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000903 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000904 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000905 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
906 offsets.push_back(m);
907 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000908 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000909 }
910 }
911
Mike Stumpf07ede52009-08-21 01:45:00 +0000912 void StartNewTable() {
913 SeenVBase.clear();
914 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000915
Mike Stumpf07ede52009-08-21 01:45:00 +0000916 inline uint32_t nottoobig(uint64_t t) {
917 assert(t < (uint32_t)-1ULL || "vtable too big");
918 return t;
919 }
920#if 0
921 inline uint32_t nottoobig(uint32_t t) {
922 return t;
923 }
924#endif
925
926 void AddMethod(const CXXMethodDecl *MD, int32_t FirstIndex) {
927 typedef CXXMethodDecl::method_iterator meth_iter;
928
929 llvm::Constant *m;
930 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
931 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
932
933 // FIXME: Don't like the nested loops. For very large inheritance
934 // heirarchies we could have a table on the side with the final overridder
935 // and just replace each instance of an overridden method once. Would be
936 // nice to measure the cost/benefit on real code.
937
938 // If we can find a previously allocated slot for this, reuse it.
939 for (meth_iter mi = MD->begin_overridden_methods(),
940 e = MD->end_overridden_methods();
941 mi != e; ++mi) {
942 const CXXMethodDecl *OMD = *mi;
943 llvm::Constant *om;
944 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
945 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
946
947 for (int32_t i = FirstIndex, e = nottoobig(methods.size()); i != e; ++i) {
948 // FIXME: begin_overridden_methods might be too lax, covariance */
949 if (methods[i] == om) {
950 methods[i] = m;
951 Index[MD] = i;
952 return;
953 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000954 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000955 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000956
957 // else allocate a new slot.
958 Index[MD] = methods.size();
959 methods.push_back(m);
960 }
961
962 void GenerateMethods(const CXXRecordDecl *RD, int32_t FirstIndex) {
963 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
964 ++mi)
965 if (mi->isVirtual())
966 AddMethod(*mi, FirstIndex);
Mike Stumpdecd7812009-08-12 23:00:59 +0000967 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000968
Mike Stump7bae1282009-08-18 21:30:21 +0000969 void GenerateVtableForBase(const CXXRecordDecl *RD,
970 bool forPrimary,
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000971 bool VBoundary,
Mike Stump7bae1282009-08-18 21:30:21 +0000972 int64_t Offset,
Mike Stumpf07ede52009-08-21 01:45:00 +0000973 bool ForVirtualBase,
974 int32_t FirstIndex) {
Mike Stump7bae1282009-08-18 21:30:21 +0000975 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stumpc57b8272009-08-16 01:46:26 +0000976
Mike Stump7bae1282009-08-18 21:30:21 +0000977 if (RD && !RD->isDynamicClass())
978 return;
979
980 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
981 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
982 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
983
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000984 if (VBoundary || forPrimary || ForVirtualBase) {
985 // then comes the the vcall offsets for all our functions...
986 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
987 }
988
Mike Stump7bae1282009-08-18 21:30:21 +0000989 // The virtual base offsets come first...
990 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +0000991 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +0000992 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000993 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000994 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
995 e = offsets.rend(); i != e; ++i)
996 methods.push_back(*i);
997 }
998
Mike Stump7bae1282009-08-18 21:30:21 +0000999 bool Top = true;
1000
1001 // vtables are composed from the chain of primaries.
1002 if (PrimaryBase) {
1003 if (PrimaryBaseWasVirtual)
1004 IndirectPrimary.insert(PrimaryBase);
1005 Top = false;
Mike Stumpb6ff81e2009-08-19 02:06:38 +00001006 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpf07ede52009-08-21 01:45:00 +00001007 Offset, PrimaryBaseWasVirtual, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001008 }
1009
1010 if (Top) {
1011 int64_t BaseOffset;
1012 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +00001013 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1014 } else
1015 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +00001016 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1017 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1018 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +00001019 methods.push_back(rtti);
Mike Stumpc57b8272009-08-16 01:46:26 +00001020 }
Mike Stump2eade572009-08-13 22:53:07 +00001021
Mike Stump7bae1282009-08-18 21:30:21 +00001022 // And add the virtuals for the class to the primary vtable.
Mike Stumpf07ede52009-08-21 01:45:00 +00001023 GenerateMethods(RD, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001024
1025 // and then the non-virtual bases.
1026 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1027 e = RD->bases_end(); i != e; ++i) {
1028 if (i->isVirtual())
1029 continue;
1030 const CXXRecordDecl *Base =
1031 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1032 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1033 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001034 StartNewTable();
1035 FirstIndex = methods.size();
1036 GenerateVtableForBase(Base, true, false, o, false, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001037 }
1038 }
1039 }
1040
1041 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001042 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001043 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1044 e = RD->bases_end(); i != e; ++i) {
1045 const CXXRecordDecl *Base =
1046 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1047 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1048 // Mark it so we don't output it twice.
1049 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001050 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001051 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001052 int32_t FirstIndex = methods.size();
1053 GenerateVtableForBase(Base, false, true, BaseOffset, true, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001054 }
1055 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001056 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001057 }
1058 }
Mike Stump7bae1282009-08-18 21:30:21 +00001059};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001060
Mike Stump7e8c9932009-07-31 18:25:34 +00001061llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001062 llvm::SmallString<256> OutName;
1063 llvm::raw_svector_ostream Out(OutName);
1064 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001065 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001066 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001067 llvm::GlobalVariable::LinkageTypes linktype;
1068 linktype = llvm::GlobalValue::WeakAnyLinkage;
1069 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001070 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump8b82eeb2009-08-05 22:37:18 +00001071 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +00001072
1073 Offset += LLVMPointerWidth;
1074 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001075
Mike Stump86a859e2009-08-19 18:10:47 +00001076 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001077
Mike Stumpc57b8272009-08-16 01:46:26 +00001078 // First comes the vtables for all the non-virtual bases...
Mike Stumpf07ede52009-08-21 01:45:00 +00001079 b.GenerateVtableForBase(RD, true, false, 0, false, 0);
Mike Stump42368bb2009-08-14 01:44:03 +00001080
Mike Stumpc57b8272009-08-16 01:46:26 +00001081 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001082 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001083
Mike Stumpd0672782009-07-31 21:43:43 +00001084 llvm::Constant *C;
1085 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1086 C = llvm::ConstantArray::get(type, methods);
1087 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001088 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001089 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001090 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001091 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump8b82eeb2009-08-05 22:37:18 +00001092 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001093 return vtable;
1094}
1095
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001096/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1097/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1098/// copy or via a copy constructor call.
1099void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1100 llvm::Value *Src,
1101 const ArrayType *Array,
1102 const CXXRecordDecl *BaseClassDecl,
1103 QualType Ty) {
1104 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1105 assert(CA && "VLA cannot be copied over");
1106 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1107
1108 // Create a temporary for the loop index and initialize it with 0.
1109 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1110 "loop.index");
1111 llvm::Value* zeroConstant =
1112 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1113 Builder.CreateStore(zeroConstant, IndexPtr, false);
1114 // Start the loop with a block that tests the condition.
1115 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1116 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1117
1118 EmitBlock(CondBlock);
1119
1120 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1121 // Generate: if (loop-index < number-of-elements fall to the loop body,
1122 // otherwise, go to the block after the for-loop.
1123 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1124 llvm::Value * NumElementsPtr =
1125 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1126 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1127 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1128 "isless");
1129 // If the condition is true, execute the body.
1130 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1131
1132 EmitBlock(ForBody);
1133 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1134 // Inside the loop body, emit the constructor call on the array element.
1135 Counter = Builder.CreateLoad(IndexPtr);
1136 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1137 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1138 if (BitwiseCopy)
1139 EmitAggregateCopy(Dest, Src, Ty);
1140 else if (CXXConstructorDecl *BaseCopyCtor =
1141 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1142 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1143 Ctor_Complete);
1144 CallArgList CallArgs;
1145 // Push the this (Dest) ptr.
1146 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1147 BaseCopyCtor->getThisType(getContext())));
1148
1149 // Push the Src ptr.
1150 CallArgs.push_back(std::make_pair(RValue::get(Src),
1151 BaseCopyCtor->getParamDecl(0)->getType()));
1152 QualType ResultType =
1153 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1154 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1155 Callee, CallArgs, BaseCopyCtor);
1156 }
1157 EmitBlock(ContinueBlock);
1158
1159 // Emit the increment of the loop counter.
1160 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1161 Counter = Builder.CreateLoad(IndexPtr);
1162 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1163 Builder.CreateStore(NextVal, IndexPtr, false);
1164
1165 // Finally, branch back up to the condition for the next iteration.
1166 EmitBranch(CondBlock);
1167
1168 // Emit the fall-through block.
1169 EmitBlock(AfterFor, true);
1170}
1171
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001172/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1173/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001174/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001175void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001176 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001177 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001178 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1179 if (ClassDecl) {
1180 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1181 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1182 }
1183 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1184 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001185 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001186 }
1187
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001188 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001189 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001190 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1191 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001192 CallArgList CallArgs;
1193 // Push the this (Dest) ptr.
1194 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1195 BaseCopyCtor->getThisType(getContext())));
1196
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001197 // Push the Src ptr.
1198 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001199 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001200 QualType ResultType =
1201 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1202 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1203 Callee, CallArgs, BaseCopyCtor);
1204 }
1205}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001206
Fariborz Jahanian04500242009-08-12 23:34:46 +00001207/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1208/// object from SrcValue to DestValue. Assignment can be either a bitwise
1209/// assignment of via an assignment operator call.
1210void CodeGenFunction::EmitClassCopyAssignment(
1211 llvm::Value *Dest, llvm::Value *Src,
1212 const CXXRecordDecl *ClassDecl,
1213 const CXXRecordDecl *BaseClassDecl,
1214 QualType Ty) {
1215 if (ClassDecl) {
1216 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1217 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1218 }
1219 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1220 EmitAggregateCopy(Dest, Src, Ty);
1221 return;
1222 }
1223
1224 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001225 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1226 MD);
1227 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1228 (void)ConstCopyAssignOp;
1229
1230 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1231 const llvm::Type *LTy =
1232 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1233 FPT->isVariadic());
1234 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001235
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001236 CallArgList CallArgs;
1237 // Push the this (Dest) ptr.
1238 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1239 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001240
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001241 // Push the Src ptr.
1242 CallArgs.push_back(std::make_pair(RValue::get(Src),
1243 MD->getParamDecl(0)->getType()));
1244 QualType ResultType =
1245 MD->getType()->getAsFunctionType()->getResultType();
1246 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1247 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001248}
1249
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001250/// SynthesizeDefaultConstructor - synthesize a default constructor
1251void
1252CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1253 const FunctionDecl *FD,
1254 llvm::Function *Fn,
1255 const FunctionArgList &Args) {
1256 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1257 EmitCtorPrologue(CD);
1258 FinishFunction();
1259}
1260
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001261/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001262/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1263/// The implicitly-defined copy constructor for class X performs a memberwise
1264/// copy of its subobjects. The order of copying is the same as the order
1265/// of initialization of bases and members in a user-defined constructor
1266/// Each subobject is copied in the manner appropriate to its type:
1267/// if the subobject is of class type, the copy constructor for the class is
1268/// used;
1269/// if the subobject is an array, each element is copied, in the manner
1270/// appropriate to the element type;
1271/// if the subobject is of scalar type, the built-in assignment operator is
1272/// used.
1273/// Virtual base class subobjects shall be copied only once by the
1274/// implicitly-defined copy constructor
1275
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001276void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1277 const FunctionDecl *FD,
1278 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001279 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001280 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1281 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001282 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1283 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001284
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001285 FunctionArgList::const_iterator i = Args.begin();
1286 const VarDecl *ThisArg = i->first;
1287 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1288 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1289 const VarDecl *SrcArg = (i+1)->first;
1290 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1291 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1292
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001293 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1294 Base != ClassDecl->bases_end(); ++Base) {
1295 // FIXME. copy constrution of virtual base NYI
1296 if (Base->isVirtual())
1297 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001298
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001299 CXXRecordDecl *BaseClassDecl
1300 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001301 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1302 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001303 }
1304
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001305 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1306 FieldEnd = ClassDecl->field_end();
1307 Field != FieldEnd; ++Field) {
1308 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001309 const ConstantArrayType *Array =
1310 getContext().getAsConstantArrayType(FieldType);
1311 if (Array)
1312 FieldType = getContext().getBaseElementType(FieldType);
1313
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001314 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1315 CXXRecordDecl *FieldClassDecl
1316 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1317 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1318 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001319 if (Array) {
1320 const llvm::Type *BasePtr = ConvertType(FieldType);
1321 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1322 llvm::Value *DestBaseAddrPtr =
1323 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1324 llvm::Value *SrcBaseAddrPtr =
1325 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1326 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1327 FieldClassDecl, FieldType);
1328 }
1329 else
1330 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1331 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001332 continue;
1333 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001334 // Do a built-in assignment of scalar data members.
1335 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1336 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1337 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1338 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001339 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001340 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001341}
1342
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001343/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1344/// Before the implicitly-declared copy assignment operator for a class is
1345/// implicitly defined, all implicitly- declared copy assignment operators for
1346/// its direct base classes and its nonstatic data members shall have been
1347/// implicitly defined. [12.8-p12]
1348/// The implicitly-defined copy assignment operator for class X performs
1349/// memberwise assignment of its subob- jects. The direct base classes of X are
1350/// assigned first, in the order of their declaration in
1351/// the base-specifier-list, and then the immediate nonstatic data members of X
1352/// are assigned, in the order in which they were declared in the class
1353/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001354/// if the subobject is of class type, the copy assignment operator for the
1355/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001356/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001357///
1358/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001359/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001360///
1361/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001362/// used.
1363void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1364 const FunctionDecl *FD,
1365 llvm::Function *Fn,
1366 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001367
1368 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1369 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1370 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001371 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1372
Fariborz Jahanian04500242009-08-12 23:34:46 +00001373 FunctionArgList::const_iterator i = Args.begin();
1374 const VarDecl *ThisArg = i->first;
1375 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1376 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1377 const VarDecl *SrcArg = (i+1)->first;
1378 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1379 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1380
1381 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1382 Base != ClassDecl->bases_end(); ++Base) {
1383 // FIXME. copy assignment of virtual base NYI
1384 if (Base->isVirtual())
1385 continue;
1386
1387 CXXRecordDecl *BaseClassDecl
1388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1389 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1390 Base->getType());
1391 }
1392
1393 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1394 FieldEnd = ClassDecl->field_end();
1395 Field != FieldEnd; ++Field) {
1396 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1397
1398 // FIXME. How about copy assignment of arrays!
1399 assert(!getContext().getAsArrayType(FieldType) &&
1400 "FIXME. Copy assignment of arrays NYI");
1401
1402 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1403 CXXRecordDecl *FieldClassDecl
1404 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1405 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1406 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1407
1408 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1409 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1410 continue;
1411 }
1412 // Do a built-in assignment of scalar data members.
1413 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1414 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1415 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1416 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001417 }
1418
1419 // return *this;
1420 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001421
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001422 FinishFunction();
1423}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001424
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001425/// EmitCtorPrologue - This routine generates necessary code to initialize
1426/// base classes and non-static data members belonging to this constructor.
1427void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001428 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001429 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001430 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001431
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001432 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001433 E = CD->init_end();
1434 B != E; ++B) {
1435 CXXBaseOrMemberInitializer *Member = (*B);
1436 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001437 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001438 Type *BaseType = Member->getBaseClass();
1439 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001440 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001441 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1442 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001443 EmitCXXConstructorCall(Member->getConstructor(),
1444 Ctor_Complete, V,
1445 Member->const_arg_begin(),
1446 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001447 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001448 // non-static data member initilaizers.
1449 FieldDecl *Field = Member->getMember();
1450 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001451 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001452 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001453 if (Array)
1454 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001455
Mike Stump7e8c9932009-07-31 18:25:34 +00001456 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001457 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001458 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001459 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001460 assert(Member->getConstructor() &&
1461 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001462 if (Array) {
1463 const llvm::Type *BasePtr = ConvertType(FieldType);
1464 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1465 llvm::Value *BaseAddrPtr =
1466 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1467 EmitCXXAggrConstructorCall(Member->getConstructor(),
1468 Array, BaseAddrPtr);
1469 }
1470 else
1471 EmitCXXConstructorCall(Member->getConstructor(),
1472 Ctor_Complete, LHS.getAddress(),
1473 Member->const_arg_begin(),
1474 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001475 continue;
1476 }
1477 else {
1478 // Initializing an anonymous union data member.
1479 FieldDecl *anonMember = Member->getAnonUnionMember();
1480 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1481 FieldType = anonMember->getType();
1482 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001483 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001484
1485 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001486 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001487 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001488 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001489 }
1490 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001491
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001492 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001493 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001494 // have bases classes and/or contain non-static data members which require
1495 // construction.
1496 for (CXXRecordDecl::base_class_const_iterator Base =
1497 ClassDecl->bases_begin();
1498 Base != ClassDecl->bases_end(); ++Base) {
1499 // FIXME. copy assignment of virtual base NYI
1500 if (Base->isVirtual())
1501 continue;
1502
1503 CXXRecordDecl *BaseClassDecl
1504 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1505 if (BaseClassDecl->hasTrivialConstructor())
1506 continue;
1507 if (CXXConstructorDecl *BaseCX =
1508 BaseClassDecl->getDefaultConstructor(getContext())) {
1509 LoadOfThis = LoadCXXThis();
1510 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1511 BaseClassDecl);
1512 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1513 }
1514 }
1515
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001516 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1517 FieldEnd = ClassDecl->field_end();
1518 Field != FieldEnd; ++Field) {
1519 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001520 const ConstantArrayType *Array =
1521 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001522 if (Array)
1523 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001524 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1525 continue;
1526 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001527 CXXRecordDecl *MemberClassDecl =
1528 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1529 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1530 continue;
1531 if (CXXConstructorDecl *MamberCX =
1532 MemberClassDecl->getDefaultConstructor(getContext())) {
1533 LoadOfThis = LoadCXXThis();
1534 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001535 if (Array) {
1536 const llvm::Type *BasePtr = ConvertType(FieldType);
1537 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1538 llvm::Value *BaseAddrPtr =
1539 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1540 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1541 }
1542 else
1543 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1544 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001545 }
1546 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001547 }
1548
Mike Stump7e8c9932009-07-31 18:25:34 +00001549 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001550 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001551 if (!LoadOfThis)
1552 LoadOfThis = LoadCXXThis();
1553 llvm::Value *VtableField;
1554 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001555 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001556 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1557 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1558 llvm::Value *vtable = GenerateVtable(ClassDecl);
1559 Builder.CreateStore(vtable, VtableField);
1560 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001561}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001562
1563/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1564/// destructor. This is to call destructors on members and base classes
1565/// in reverse order of their construction.
1566void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1567 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1568 assert(!ClassDecl->isPolymorphic() &&
1569 "FIXME. polymorphic destruction not supported");
1570 (void)ClassDecl; // prevent warning.
1571
1572 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1573 *E = DD->destr_end(); B != E; ++B) {
1574 uintptr_t BaseOrMember = (*B);
1575 if (DD->isMemberToDestroy(BaseOrMember)) {
1576 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1577 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001578 const ConstantArrayType *Array =
1579 getContext().getAsConstantArrayType(FieldType);
1580 if (Array)
1581 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001582 const RecordType *RT = FieldType->getAs<RecordType>();
1583 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1584 if (FieldClassDecl->hasTrivialDestructor())
1585 continue;
1586 llvm::Value *LoadOfThis = LoadCXXThis();
1587 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001588 if (Array) {
1589 const llvm::Type *BasePtr = ConvertType(FieldType);
1590 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1591 llvm::Value *BaseAddrPtr =
1592 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1593 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1594 Array, BaseAddrPtr);
1595 }
1596 else
1597 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1598 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001599 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001600 const RecordType *RT =
1601 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1602 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1603 if (BaseClassDecl->hasTrivialDestructor())
1604 continue;
1605 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1606 ClassDecl,BaseClassDecl);
1607 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1608 Dtor_Complete, V);
1609 }
1610 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001611 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1612 return;
1613 // Case of destructor synthesis with fields and base classes
1614 // which have non-trivial destructors. They must be destructed in
1615 // reverse order of their construction.
1616 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1617
1618 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1619 FieldEnd = ClassDecl->field_end();
1620 Field != FieldEnd; ++Field) {
1621 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001622 if (getContext().getAsConstantArrayType(FieldType))
1623 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001624 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1625 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1626 if (FieldClassDecl->hasTrivialDestructor())
1627 continue;
1628 DestructedFields.push_back(*Field);
1629 }
1630 }
1631 if (!DestructedFields.empty())
1632 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1633 FieldDecl *Field = DestructedFields[i];
1634 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001635 const ConstantArrayType *Array =
1636 getContext().getAsConstantArrayType(FieldType);
1637 if (Array)
1638 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001639 const RecordType *RT = FieldType->getAs<RecordType>();
1640 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1641 llvm::Value *LoadOfThis = LoadCXXThis();
1642 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001643 if (Array) {
1644 const llvm::Type *BasePtr = ConvertType(FieldType);
1645 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1646 llvm::Value *BaseAddrPtr =
1647 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1648 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1649 Array, BaseAddrPtr);
1650 }
1651 else
1652 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1653 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001654 }
1655
1656 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1657 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1658 Base != ClassDecl->bases_end(); ++Base) {
1659 // FIXME. copy assignment of virtual base NYI
1660 if (Base->isVirtual())
1661 continue;
1662
1663 CXXRecordDecl *BaseClassDecl
1664 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1665 if (BaseClassDecl->hasTrivialDestructor())
1666 continue;
1667 DestructedBases.push_back(BaseClassDecl);
1668 }
1669 if (DestructedBases.empty())
1670 return;
1671 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1672 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1673 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1674 ClassDecl,BaseClassDecl);
1675 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1676 Dtor_Complete, V);
1677 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001678}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001679
1680void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1681 const FunctionDecl *FD,
1682 llvm::Function *Fn,
1683 const FunctionArgList &Args) {
1684
1685 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1686 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1687 "SynthesizeDefaultDestructor - destructor has user declaration");
1688 (void) ClassDecl;
1689
1690 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1691 EmitDtorEpilogue(CD);
1692 FinishFunction();
1693}