blob: 22ff22e22e4e9e9a932f3fd659374fcc942c1d09 [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
Douglas Gregor6ccc6f32009-09-04 19:04:08 +0000181 // A call to a trivial destructor requires no code generation.
182 if (const CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(MD))
183 if (Destructor->isTrivial())
184 return RValue::get(0);
185
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000186 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
187
188 CallArgList Args;
189
190 // Push the this ptr.
191 Args.push_back(std::make_pair(RValue::get(This),
192 MD->getThisType(getContext())));
193
194 // And the rest of the call args
195 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
196
197 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
198 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
199 Callee, Args, MD);
200}
201
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000202RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
203 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
204 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000205
Anders Carlssonc5223142009-04-08 20:31:57 +0000206 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000207
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000208 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000209 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
210 FPT->isVariadic());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000211 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000212
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000214 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000215 else {
216 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000217 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000218 }
Mike Stumpf7d47a52009-08-26 20:46:33 +0000219
Douglas Gregore399ad42009-08-26 22:36:53 +0000220 // C++ [class.virtual]p12:
221 // Explicit qualification with the scope operator (5.1) suppresses the
222 // virtual call mechanism.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000223 llvm::Value *Callee;
Douglas Gregorefccbec2009-08-31 21:41:48 +0000224 if (MD->isVirtual() && !ME->hasQualifier())
Mike Stumpf7d47a52009-08-26 20:46:33 +0000225 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregor6ccc6f32009-09-04 19:04:08 +0000226 else if (const CXXDestructorDecl *Destructor
227 = dyn_cast<CXXDestructorDecl>(MD))
228 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
Douglas Gregorefccbec2009-08-31 21:41:48 +0000229 else
Mike Stumpf7d47a52009-08-26 20:46:33 +0000230 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000231
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000232 return EmitCXXMemberCall(MD, Callee, This,
233 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000234}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000235
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000236RValue
237CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
238 const CXXMethodDecl *MD) {
239 assert(MD->isInstance() &&
240 "Trying to emit a member call expr on a static method!");
241
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000242 if (MD->isCopyAssignment()) {
243 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
244 if (ClassDecl->hasTrivialCopyAssignment()) {
245 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
246 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
247 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
248 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
249 QualType Ty = E->getType();
250 EmitAggregateCopy(This, Src, Ty);
251 return RValue::get(This);
252 }
253 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000254
255 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
256 const llvm::Type *Ty =
Mike Stumpd5b15562009-09-04 18:27:16 +0000257 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
258 FPT->isVariadic());
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000259 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
260
261 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
262
263 return EmitCXXMemberCall(MD, Callee, This,
264 E->arg_begin() + 1, E->arg_end());
265}
266
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000267RValue
268CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
269 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
270 "EmitCXXFunctionalCastExpr - called with wrong cast");
271
272 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000273 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
274 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
275 " method decl");
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000276 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000277
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000278 const llvm::Type *Ty =
279 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
280 FPT->isVariadic());
281 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
282 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
283 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
284 if (RV.isAggregate())
285 RV = RValue::get(RV.getAggregateAddr());
286 return RV;
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000287}
288
Anders Carlsson49d4a572009-04-14 16:58:56 +0000289llvm::Value *CodeGenFunction::LoadCXXThis() {
290 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
291 "Must be in a C++ member function decl to load 'this'");
292 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
293 "Must be in a C++ member function decl to load 'this'");
294
295 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000296 // ans: See how CodeGenFunction::LoadObjCSelf() uses
297 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000298 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
299}
Anders Carlsson652951a2009-04-15 15:55:24 +0000300
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000301static bool
302GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
303 const CXXRecordDecl *ClassDecl,
304 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000305 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
306 e = ClassDecl->bases_end(); i != e; ++i) {
307 if (i->isVirtual())
308 continue;
309 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000310 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000311 if (Base == BaseClassDecl) {
312 NestedBasePaths.push_back(BaseClassDecl);
313 return true;
314 }
315 }
316 // BaseClassDecl not an immediate base of ClassDecl.
317 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
318 e = ClassDecl->bases_end(); i != e; ++i) {
319 if (i->isVirtual())
320 continue;
321 const CXXRecordDecl *Base =
322 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
323 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
324 NestedBasePaths.push_back(Base);
325 return true;
326 }
327 }
328 return false;
329}
330
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000332 const CXXRecordDecl *ClassDecl,
333 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000334 if (ClassDecl == BaseClassDecl)
335 return BaseValue;
336
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000337 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000338 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
339 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
340 assert(NestedBasePaths.size() > 0 &&
341 "AddressCXXOfBaseClass - inheritence path failed");
342 NestedBasePaths.push_back(ClassDecl);
343 uint64_t Offset = 0;
344
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000345 // Accessing a member of the base class. Must add delata to
346 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000347 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
348 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
349 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
350 const ASTRecordLayout &Layout =
351 getContext().getASTRecordLayout(DerivedClass);
352 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
353 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000354 llvm::Value *OffsetVal =
355 llvm::ConstantInt::get(
356 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000357 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
358 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
359 QualType BTy =
360 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000361 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000362 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000363 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000364 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
365 return BaseValue;
366}
367
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000368/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
369/// for-loop to call the default constructor on individual members of the
370/// array. 'Array' is the array type, 'This' is llvm pointer of the start
371/// of the array and 'D' is the default costructor Decl for elements of the
372/// array. It is assumed that all relevant checks have been made by the
373/// caller.
374void
375CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
376 const ArrayType *Array,
377 llvm::Value *This) {
378 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
379 assert(CA && "Do we support VLA for construction ?");
380
381 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000382 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000383 "loop.index");
384 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000385 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000386 Builder.CreateStore(zeroConstant, IndexPtr, false);
387
388 // Start the loop with a block that tests the condition.
389 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
390 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
391
392 EmitBlock(CondBlock);
393
394 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
395
396 // Generate: if (loop-index < number-of-elements fall to the loop body,
397 // otherwise, go to the block after the for-loop.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000398 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000399 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000400 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000401 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
402 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
403 "isless");
404 // If the condition is true, execute the body.
405 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
406
407 EmitBlock(ForBody);
408
409 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000410 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000411 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000412 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
413 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000414
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000415 EmitBlock(ContinueBlock);
416
417 // Emit the increment of the loop counter.
418 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
419 Counter = Builder.CreateLoad(IndexPtr);
420 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
421 Builder.CreateStore(NextVal, IndexPtr, false);
422
423 // Finally, branch back up to the condition for the next iteration.
424 EmitBranch(CondBlock);
425
426 // Emit the fall-through block.
427 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000428}
429
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000430/// EmitCXXAggrDestructorCall - calls the default destructor on array
431/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000432void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000433CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
434 const ArrayType *Array,
435 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000436 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
437 assert(CA && "Do we support VLA for destruction ?");
438 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
439 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000440 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000441 // Create a temporary for the loop index and initialize it with count of
442 // array elements.
443 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
444 "loop.index");
445 // Index = ElementCount;
446 llvm::Value* UpperCount =
447 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
448 Builder.CreateStore(UpperCount, IndexPtr, false);
449
450 // Start the loop with a block that tests the condition.
451 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
452 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
453
454 EmitBlock(CondBlock);
455
456 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
457
458 // Generate: if (loop-index != 0 fall to the loop body,
459 // otherwise, go to the block after the for-loop.
460 llvm::Value* zeroConstant =
461 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
462 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
463 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
464 "isne");
465 // If the condition is true, execute the body.
466 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
467
468 EmitBlock(ForBody);
469
470 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
471 // Inside the loop body, emit the constructor call on the array element.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One);
474 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
475 EmitCXXDestructorCall(D, Dtor_Complete, Address);
476
477 EmitBlock(ContinueBlock);
478
479 // Emit the decrement of the loop counter.
480 Counter = Builder.CreateLoad(IndexPtr);
481 Counter = Builder.CreateSub(Counter, One, "dec");
482 Builder.CreateStore(Counter, IndexPtr, false);
483
484 // Finally, branch back up to the condition for the next iteration.
485 EmitBranch(CondBlock);
486
487 // Emit the fall-through block.
488 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000489}
490
491void
Anders Carlsson72f48292009-04-17 00:06:03 +0000492CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
493 CXXCtorType Type,
494 llvm::Value *This,
495 CallExpr::const_arg_iterator ArgBeg,
496 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000497 if (D->isCopyConstructor(getContext())) {
498 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
499 if (ClassDecl->hasTrivialCopyConstructor()) {
500 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
501 "EmitCXXConstructorCall - user declared copy constructor");
502 const Expr *E = (*ArgBeg);
503 QualType Ty = E->getType();
504 llvm::Value *Src = EmitLValue(E).getAddress();
505 EmitAggregateCopy(This, Src, Ty);
506 return;
507 }
508 }
509
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000510 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000513}
514
Anders Carlssond3f6b162009-05-29 21:03:38 +0000515void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
516 CXXDtorType Type,
517 llvm::Value *This) {
518 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
519
520 EmitCXXMemberCall(D, Callee, This, 0, 0);
521}
522
Anders Carlsson72f48292009-04-17 00:06:03 +0000523void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000524CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
525 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000526 assert(Dest && "Must have a destination!");
527
528 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000529 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000530 if (RD->hasTrivialConstructor())
531 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000532
533 // Code gen optimization to eliminate copy constructor and return
534 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000535 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000536 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000537 EmitAggExpr((*i), Dest, false);
538 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000539 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000540 // Call the constructor.
541 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
542 E->arg_begin(), E->arg_end());
543}
544
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000545llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000546 if (E->isArray()) {
547 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000548 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000549 }
550
551 QualType AllocType = E->getAllocatedType();
552 FunctionDecl *NewFD = E->getOperatorNew();
553 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
554
555 CallArgList NewArgs;
556
557 // The allocation size is the first argument.
558 QualType SizeTy = getContext().getSizeType();
559 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000560 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000561 getContext().getTypeSize(AllocType) / 8);
562
563 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
564
565 // Emit the rest of the arguments.
566 // FIXME: Ideally, this should just use EmitCallArgs.
567 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
568
569 // First, use the types from the function type.
570 // We start at 1 here because the first argument (the allocation size)
571 // has already been emitted.
572 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
573 QualType ArgType = NewFTy->getArgType(i);
574
575 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
576 getTypePtr() ==
577 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
578 "type mismatch in call argument!");
579
580 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
581 ArgType));
582
583 }
584
585 // Either we've emitted all the call args, or we have a call to a
586 // variadic function.
587 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
588 "Extra arguments in non-variadic function!");
589
590 // If we still have any arguments, emit them using the type of the argument.
591 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
592 NewArg != NewArgEnd; ++NewArg) {
593 QualType ArgType = NewArg->getType();
594 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
595 ArgType));
596 }
597
598 // Emit the call to new.
599 RValue RV =
600 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
601 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
602 NewArgs, NewFD);
603
Anders Carlsson11269042009-05-31 21:53:59 +0000604 // If an allocation function is declared with an empty exception specification
605 // it returns null to indicate failure to allocate storage. [expr.new]p13.
606 // (We don't need to check for null when there's no new initializer and
607 // we're allocating a POD type).
608 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
609 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000610
Anders Carlssondbee9a52009-06-01 00:05:16 +0000611 llvm::BasicBlock *NewNull = 0;
612 llvm::BasicBlock *NewNotNull = 0;
613 llvm::BasicBlock *NewEnd = 0;
614
615 llvm::Value *NewPtr = RV.getScalarVal();
616
Anders Carlsson11269042009-05-31 21:53:59 +0000617 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000618 NewNull = createBasicBlock("new.null");
619 NewNotNull = createBasicBlock("new.notnull");
620 NewEnd = createBasicBlock("new.end");
621
622 llvm::Value *IsNull =
623 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000624 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000625 "isnull");
626
627 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
628 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000629 }
630
Anders Carlssondbee9a52009-06-01 00:05:16 +0000631 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000632
Anders Carlsson7c294782009-05-31 20:56:36 +0000633 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000634 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000635 assert(E->getNumConstructorArgs() == 1 &&
636 "Can only have one argument to initializer of POD type.");
637
638 const Expr *Init = E->getConstructorArg(0);
639
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000640 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000641 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000642 else if (AllocType->isAnyComplexType())
643 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000644 else
645 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000646 }
Anders Carlsson11269042009-05-31 21:53:59 +0000647 } else {
648 // Call the constructor.
649 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000650
Anders Carlsson11269042009-05-31 21:53:59 +0000651 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
652 E->constructor_arg_begin(),
653 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000654 }
Anders Carlsson11269042009-05-31 21:53:59 +0000655
Anders Carlssondbee9a52009-06-01 00:05:16 +0000656 if (NullCheckResult) {
657 Builder.CreateBr(NewEnd);
658 EmitBlock(NewNull);
659 Builder.CreateBr(NewEnd);
660 EmitBlock(NewEnd);
661
662 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
663 PHI->reserveOperandSpace(2);
664 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000665 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000666
667 NewPtr = PHI;
668 }
669
Anders Carlsson11269042009-05-31 21:53:59 +0000670 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000671}
672
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000673void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
674 if (E->isArrayForm()) {
675 ErrorUnsupported(E, "delete[] expression");
676 return;
677 };
678
679 QualType DeleteTy =
680 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
681
682 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
683
684 // Null check the pointer.
685 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
686 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
687
688 llvm::Value *IsNull =
689 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
690 "isnull");
691
692 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
693 EmitBlock(DeleteNotNull);
694
695 // Call the destructor if necessary.
696 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
698 if (!RD->hasTrivialDestructor()) {
699 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
700 if (Dtor->isVirtual()) {
701 ErrorUnsupported(E, "delete expression with virtual destructor");
702 return;
703 }
704
705 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
706 }
707 }
708 }
709
710 // Call delete.
711 FunctionDecl *DeleteFD = E->getOperatorDelete();
712 const FunctionProtoType *DeleteFTy =
713 DeleteFD->getType()->getAsFunctionProtoType();
714
715 CallArgList DeleteArgs;
716
717 QualType ArgTy = DeleteFTy->getArgType(0);
718 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
719 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
720
721 // Emit the call to delete.
722 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
723 DeleteArgs),
724 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
725 DeleteArgs, DeleteFD);
726
727 EmitBlock(DeleteEnd);
728}
729
Anders Carlsson652951a2009-04-15 15:55:24 +0000730void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson1764af42009-05-05 04:44:02 +0000731 EmitGlobal(GlobalDecl(D, Ctor_Complete));
732 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000733}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000734
Anders Carlsson4811c302009-04-17 01:58:57 +0000735void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
736 CXXCtorType Type) {
737
738 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
739
740 CodeGenFunction(*this).GenerateCode(D, Fn);
741
742 SetFunctionDefinitionAttributes(D, Fn);
743 SetLLVMFunctionAttributesForDefinition(D, Fn);
744}
745
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000746llvm::Function *
747CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
748 CXXCtorType Type) {
749 const llvm::FunctionType *FTy =
750 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
751
752 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000753 return cast<llvm::Function>(
754 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000755}
Anders Carlsson4811c302009-04-17 01:58:57 +0000756
757const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
758 CXXCtorType Type) {
759 llvm::SmallString<256> Name;
760 llvm::raw_svector_ostream Out(Name);
761 mangleCXXCtor(D, Type, Context, Out);
762
763 Name += '\0';
764 return UniqueMangledName(Name.begin(), Name.end());
765}
766
767void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000768 EmitCXXDestructor(D, Dtor_Complete);
769 EmitCXXDestructor(D, Dtor_Base);
770}
771
772void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
773 CXXDtorType Type) {
774 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
775
776 CodeGenFunction(*this).GenerateCode(D, Fn);
777
778 SetFunctionDefinitionAttributes(D, Fn);
779 SetLLVMFunctionAttributesForDefinition(D, Fn);
780}
781
782llvm::Function *
783CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
784 CXXDtorType Type) {
785 const llvm::FunctionType *FTy =
786 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
787
788 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000789 return cast<llvm::Function>(
790 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000791}
792
793const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
794 CXXDtorType Type) {
795 llvm::SmallString<256> Name;
796 llvm::raw_svector_ostream Out(Name);
797 mangleCXXDtor(D, Type, Context, Out);
798
799 Name += '\0';
800 return UniqueMangledName(Name.begin(), Name.end());
801}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000802
Mike Stumpdca5e512009-08-18 21:49:00 +0000803llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000804 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000805 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000806 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000807
808 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000809 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000810
811 llvm::SmallString<256> OutName;
812 llvm::raw_svector_ostream Out(OutName);
813 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000814 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000815 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000816 llvm::GlobalVariable::LinkageTypes linktype;
817 linktype = llvm::GlobalValue::WeakAnyLinkage;
818 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000819 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000820 // FIXME: descriptor
821 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000822 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000823 // FIXME: TS
824 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
825
826 llvm::Constant *C;
827 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
828 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000829 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000830 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000831 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
832 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000833}
834
Mike Stump86a859e2009-08-19 18:10:47 +0000835class VtableBuilder {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000836public:
837 /// Index_t - Vtable index type.
838 typedef uint64_t Index_t;
839private:
Mike Stumpad734d12009-08-18 20:50:28 +0000840 std::vector<llvm::Constant *> &methods;
Mike Stumpf3245642009-08-28 23:22:54 +0000841 std::vector<llvm::Constant *> submethods;
Mike Stumpad734d12009-08-18 20:50:28 +0000842 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000843 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000844 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000845 /// BLayout - Layout for the most derived class that this vtable is being
846 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000847 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000848 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000850 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000851 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000852 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000853 /// Index - Maps a method decl into a vtable index. Useful for virtual
854 /// dispatch codegen.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000855 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpf3245642009-08-28 23:22:54 +0000856 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
857 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCallOffset;
Mike Stump58256412009-09-05 07:20:32 +0000858 typedef llvm::DenseMap<const CXXMethodDecl *,
859 std::pair<Index_t, Index_t> > Thunks_t;
860 Thunks_t Thunks;
Mike Stumpf3245642009-08-28 23:22:54 +0000861 std::vector<Index_t> VCalls;
Mike Stumpd75d3232009-08-18 22:04:08 +0000862 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpd5b15562009-09-04 18:27:16 +0000863 // FIXME: Linkage should follow vtable
864 const bool Extern;
Mike Stump58256412009-09-05 07:20:32 +0000865 const uint32_t LLVMPointerWidth;
866 Index_t extra;
Mike Stumpad734d12009-08-18 20:50:28 +0000867public:
Mike Stump86a859e2009-08-19 18:10:47 +0000868 VtableBuilder(std::vector<llvm::Constant *> &meth,
869 const CXXRecordDecl *c,
870 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000871 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
872 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
Mike Stump58256412009-09-05 07:20:32 +0000873 CGM(cgm), Extern(true),
874 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Mike Stumpad734d12009-08-18 20:50:28 +0000875 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
876 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000877
Mike Stumpf7d47a52009-08-26 20:46:33 +0000878 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000879
Mike Stumpf3245642009-08-28 23:22:54 +0000880 llvm::Constant *wrap(Index_t i) {
881 llvm::Constant *m;
882 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
883 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000884 }
885
Mike Stumpf3245642009-08-28 23:22:54 +0000886 llvm::Constant *wrap(llvm::Constant *m) {
887 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
Mike Stump23b238e2009-08-12 23:25:18 +0000888 }
Mike Stumpf640de52009-08-12 23:14:12 +0000889
Mike Stump2b9ba612009-08-20 02:11:48 +0000890 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000891 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000892 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
893 e = RD->bases_end(); i != e; ++i) {
894 const CXXRecordDecl *Base =
895 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
896 if (i->isVirtual() && !SeenVBase.count(Base)) {
897 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000898 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stumpf3245642009-08-28 23:22:54 +0000899 llvm::Constant *m = wrap(BaseOffset);
900 m = wrap((0?700:0) + BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000901 offsets.push_back(m);
902 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000903 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000904 }
905 }
906
Mike Stumpf07ede52009-08-21 01:45:00 +0000907 void StartNewTable() {
908 SeenVBase.clear();
909 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000910
Mike Stump35af2b12009-09-01 22:20:28 +0000911 bool OverrideMethod(const CXXMethodDecl *MD, llvm::Constant *m,
Mike Stumpd5b15562009-09-04 18:27:16 +0000912 bool MorallyVirtual, Index_t Offset,
913 std::vector<llvm::Constant *> &submethods,
914 Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000915 typedef CXXMethodDecl::method_iterator meth_iter;
916
Mike Stumpf07ede52009-08-21 01:45:00 +0000917 // FIXME: Don't like the nested loops. For very large inheritance
918 // heirarchies we could have a table on the side with the final overridder
919 // and just replace each instance of an overridden method once. Would be
920 // nice to measure the cost/benefit on real code.
921
Mike Stumpf07ede52009-08-21 01:45:00 +0000922 for (meth_iter mi = MD->begin_overridden_methods(),
923 e = MD->end_overridden_methods();
924 mi != e; ++mi) {
925 const CXXMethodDecl *OMD = *mi;
926 llvm::Constant *om;
927 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
928 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
929
Mike Stumpd5b15562009-09-04 18:27:16 +0000930 for (Index_t i = AddressPoint, e = submethods.size();
Mike Stumpf7d47a52009-08-26 20:46:33 +0000931 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000932 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stump58256412009-09-05 07:20:32 +0000933 if (submethods[i] != om)
934 continue;
935 submethods[i] = m;
936 Index[MD] = i - AddressPoint;
937
938 Thunks.erase(OMD);
939 if (MorallyVirtual) {
940 VCallOffset[MD] = Offset/8;
941 Index_t &idx = VCall[OMD];
942 if (idx == 0) {
943 idx = VCalls.size()+1;
944 VCalls.push_back(0);
Mike Stumpf3245642009-08-28 23:22:54 +0000945 }
Mike Stump58256412009-09-05 07:20:32 +0000946 VCalls[idx] = Offset/8 - VCallOffset[OMD];
947 VCall[MD] = idx;
948 // FIXME: 0?
949 Thunks[MD] = std::make_pair(0, -((idx+extra+2)*LLVMPointerWidth/8));
Mike Stump35af2b12009-09-01 22:20:28 +0000950 return true;
Mike Stumpf07ede52009-08-21 01:45:00 +0000951 }
Mike Stump58256412009-09-05 07:20:32 +0000952#if 0
953 // FIXME: finish off
954 int64_t O = VCallOffset[OMD] - Offset/8;
955 if (O) {
956 Thunks[MD] = std::make_pair(O, 0);
957 }
958#endif
959 return true;
Mike Stump1e10cf32009-08-18 21:03:28 +0000960 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000961 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000962
Mike Stump35af2b12009-09-01 22:20:28 +0000963 return false;
964 }
965
Mike Stumpf0415ae2009-09-05 11:28:33 +0000966 void InstallThunks() {
Mike Stump58256412009-09-05 07:20:32 +0000967 for (Thunks_t::iterator i = Thunks.begin(), e = Thunks.end();
968 i != e; ++i) {
969 const CXXMethodDecl *MD = i->first;
970 Index_t idx = Index[MD];
971 Index_t nv_O = i->second.first;
972 Index_t v_O = i->second.second;
Mike Stumpf0415ae2009-09-05 11:28:33 +0000973 submethods[idx] = CGM.BuildThunk(MD, Extern, nv_O, v_O);
Mike Stump58256412009-09-05 07:20:32 +0000974 }
975 Thunks.clear();
976 }
977
Mike Stumpf0415ae2009-09-05 11:28:33 +0000978 void OverrideMethods(std::vector<const CXXRecordDecl *> *Path,
Mike Stump35240ec2009-09-01 23:22:44 +0000979 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf0415ae2009-09-05 11:28:33 +0000980 for (std::vector<const CXXRecordDecl *>::reverse_iterator i =Path->rbegin(),
981 e = Path->rend(); i != e; ++i) {
982 const CXXRecordDecl *RD = *i;
983 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
984 ++mi)
985 if (mi->isVirtual()) {
986 const CXXMethodDecl *MD = *mi;
987 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD),
988 Ptr8Ty));
989 OverrideMethod(MD, m, MorallyVirtual, Offset, submethods, 0);
990 }
991 }
Mike Stump35240ec2009-09-01 23:22:44 +0000992 }
993
Mike Stump53f32982009-09-05 07:49:12 +0000994 void AddMethod(const CXXMethodDecl *MD, bool MorallyVirtual, Index_t Offset) {
Mike Stump35240ec2009-09-01 23:22:44 +0000995 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stump58256412009-09-05 07:20:32 +0000996 // If we can find a previously allocated slot for this, reuse it.
Mike Stumpd5b15562009-09-04 18:27:16 +0000997 if (OverrideMethod(MD, m, MorallyVirtual, Offset, submethods, 0))
Mike Stump35af2b12009-09-01 22:20:28 +0000998 return;
999
Mike Stumpf07ede52009-08-21 01:45:00 +00001000 // else allocate a new slot.
Mike Stumpf3245642009-08-28 23:22:54 +00001001 Index[MD] = submethods.size();
Mike Stumpf3245642009-08-28 23:22:54 +00001002 if (MorallyVirtual) {
1003 VCallOffset[MD] = Offset/8;
1004 Index_t &idx = VCall[MD];
1005 // Allocate the first one, after that, we reuse the previous one.
1006 if (idx == 0) {
1007 idx = VCalls.size()+1;
Mike Stumpf3245642009-08-28 23:22:54 +00001008 VCalls.push_back(0);
1009 }
1010 }
1011 submethods.push_back(m);
Mike Stumpf07ede52009-08-21 01:45:00 +00001012 }
1013
Mike Stump53f32982009-09-05 07:49:12 +00001014 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
1015 Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +00001016 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
1017 ++mi)
1018 if (mi->isVirtual())
Mike Stump53f32982009-09-05 07:49:12 +00001019 AddMethod(*mi, MorallyVirtual, Offset);
Mike Stumpdecd7812009-08-12 23:00:59 +00001020 }
Mike Stump1e10cf32009-08-18 21:03:28 +00001021
Mike Stump58256412009-09-05 07:20:32 +00001022 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
1023 const CXXRecordDecl *PrimaryBase,
1024 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
1025 int64_t Offset) {
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);
1034 StartNewTable();
Mike Stumpf0415ae2009-09-05 11:28:33 +00001035 std::vector<const CXXRecordDecl *> S;
1036 S.push_back(RD);
1037 GenerateVtableForBase(Base, MorallyVirtual, o, false, &S);
Mike Stump58256412009-09-05 07:20:32 +00001038 }
1039 }
1040 }
1041
Mike Stump53f32982009-09-05 07:49:12 +00001042 Index_t end(const CXXRecordDecl *RD, std::vector<llvm::Constant *> &offsets,
1043 const ASTRecordLayout &Layout,
1044 const CXXRecordDecl *PrimaryBase,
1045 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
1046 int64_t Offset, bool ForVirtualBase) {
1047 StartNewTable();
1048 extra = 0;
1049 // FIXME: Cleanup.
1050 if (!ForVirtualBase) {
1051 // then virtual base offsets...
1052 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1053 e = offsets.rend(); i != e; ++i)
1054 methods.push_back(*i);
1055 }
1056
1057 // The vcalls come first...
1058 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1059 i < e; ++i)
1060 methods.push_back(wrap((0?600:0) + *i));
1061 VCalls.clear();
1062
1063 if (ForVirtualBase) {
1064 // then virtual base offsets...
1065 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1066 e = offsets.rend(); i != e; ++i)
1067 methods.push_back(*i);
1068 }
1069
1070 methods.push_back(wrap(-(Offset/8)));
1071 methods.push_back(rtti);
1072 Index_t AddressPoint = methods.size();
1073
Mike Stumpf0415ae2009-09-05 11:28:33 +00001074 InstallThunks();
Mike Stump53f32982009-09-05 07:49:12 +00001075 methods.insert(methods.end(), submethods.begin(), submethods.end());
1076 submethods.clear();
Mike Stump53f32982009-09-05 07:49:12 +00001077
1078 // and then the non-virtual bases.
1079 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
1080 MorallyVirtual, Offset);
1081 return AddressPoint;
1082 }
1083
Mike Stump8e0f10f2009-09-05 08:40:18 +00001084 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset) {
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001085 if (!RD->isDynamicClass())
1086 return;
1087
1088 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1089 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1090 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1091
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001092 // vtables are composed from the chain of primaries.
1093 if (PrimaryBase) {
1094 if (PrimaryBaseWasVirtual)
1095 IndirectPrimary.insert(PrimaryBase);
Mike Stump8e0f10f2009-09-05 08:40:18 +00001096 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset);
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001097 }
1098
1099 // And add the virtuals for the class to the primary vtable.
1100 AddMethods(RD, MorallyVirtual, Offset);
1101 }
1102
Mike Stump634ef532009-09-05 09:10:58 +00001103 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stump3cd18e42009-09-05 09:24:43 +00001104 bool MorallyVirtual = false, int64_t Offset = 0,
1105 bool ForVirtualBase = false,
Mike Stumpf0415ae2009-09-05 11:28:33 +00001106 std::vector<const CXXRecordDecl *> *Path = 0) {
Mike Stump900acd32009-09-05 08:07:32 +00001107 if (!RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +00001108 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +00001109
1110 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1111 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1112 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1113
Mike Stumpf3245642009-08-28 23:22:54 +00001114 std::vector<llvm::Constant *> offsets;
Mike Stump8e8e0f42009-09-05 08:45:02 +00001115 extra = 0;
1116 GenerateVBaseOffsets(offsets, RD, Offset);
1117 if (ForVirtualBase)
1118 extra = offsets.size();
Mike Stump7bae1282009-08-18 21:30:21 +00001119
1120 // vtables are composed from the chain of primaries.
1121 if (PrimaryBase) {
1122 if (PrimaryBaseWasVirtual)
1123 IndirectPrimary.insert(PrimaryBase);
Mike Stump8e0f10f2009-09-05 08:40:18 +00001124 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +00001125 }
1126
Mike Stumpf3245642009-08-28 23:22:54 +00001127 // And add the virtuals for the class to the primary vtable.
Mike Stump53f32982009-09-05 07:49:12 +00001128 AddMethods(RD, MorallyVirtual, Offset);
Mike Stumpf3245642009-08-28 23:22:54 +00001129
Mike Stumpf0415ae2009-09-05 11:28:33 +00001130 if (Path)
1131 OverrideMethods(Path, MorallyVirtual, Offset);
1132
Mike Stump53f32982009-09-05 07:49:12 +00001133 return end(RD, offsets, Layout, PrimaryBase, PrimaryBaseWasVirtual,
1134 MorallyVirtual, Offset, ForVirtualBase);
Mike Stump7bae1282009-08-18 21:30:21 +00001135 }
1136
Mike Stumpf0415ae2009-09-05 11:28:33 +00001137 void GenerateVtableForVBases(const CXXRecordDecl *RD,
1138 std::vector<const CXXRecordDecl *> *Path = 0) {
1139 bool alloc = false;
1140 if (Path == 0) {
1141 alloc = true;
1142 Path = new std::vector<const CXXRecordDecl *>;
1143 }
1144 // FIXME: We also need to override using all paths to a virtual base,
1145 // right now, we just process the first path
1146 Path->push_back(RD);
Mike Stump7bae1282009-08-18 21:30:21 +00001147 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1148 e = RD->bases_end(); i != e; ++i) {
1149 const CXXRecordDecl *Base =
1150 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1151 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1152 // Mark it so we don't output it twice.
1153 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001154 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001155 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf0415ae2009-09-05 11:28:33 +00001156 GenerateVtableForBase(Base, true, BaseOffset, true, Path);
Mike Stump7bae1282009-08-18 21:30:21 +00001157 }
1158 if (Base->getNumVBases())
Mike Stumpf0415ae2009-09-05 11:28:33 +00001159 GenerateVtableForVBases(Base, Path);
Mike Stumpc57b8272009-08-16 01:46:26 +00001160 }
Mike Stumpf0415ae2009-09-05 11:28:33 +00001161 Path->pop_back();
1162 if (alloc)
1163 delete Path;
Mike Stumpc57b8272009-08-16 01:46:26 +00001164 }
Mike Stump7bae1282009-08-18 21:30:21 +00001165};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001166
Mike Stumpf7d47a52009-08-26 20:46:33 +00001167class VtableInfo {
1168public:
1169 typedef VtableBuilder::Index_t Index_t;
1170private:
1171 CodeGenModule &CGM; // Per-module state.
1172 /// Index_t - Vtable index type.
1173 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1174 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1175 // FIXME: Move to Context.
1176 static MapTy IndexFor;
1177public:
1178 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1179 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1180 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1181 // We own a copy of this, it will go away shortly.
1182 new ElTy (e);
1183 IndexFor[RD] = new ElTy (e);
1184 }
1185 Index_t lookup(const CXXMethodDecl *MD) {
1186 const CXXRecordDecl *RD = MD->getParent();
1187 MapTy::iterator I = IndexFor.find(RD);
1188 if (I == IndexFor.end()) {
1189 std::vector<llvm::Constant *> methods;
1190 VtableBuilder b(methods, RD, CGM);
Mike Stump3cd18e42009-09-05 09:24:43 +00001191 b.GenerateVtableForBase(RD);
Mike Stump900acd32009-09-05 08:07:32 +00001192 b.GenerateVtableForVBases(RD);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001193 register_index(RD, b.getIndex());
1194 I = IndexFor.find(RD);
1195 }
1196 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1197 return (*I->second)[MD];
1198 }
1199};
1200
1201// FIXME: Move to Context.
1202VtableInfo::MapTy VtableInfo::IndexFor;
1203
Mike Stump7e8c9932009-07-31 18:25:34 +00001204llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001205 llvm::SmallString<256> OutName;
1206 llvm::raw_svector_ostream Out(OutName);
1207 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001208 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001209 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001210 llvm::GlobalVariable::LinkageTypes linktype;
1211 linktype = llvm::GlobalValue::WeakAnyLinkage;
1212 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001213 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stumpf0415ae2009-09-05 11:28:33 +00001214 int64_t AddressPoint;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001215
Mike Stump86a859e2009-08-19 18:10:47 +00001216 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001217
Mike Stumpc57b8272009-08-16 01:46:26 +00001218 // First comes the vtables for all the non-virtual bases...
Mike Stumpf0415ae2009-09-05 11:28:33 +00001219 AddressPoint = b.GenerateVtableForBase(RD);
Mike Stump42368bb2009-08-14 01:44:03 +00001220
Mike Stumpc57b8272009-08-16 01:46:26 +00001221 // then the vtables for all the virtual bases.
Mike Stump900acd32009-09-05 08:07:32 +00001222 b.GenerateVtableForVBases(RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001223
Mike Stumpd0672782009-07-31 21:43:43 +00001224 llvm::Constant *C;
1225 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1226 C = llvm::ConstantArray::get(type, methods);
1227 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001228 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001229 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001230 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001231 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stumpf0415ae2009-09-05 11:28:33 +00001232 AddressPoint*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001233 return vtable;
1234}
1235
Mike Stumpf7d47a52009-08-26 20:46:33 +00001236// FIXME: move to Context
1237static VtableInfo *vtableinfo;
1238
Mike Stumpd5b15562009-09-04 18:27:16 +00001239llvm::Constant *CodeGenFunction::GenerateThunk(llvm::Function *Fn,
1240 const CXXMethodDecl *MD,
Mike Stump58256412009-09-05 07:20:32 +00001241 bool Extern, int64_t nv,
1242 int64_t v) {
Mike Stumpd5b15562009-09-04 18:27:16 +00001243 QualType R = MD->getType()->getAsFunctionType()->getResultType();
1244
1245 FunctionArgList Args;
1246 ImplicitParamDecl *ThisDecl =
1247 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
1248 MD->getThisType(getContext()));
1249 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
1250 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
1251 e = MD->param_end();
1252 i != e; ++i) {
1253 ParmVarDecl *D = *i;
1254 Args.push_back(std::make_pair(D, D->getType()));
1255 }
1256 IdentifierInfo *II
1257 = &CGM.getContext().Idents.get("__thunk_named_foo_");
1258 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1259 getContext().getTranslationUnitDecl(),
1260 SourceLocation(), II, R, 0,
1261 Extern
1262 ? FunctionDecl::Extern
1263 : FunctionDecl::Static,
1264 false, true);
1265 StartFunction(FD, R, Fn, Args, SourceLocation());
1266 // FIXME: generate body
1267 FinishFunction();
1268 return Fn;
1269}
1270
Mike Stump58256412009-09-05 07:20:32 +00001271llvm::Constant *CodeGenModule::BuildThunk(const CXXMethodDecl *MD, bool Extern,
1272 int64_t nv, int64_t v) {
Mike Stumpd5b15562009-09-04 18:27:16 +00001273 llvm::SmallString<256> OutName;
1274 llvm::raw_svector_ostream Out(OutName);
Mike Stump58256412009-09-05 07:20:32 +00001275 mangleThunk(MD, nv, v, getContext(), Out);
Mike Stumpd5b15562009-09-04 18:27:16 +00001276 llvm::GlobalVariable::LinkageTypes linktype;
1277 linktype = llvm::GlobalValue::WeakAnyLinkage;
1278 if (!Extern)
1279 linktype = llvm::GlobalValue::InternalLinkage;
1280 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1281 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1282 const llvm::FunctionType *FTy =
1283 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1284 FPT->isVariadic());
1285
1286 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(),
1287 &getModule());
Mike Stump58256412009-09-05 07:20:32 +00001288 CodeGenFunction(*this).GenerateThunk(Fn, MD, Extern, nv, v);
Mike Stumpd5b15562009-09-04 18:27:16 +00001289 // Fn = Builder.CreateBitCast(Fn, Ptr8Ty);
1290 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1291 return m;
1292}
1293
Mike Stumpf7d47a52009-08-26 20:46:33 +00001294llvm::Value *
1295CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1296 const llvm::Type *Ty) {
1297 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1298
1299 // FIXME: move to Context
1300 if (vtableinfo == 0)
1301 vtableinfo = new VtableInfo(CGM);
1302
1303 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1304
1305 Ty = llvm::PointerType::get(Ty, 0);
1306 Ty = llvm::PointerType::get(Ty, 0);
1307 Ty = llvm::PointerType::get(Ty, 0);
1308 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1309 vtbl = Builder.CreateLoad(vtbl);
1310 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1311 Idx, "vfn");
1312 vfn = Builder.CreateLoad(vfn);
1313 return vfn;
1314}
1315
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001316/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1317/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1318/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001319// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001320void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1321 llvm::Value *Src,
1322 const ArrayType *Array,
1323 const CXXRecordDecl *BaseClassDecl,
1324 QualType Ty) {
1325 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1326 assert(CA && "VLA cannot be copied over");
1327 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1328
1329 // Create a temporary for the loop index and initialize it with 0.
1330 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1331 "loop.index");
1332 llvm::Value* zeroConstant =
1333 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1334 Builder.CreateStore(zeroConstant, IndexPtr, false);
1335 // Start the loop with a block that tests the condition.
1336 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1337 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1338
1339 EmitBlock(CondBlock);
1340
1341 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1342 // Generate: if (loop-index < number-of-elements fall to the loop body,
1343 // otherwise, go to the block after the for-loop.
1344 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1345 llvm::Value * NumElementsPtr =
1346 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1347 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1348 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1349 "isless");
1350 // If the condition is true, execute the body.
1351 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1352
1353 EmitBlock(ForBody);
1354 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1355 // Inside the loop body, emit the constructor call on the array element.
1356 Counter = Builder.CreateLoad(IndexPtr);
1357 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1358 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1359 if (BitwiseCopy)
1360 EmitAggregateCopy(Dest, Src, Ty);
1361 else if (CXXConstructorDecl *BaseCopyCtor =
1362 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1363 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1364 Ctor_Complete);
1365 CallArgList CallArgs;
1366 // Push the this (Dest) ptr.
1367 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1368 BaseCopyCtor->getThisType(getContext())));
1369
1370 // Push the Src ptr.
1371 CallArgs.push_back(std::make_pair(RValue::get(Src),
1372 BaseCopyCtor->getParamDecl(0)->getType()));
1373 QualType ResultType =
1374 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1375 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1376 Callee, CallArgs, BaseCopyCtor);
1377 }
1378 EmitBlock(ContinueBlock);
1379
1380 // Emit the increment of the loop counter.
1381 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1382 Counter = Builder.CreateLoad(IndexPtr);
1383 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1384 Builder.CreateStore(NextVal, IndexPtr, false);
1385
1386 // Finally, branch back up to the condition for the next iteration.
1387 EmitBranch(CondBlock);
1388
1389 // Emit the fall-through block.
1390 EmitBlock(AfterFor, true);
1391}
1392
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001393/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1394/// array of objects from SrcValue to DestValue. Assignment can be either a
1395/// bitwise assignment or via a copy assignment operator function call.
1396/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1397void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1398 llvm::Value *Src,
1399 const ArrayType *Array,
1400 const CXXRecordDecl *BaseClassDecl,
1401 QualType Ty) {
1402 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1403 assert(CA && "VLA cannot be asssigned");
1404 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1405
1406 // Create a temporary for the loop index and initialize it with 0.
1407 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1408 "loop.index");
1409 llvm::Value* zeroConstant =
1410 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1411 Builder.CreateStore(zeroConstant, IndexPtr, false);
1412 // Start the loop with a block that tests the condition.
1413 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1414 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1415
1416 EmitBlock(CondBlock);
1417
1418 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1419 // Generate: if (loop-index < number-of-elements fall to the loop body,
1420 // otherwise, go to the block after the for-loop.
1421 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1422 llvm::Value * NumElementsPtr =
1423 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1424 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1425 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1426 "isless");
1427 // If the condition is true, execute the body.
1428 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1429
1430 EmitBlock(ForBody);
1431 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1432 // Inside the loop body, emit the assignment operator call on array element.
1433 Counter = Builder.CreateLoad(IndexPtr);
1434 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1435 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1436 const CXXMethodDecl *MD = 0;
1437 if (BitwiseAssign)
1438 EmitAggregateCopy(Dest, Src, Ty);
1439 else {
1440 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1441 MD);
1442 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1443 (void)hasCopyAssign;
1444 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1445 const llvm::Type *LTy =
1446 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1447 FPT->isVariadic());
1448 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1449
1450 CallArgList CallArgs;
1451 // Push the this (Dest) ptr.
1452 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1453 MD->getThisType(getContext())));
1454
1455 // Push the Src ptr.
1456 CallArgs.push_back(std::make_pair(RValue::get(Src),
1457 MD->getParamDecl(0)->getType()));
Mike Stumpd5b15562009-09-04 18:27:16 +00001458 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001459 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1460 Callee, CallArgs, MD);
1461 }
1462 EmitBlock(ContinueBlock);
1463
1464 // Emit the increment of the loop counter.
1465 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1466 Counter = Builder.CreateLoad(IndexPtr);
1467 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1468 Builder.CreateStore(NextVal, IndexPtr, false);
1469
1470 // Finally, branch back up to the condition for the next iteration.
1471 EmitBranch(CondBlock);
1472
1473 // Emit the fall-through block.
1474 EmitBlock(AfterFor, true);
1475}
1476
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001477/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1478/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001479/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001480void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001481 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001482 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001483 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1484 if (ClassDecl) {
1485 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1486 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1487 }
1488 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1489 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001490 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001491 }
1492
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001493 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001494 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001495 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1496 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001497 CallArgList CallArgs;
1498 // Push the this (Dest) ptr.
1499 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1500 BaseCopyCtor->getThisType(getContext())));
1501
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001502 // Push the Src ptr.
1503 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001504 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001505 QualType ResultType =
1506 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1507 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1508 Callee, CallArgs, BaseCopyCtor);
1509 }
1510}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001511
Fariborz Jahanian04500242009-08-12 23:34:46 +00001512/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1513/// object from SrcValue to DestValue. Assignment can be either a bitwise
1514/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001515// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001516void CodeGenFunction::EmitClassCopyAssignment(
1517 llvm::Value *Dest, llvm::Value *Src,
1518 const CXXRecordDecl *ClassDecl,
1519 const CXXRecordDecl *BaseClassDecl,
1520 QualType Ty) {
1521 if (ClassDecl) {
1522 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1523 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1524 }
1525 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1526 EmitAggregateCopy(Dest, Src, Ty);
1527 return;
1528 }
1529
1530 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001531 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1532 MD);
1533 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1534 (void)ConstCopyAssignOp;
1535
1536 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1537 const llvm::Type *LTy =
1538 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1539 FPT->isVariadic());
1540 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001541
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001542 CallArgList CallArgs;
1543 // Push the this (Dest) ptr.
1544 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1545 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001546
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001547 // Push the Src ptr.
1548 CallArgs.push_back(std::make_pair(RValue::get(Src),
1549 MD->getParamDecl(0)->getType()));
1550 QualType ResultType =
1551 MD->getType()->getAsFunctionType()->getResultType();
1552 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1553 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001554}
1555
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001556/// SynthesizeDefaultConstructor - synthesize a default constructor
1557void
1558CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1559 const FunctionDecl *FD,
1560 llvm::Function *Fn,
1561 const FunctionArgList &Args) {
1562 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1563 EmitCtorPrologue(CD);
1564 FinishFunction();
1565}
1566
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001567/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001568/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1569/// The implicitly-defined copy constructor for class X performs a memberwise
1570/// copy of its subobjects. The order of copying is the same as the order
1571/// of initialization of bases and members in a user-defined constructor
1572/// Each subobject is copied in the manner appropriate to its type:
1573/// if the subobject is of class type, the copy constructor for the class is
1574/// used;
1575/// if the subobject is an array, each element is copied, in the manner
1576/// appropriate to the element type;
1577/// if the subobject is of scalar type, the built-in assignment operator is
1578/// used.
1579/// Virtual base class subobjects shall be copied only once by the
1580/// implicitly-defined copy constructor
1581
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001582void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1583 const FunctionDecl *FD,
1584 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001585 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001586 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1587 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001588 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1589 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001590
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001591 FunctionArgList::const_iterator i = Args.begin();
1592 const VarDecl *ThisArg = i->first;
1593 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1594 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1595 const VarDecl *SrcArg = (i+1)->first;
1596 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1597 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1598
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001599 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1600 Base != ClassDecl->bases_end(); ++Base) {
1601 // FIXME. copy constrution of virtual base NYI
1602 if (Base->isVirtual())
1603 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001604
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001605 CXXRecordDecl *BaseClassDecl
1606 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001607 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1608 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001609 }
1610
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001611 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1612 FieldEnd = ClassDecl->field_end();
1613 Field != FieldEnd; ++Field) {
1614 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001615 const ConstantArrayType *Array =
1616 getContext().getAsConstantArrayType(FieldType);
1617 if (Array)
1618 FieldType = getContext().getBaseElementType(FieldType);
1619
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001620 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1621 CXXRecordDecl *FieldClassDecl
1622 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1623 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1624 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001625 if (Array) {
1626 const llvm::Type *BasePtr = ConvertType(FieldType);
1627 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1628 llvm::Value *DestBaseAddrPtr =
1629 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1630 llvm::Value *SrcBaseAddrPtr =
1631 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1632 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1633 FieldClassDecl, FieldType);
1634 }
1635 else
1636 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1637 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001638 continue;
1639 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001640 // Do a built-in assignment of scalar data members.
1641 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1642 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1643 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1644 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001645 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001646 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001647}
1648
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001649/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1650/// Before the implicitly-declared copy assignment operator for a class is
1651/// implicitly defined, all implicitly- declared copy assignment operators for
1652/// its direct base classes and its nonstatic data members shall have been
1653/// implicitly defined. [12.8-p12]
1654/// The implicitly-defined copy assignment operator for class X performs
1655/// memberwise assignment of its subob- jects. The direct base classes of X are
1656/// assigned first, in the order of their declaration in
1657/// the base-specifier-list, and then the immediate nonstatic data members of X
1658/// are assigned, in the order in which they were declared in the class
1659/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001660/// if the subobject is of class type, the copy assignment operator for the
1661/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001662/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001663///
1664/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001665/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001666///
1667/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001668/// used.
1669void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1670 const FunctionDecl *FD,
1671 llvm::Function *Fn,
1672 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001673
1674 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1675 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1676 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001677 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1678
Fariborz Jahanian04500242009-08-12 23:34:46 +00001679 FunctionArgList::const_iterator i = Args.begin();
1680 const VarDecl *ThisArg = i->first;
1681 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1682 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1683 const VarDecl *SrcArg = (i+1)->first;
1684 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1685 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1686
1687 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1688 Base != ClassDecl->bases_end(); ++Base) {
1689 // FIXME. copy assignment of virtual base NYI
1690 if (Base->isVirtual())
1691 continue;
1692
1693 CXXRecordDecl *BaseClassDecl
1694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1695 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1696 Base->getType());
1697 }
1698
1699 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1700 FieldEnd = ClassDecl->field_end();
1701 Field != FieldEnd; ++Field) {
1702 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001703 const ConstantArrayType *Array =
1704 getContext().getAsConstantArrayType(FieldType);
1705 if (Array)
1706 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001707
1708 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1709 CXXRecordDecl *FieldClassDecl
1710 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1711 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1712 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001713 if (Array) {
1714 const llvm::Type *BasePtr = ConvertType(FieldType);
1715 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1716 llvm::Value *DestBaseAddrPtr =
1717 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1718 llvm::Value *SrcBaseAddrPtr =
1719 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1720 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1721 FieldClassDecl, FieldType);
1722 }
1723 else
1724 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1725 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001726 continue;
1727 }
1728 // Do a built-in assignment of scalar data members.
1729 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1730 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1731 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1732 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001733 }
1734
1735 // return *this;
1736 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001737
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001738 FinishFunction();
1739}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001740
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001741/// EmitCtorPrologue - This routine generates necessary code to initialize
1742/// base classes and non-static data members belonging to this constructor.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001743/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001744void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001745 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001746 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001747 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001748
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001749 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001750 E = CD->init_end();
1751 B != E; ++B) {
1752 CXXBaseOrMemberInitializer *Member = (*B);
1753 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001754 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001755 Type *BaseType = Member->getBaseClass();
1756 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001757 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001758 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1759 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001760 EmitCXXConstructorCall(Member->getConstructor(),
1761 Ctor_Complete, V,
1762 Member->const_arg_begin(),
1763 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001764 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001765 // non-static data member initilaizers.
1766 FieldDecl *Field = Member->getMember();
1767 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001768 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001769 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001770 if (Array)
1771 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001772
Mike Stump7e8c9932009-07-31 18:25:34 +00001773 LoadOfThis = LoadCXXThis();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001774 LValue LHS;
1775 if (FieldType->isReferenceType()) {
1776 // FIXME: This is really ugly; should be refactored somehow
1777 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1778 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1779 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1780 QualType::GCNone, FieldType.getAddressSpace());
1781 } else {
1782 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1783 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001784 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001785 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001786 assert(Member->getConstructor() &&
1787 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001788 if (Array) {
1789 const llvm::Type *BasePtr = ConvertType(FieldType);
1790 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1791 llvm::Value *BaseAddrPtr =
1792 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1793 EmitCXXAggrConstructorCall(Member->getConstructor(),
1794 Array, BaseAddrPtr);
1795 }
1796 else
1797 EmitCXXConstructorCall(Member->getConstructor(),
1798 Ctor_Complete, LHS.getAddress(),
1799 Member->const_arg_begin(),
1800 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001801 continue;
1802 }
1803 else {
1804 // Initializing an anonymous union data member.
1805 FieldDecl *anonMember = Member->getAnonUnionMember();
Anders Carlsson9e00ce72009-09-02 21:14:47 +00001806 LHS = EmitLValueForField(LHS.getAddress(), anonMember,
1807 /*IsUnion=*/true, 0);
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001808 FieldType = anonMember->getType();
1809 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001810 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001811
1812 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001813 Expr *RhsExpr = *Member->arg_begin();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001814 RValue RHS;
1815 if (FieldType->isReferenceType())
1816 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1817 /*IsInitializer=*/true);
1818 else
1819 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1820 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001821 }
1822 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001823
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001824 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001825 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001826 // have bases classes and/or contain non-static data members which require
1827 // construction.
1828 for (CXXRecordDecl::base_class_const_iterator Base =
1829 ClassDecl->bases_begin();
1830 Base != ClassDecl->bases_end(); ++Base) {
1831 // FIXME. copy assignment of virtual base NYI
1832 if (Base->isVirtual())
1833 continue;
1834
1835 CXXRecordDecl *BaseClassDecl
1836 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1837 if (BaseClassDecl->hasTrivialConstructor())
1838 continue;
1839 if (CXXConstructorDecl *BaseCX =
1840 BaseClassDecl->getDefaultConstructor(getContext())) {
1841 LoadOfThis = LoadCXXThis();
1842 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1843 BaseClassDecl);
1844 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1845 }
1846 }
1847
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001848 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1849 FieldEnd = ClassDecl->field_end();
1850 Field != FieldEnd; ++Field) {
1851 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001852 const ConstantArrayType *Array =
1853 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001854 if (Array)
1855 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001856 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1857 continue;
1858 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001859 CXXRecordDecl *MemberClassDecl =
1860 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1861 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1862 continue;
1863 if (CXXConstructorDecl *MamberCX =
1864 MemberClassDecl->getDefaultConstructor(getContext())) {
1865 LoadOfThis = LoadCXXThis();
1866 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001867 if (Array) {
1868 const llvm::Type *BasePtr = ConvertType(FieldType);
1869 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1870 llvm::Value *BaseAddrPtr =
1871 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1872 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1873 }
1874 else
1875 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1876 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001877 }
1878 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001879 }
1880
Mike Stump7e8c9932009-07-31 18:25:34 +00001881 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001882 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001883 if (!LoadOfThis)
1884 LoadOfThis = LoadCXXThis();
1885 llvm::Value *VtableField;
1886 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001887 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001888 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1889 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1890 llvm::Value *vtable = GenerateVtable(ClassDecl);
1891 Builder.CreateStore(vtable, VtableField);
1892 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001893}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001894
1895/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1896/// destructor. This is to call destructors on members and base classes
1897/// in reverse order of their construction.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001898/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001899void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1900 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
Anders Carlssona82465d2009-09-01 21:12:16 +00001901 assert(!ClassDecl->getNumVBases() &&
1902 "FIXME: Destruction of virtual bases not supported");
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001903 (void)ClassDecl; // prevent warning.
1904
1905 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1906 *E = DD->destr_end(); B != E; ++B) {
1907 uintptr_t BaseOrMember = (*B);
1908 if (DD->isMemberToDestroy(BaseOrMember)) {
1909 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1910 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001911 const ConstantArrayType *Array =
1912 getContext().getAsConstantArrayType(FieldType);
1913 if (Array)
1914 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001915 const RecordType *RT = FieldType->getAs<RecordType>();
1916 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1917 if (FieldClassDecl->hasTrivialDestructor())
1918 continue;
1919 llvm::Value *LoadOfThis = LoadCXXThis();
1920 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001921 if (Array) {
1922 const llvm::Type *BasePtr = ConvertType(FieldType);
1923 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1924 llvm::Value *BaseAddrPtr =
1925 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1926 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1927 Array, BaseAddrPtr);
1928 }
1929 else
1930 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1931 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001932 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001933 const RecordType *RT =
1934 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1935 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1936 if (BaseClassDecl->hasTrivialDestructor())
1937 continue;
1938 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1939 ClassDecl,BaseClassDecl);
1940 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1941 Dtor_Complete, V);
1942 }
1943 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001944 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1945 return;
1946 // Case of destructor synthesis with fields and base classes
1947 // which have non-trivial destructors. They must be destructed in
1948 // reverse order of their construction.
1949 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1950
1951 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1952 FieldEnd = ClassDecl->field_end();
1953 Field != FieldEnd; ++Field) {
1954 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001955 if (getContext().getAsConstantArrayType(FieldType))
1956 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001957 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1958 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1959 if (FieldClassDecl->hasTrivialDestructor())
1960 continue;
1961 DestructedFields.push_back(*Field);
1962 }
1963 }
1964 if (!DestructedFields.empty())
1965 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1966 FieldDecl *Field = DestructedFields[i];
1967 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001968 const ConstantArrayType *Array =
1969 getContext().getAsConstantArrayType(FieldType);
1970 if (Array)
1971 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001972 const RecordType *RT = FieldType->getAs<RecordType>();
1973 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1974 llvm::Value *LoadOfThis = LoadCXXThis();
1975 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001976 if (Array) {
1977 const llvm::Type *BasePtr = ConvertType(FieldType);
1978 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1979 llvm::Value *BaseAddrPtr =
1980 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1981 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1982 Array, BaseAddrPtr);
1983 }
1984 else
1985 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1986 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001987 }
1988
1989 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1990 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1991 Base != ClassDecl->bases_end(); ++Base) {
1992 // FIXME. copy assignment of virtual base NYI
1993 if (Base->isVirtual())
1994 continue;
1995
1996 CXXRecordDecl *BaseClassDecl
1997 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1998 if (BaseClassDecl->hasTrivialDestructor())
1999 continue;
2000 DestructedBases.push_back(BaseClassDecl);
2001 }
2002 if (DestructedBases.empty())
2003 return;
2004 for (int i = DestructedBases.size() -1; i >= 0; --i) {
2005 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
2006 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
2007 ClassDecl,BaseClassDecl);
2008 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
2009 Dtor_Complete, V);
2010 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00002011}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002012
2013void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
2014 const FunctionDecl *FD,
2015 llvm::Function *Fn,
2016 const FunctionArgList &Args) {
2017
2018 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
2019 assert(!ClassDecl->hasUserDeclaredDestructor() &&
2020 "SynthesizeDefaultDestructor - destructor has user declaration");
2021 (void) ClassDecl;
2022
2023 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
2024 EmitDtorEpilogue(CD);
2025 FinishFunction();
2026}