blob: d71597fd93bfd7ce5b59924b341edab2cf2fe6e1 [file] [log] [blame]
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson33e65e52009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniana0107de2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson7a9b2982009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson4715ebb2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbardea59212009-02-25 19:24:29 +000028void
Anders Carlssonf2a022a2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonf2a022a2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf2a022a2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlssonf49ffa92009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf2a022a2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlssoncde4a862009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlssoncde4a862009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer3c1fe262009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlssoncde4a862009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbardea59212009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000136
Anders Carlsson33e65e52009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar0433a022009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar72f96552008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000203 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000204 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
205 FPT->isVariadic());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000206 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000208 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000209 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000210 else {
211 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213 }
Mike Stumpf7d47a52009-08-26 20:46:33 +0000214
Douglas Gregore399ad42009-08-26 22:36:53 +0000215 // C++ [class.virtual]p12:
216 // Explicit qualification with the scope operator (5.1) suppresses the
217 // virtual call mechanism.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000218 llvm::Value *Callee;
Douglas Gregorefccbec2009-08-31 21:41:48 +0000219 if (MD->isVirtual() && !ME->hasQualifier())
Mike Stumpf7d47a52009-08-26 20:46:33 +0000220 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregorefccbec2009-08-31 21:41:48 +0000221 else
Mike Stumpf7d47a52009-08-26 20:46:33 +0000222 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000224 return EmitCXXMemberCall(MD, Callee, This,
225 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000226}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000227
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000228RValue
229CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
230 const CXXMethodDecl *MD) {
231 assert(MD->isInstance() &&
232 "Trying to emit a member call expr on a static method!");
233
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000234 if (MD->isCopyAssignment()) {
235 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
236 if (ClassDecl->hasTrivialCopyAssignment()) {
237 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
238 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
239 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
240 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
241 QualType Ty = E->getType();
242 EmitAggregateCopy(This, Src, Ty);
243 return RValue::get(This);
244 }
245 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000246
247 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
248 const llvm::Type *Ty =
249 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
250 FPT->isVariadic());
251 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
252
253 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
254
255 return EmitCXXMemberCall(MD, Callee, This,
256 E->arg_begin() + 1, E->arg_end());
257}
258
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000259RValue
260CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
261 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
262 "EmitCXXFunctionalCastExpr - called with wrong cast");
263
264 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000265 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
266 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
267 " method decl");
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000268 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000269
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000270 const llvm::Type *Ty =
271 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
272 FPT->isVariadic());
273 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
274 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
275 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
276 if (RV.isAggregate())
277 RV = RValue::get(RV.getAggregateAddr());
278 return RV;
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000279}
280
Anders Carlsson49d4a572009-04-14 16:58:56 +0000281llvm::Value *CodeGenFunction::LoadCXXThis() {
282 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
283 "Must be in a C++ member function decl to load 'this'");
284 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
285 "Must be in a C++ member function decl to load 'this'");
286
287 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000288 // ans: See how CodeGenFunction::LoadObjCSelf() uses
289 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000290 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
291}
Anders Carlsson652951a2009-04-15 15:55:24 +0000292
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000293static bool
294GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
295 const CXXRecordDecl *ClassDecl,
296 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000297 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
298 e = ClassDecl->bases_end(); i != e; ++i) {
299 if (i->isVirtual())
300 continue;
301 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000302 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000303 if (Base == BaseClassDecl) {
304 NestedBasePaths.push_back(BaseClassDecl);
305 return true;
306 }
307 }
308 // BaseClassDecl not an immediate base of ClassDecl.
309 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
310 e = ClassDecl->bases_end(); i != e; ++i) {
311 if (i->isVirtual())
312 continue;
313 const CXXRecordDecl *Base =
314 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
315 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
316 NestedBasePaths.push_back(Base);
317 return true;
318 }
319 }
320 return false;
321}
322
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000323llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000324 const CXXRecordDecl *ClassDecl,
325 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000326 if (ClassDecl == BaseClassDecl)
327 return BaseValue;
328
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000329 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000330 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
331 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
332 assert(NestedBasePaths.size() > 0 &&
333 "AddressCXXOfBaseClass - inheritence path failed");
334 NestedBasePaths.push_back(ClassDecl);
335 uint64_t Offset = 0;
336
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000337 // Accessing a member of the base class. Must add delata to
338 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000339 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
340 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
341 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
342 const ASTRecordLayout &Layout =
343 getContext().getASTRecordLayout(DerivedClass);
344 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
345 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000346 llvm::Value *OffsetVal =
347 llvm::ConstantInt::get(
348 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000349 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
350 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
351 QualType BTy =
352 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000353 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000354 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000355 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000356 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
357 return BaseValue;
358}
359
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000360/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
361/// for-loop to call the default constructor on individual members of the
362/// array. 'Array' is the array type, 'This' is llvm pointer of the start
363/// of the array and 'D' is the default costructor Decl for elements of the
364/// array. It is assumed that all relevant checks have been made by the
365/// caller.
366void
367CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
368 const ArrayType *Array,
369 llvm::Value *This) {
370 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
371 assert(CA && "Do we support VLA for construction ?");
372
373 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000374 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000375 "loop.index");
376 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000377 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000378 Builder.CreateStore(zeroConstant, IndexPtr, false);
379
380 // Start the loop with a block that tests the condition.
381 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
382 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
383
384 EmitBlock(CondBlock);
385
386 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
387
388 // Generate: if (loop-index < number-of-elements fall to the loop body,
389 // otherwise, go to the block after the for-loop.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000390 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000391 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000392 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000393 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
394 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
395 "isless");
396 // If the condition is true, execute the body.
397 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
398
399 EmitBlock(ForBody);
400
401 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000402 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000403 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000404 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
405 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000406
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000407 EmitBlock(ContinueBlock);
408
409 // Emit the increment of the loop counter.
410 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
411 Counter = Builder.CreateLoad(IndexPtr);
412 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
413 Builder.CreateStore(NextVal, IndexPtr, false);
414
415 // Finally, branch back up to the condition for the next iteration.
416 EmitBranch(CondBlock);
417
418 // Emit the fall-through block.
419 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000420}
421
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000422/// EmitCXXAggrDestructorCall - calls the default destructor on array
423/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000424void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000425CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
426 const ArrayType *Array,
427 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000428 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
429 assert(CA && "Do we support VLA for destruction ?");
430 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
431 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000432 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000433 // Create a temporary for the loop index and initialize it with count of
434 // array elements.
435 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
436 "loop.index");
437 // Index = ElementCount;
438 llvm::Value* UpperCount =
439 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
440 Builder.CreateStore(UpperCount, IndexPtr, false);
441
442 // Start the loop with a block that tests the condition.
443 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
444 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
445
446 EmitBlock(CondBlock);
447
448 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
449
450 // Generate: if (loop-index != 0 fall to the loop body,
451 // otherwise, go to the block after the for-loop.
452 llvm::Value* zeroConstant =
453 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
454 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
455 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
456 "isne");
457 // If the condition is true, execute the body.
458 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
459
460 EmitBlock(ForBody);
461
462 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
463 // Inside the loop body, emit the constructor call on the array element.
464 Counter = Builder.CreateLoad(IndexPtr);
465 Counter = Builder.CreateSub(Counter, One);
466 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
467 EmitCXXDestructorCall(D, Dtor_Complete, Address);
468
469 EmitBlock(ContinueBlock);
470
471 // Emit the decrement of the loop counter.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One, "dec");
474 Builder.CreateStore(Counter, IndexPtr, false);
475
476 // Finally, branch back up to the condition for the next iteration.
477 EmitBranch(CondBlock);
478
479 // Emit the fall-through block.
480 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000481}
482
483void
Anders Carlsson72f48292009-04-17 00:06:03 +0000484CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
485 CXXCtorType Type,
486 llvm::Value *This,
487 CallExpr::const_arg_iterator ArgBeg,
488 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000489 if (D->isCopyConstructor(getContext())) {
490 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
491 if (ClassDecl->hasTrivialCopyConstructor()) {
492 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
493 "EmitCXXConstructorCall - user declared copy constructor");
494 const Expr *E = (*ArgBeg);
495 QualType Ty = E->getType();
496 llvm::Value *Src = EmitLValue(E).getAddress();
497 EmitAggregateCopy(This, Src, Ty);
498 return;
499 }
500 }
501
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000502 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
503
504 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000505}
506
Anders Carlssond3f6b162009-05-29 21:03:38 +0000507void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
508 CXXDtorType Type,
509 llvm::Value *This) {
510 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, 0, 0);
513}
514
Anders Carlsson72f48292009-04-17 00:06:03 +0000515void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000516CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
517 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000518 assert(Dest && "Must have a destination!");
519
520 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000521 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000522 if (RD->hasTrivialConstructor())
523 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000524
525 // Code gen optimization to eliminate copy constructor and return
526 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000527 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000528 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000529 EmitAggExpr((*i), Dest, false);
530 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000531 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000532 // Call the constructor.
533 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
534 E->arg_begin(), E->arg_end());
535}
536
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000537llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000538 if (E->isArray()) {
539 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000540 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000541 }
542
543 QualType AllocType = E->getAllocatedType();
544 FunctionDecl *NewFD = E->getOperatorNew();
545 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
546
547 CallArgList NewArgs;
548
549 // The allocation size is the first argument.
550 QualType SizeTy = getContext().getSizeType();
551 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000552 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000553 getContext().getTypeSize(AllocType) / 8);
554
555 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
556
557 // Emit the rest of the arguments.
558 // FIXME: Ideally, this should just use EmitCallArgs.
559 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
560
561 // First, use the types from the function type.
562 // We start at 1 here because the first argument (the allocation size)
563 // has already been emitted.
564 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
565 QualType ArgType = NewFTy->getArgType(i);
566
567 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
568 getTypePtr() ==
569 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
570 "type mismatch in call argument!");
571
572 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
573 ArgType));
574
575 }
576
577 // Either we've emitted all the call args, or we have a call to a
578 // variadic function.
579 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
580 "Extra arguments in non-variadic function!");
581
582 // If we still have any arguments, emit them using the type of the argument.
583 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
584 NewArg != NewArgEnd; ++NewArg) {
585 QualType ArgType = NewArg->getType();
586 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
587 ArgType));
588 }
589
590 // Emit the call to new.
591 RValue RV =
592 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
593 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
594 NewArgs, NewFD);
595
Anders Carlsson11269042009-05-31 21:53:59 +0000596 // If an allocation function is declared with an empty exception specification
597 // it returns null to indicate failure to allocate storage. [expr.new]p13.
598 // (We don't need to check for null when there's no new initializer and
599 // we're allocating a POD type).
600 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
601 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000602
Anders Carlssondbee9a52009-06-01 00:05:16 +0000603 llvm::BasicBlock *NewNull = 0;
604 llvm::BasicBlock *NewNotNull = 0;
605 llvm::BasicBlock *NewEnd = 0;
606
607 llvm::Value *NewPtr = RV.getScalarVal();
608
Anders Carlsson11269042009-05-31 21:53:59 +0000609 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000610 NewNull = createBasicBlock("new.null");
611 NewNotNull = createBasicBlock("new.notnull");
612 NewEnd = createBasicBlock("new.end");
613
614 llvm::Value *IsNull =
615 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000616 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000617 "isnull");
618
619 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
620 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000621 }
622
Anders Carlssondbee9a52009-06-01 00:05:16 +0000623 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000624
Anders Carlsson7c294782009-05-31 20:56:36 +0000625 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000626 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000627 assert(E->getNumConstructorArgs() == 1 &&
628 "Can only have one argument to initializer of POD type.");
629
630 const Expr *Init = E->getConstructorArg(0);
631
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000632 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000633 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000634 else if (AllocType->isAnyComplexType())
635 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000636 else
637 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000638 }
Anders Carlsson11269042009-05-31 21:53:59 +0000639 } else {
640 // Call the constructor.
641 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000642
Anders Carlsson11269042009-05-31 21:53:59 +0000643 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
644 E->constructor_arg_begin(),
645 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000646 }
Anders Carlsson11269042009-05-31 21:53:59 +0000647
Anders Carlssondbee9a52009-06-01 00:05:16 +0000648 if (NullCheckResult) {
649 Builder.CreateBr(NewEnd);
650 EmitBlock(NewNull);
651 Builder.CreateBr(NewEnd);
652 EmitBlock(NewEnd);
653
654 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
655 PHI->reserveOperandSpace(2);
656 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000657 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000658
659 NewPtr = PHI;
660 }
661
Anders Carlsson11269042009-05-31 21:53:59 +0000662 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000663}
664
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000665void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
666 if (E->isArrayForm()) {
667 ErrorUnsupported(E, "delete[] expression");
668 return;
669 };
670
671 QualType DeleteTy =
672 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
673
674 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
675
676 // Null check the pointer.
677 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
678 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
679
680 llvm::Value *IsNull =
681 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
682 "isnull");
683
684 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
685 EmitBlock(DeleteNotNull);
686
687 // Call the destructor if necessary.
688 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
689 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
690 if (!RD->hasTrivialDestructor()) {
691 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
692 if (Dtor->isVirtual()) {
693 ErrorUnsupported(E, "delete expression with virtual destructor");
694 return;
695 }
696
697 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
698 }
699 }
700 }
701
702 // Call delete.
703 FunctionDecl *DeleteFD = E->getOperatorDelete();
704 const FunctionProtoType *DeleteFTy =
705 DeleteFD->getType()->getAsFunctionProtoType();
706
707 CallArgList DeleteArgs;
708
709 QualType ArgTy = DeleteFTy->getArgType(0);
710 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
711 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
712
713 // Emit the call to delete.
714 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
715 DeleteArgs),
716 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
717 DeleteArgs, DeleteFD);
718
719 EmitBlock(DeleteEnd);
720}
721
Anders Carlsson652951a2009-04-15 15:55:24 +0000722void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson1764af42009-05-05 04:44:02 +0000723 EmitGlobal(GlobalDecl(D, Ctor_Complete));
724 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000725}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000726
Anders Carlsson4811c302009-04-17 01:58:57 +0000727void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
728 CXXCtorType Type) {
729
730 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
731
732 CodeGenFunction(*this).GenerateCode(D, Fn);
733
734 SetFunctionDefinitionAttributes(D, Fn);
735 SetLLVMFunctionAttributesForDefinition(D, Fn);
736}
737
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000738llvm::Function *
739CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
740 CXXCtorType Type) {
741 const llvm::FunctionType *FTy =
742 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
743
744 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000745 return cast<llvm::Function>(
746 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000747}
Anders Carlsson4811c302009-04-17 01:58:57 +0000748
749const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
750 CXXCtorType Type) {
751 llvm::SmallString<256> Name;
752 llvm::raw_svector_ostream Out(Name);
753 mangleCXXCtor(D, Type, Context, Out);
754
755 Name += '\0';
756 return UniqueMangledName(Name.begin(), Name.end());
757}
758
759void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000760 EmitCXXDestructor(D, Dtor_Complete);
761 EmitCXXDestructor(D, Dtor_Base);
762}
763
764void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
765 CXXDtorType Type) {
766 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
767
768 CodeGenFunction(*this).GenerateCode(D, Fn);
769
770 SetFunctionDefinitionAttributes(D, Fn);
771 SetLLVMFunctionAttributesForDefinition(D, Fn);
772}
773
774llvm::Function *
775CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
776 CXXDtorType Type) {
777 const llvm::FunctionType *FTy =
778 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
779
780 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000781 return cast<llvm::Function>(
782 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000783}
784
785const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
786 CXXDtorType Type) {
787 llvm::SmallString<256> Name;
788 llvm::raw_svector_ostream Out(Name);
789 mangleCXXDtor(D, Type, Context, Out);
790
791 Name += '\0';
792 return UniqueMangledName(Name.begin(), Name.end());
793}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000794
Mike Stumpdca5e512009-08-18 21:49:00 +0000795llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000796 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000797 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000798 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000799
800 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000801 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000802
803 llvm::SmallString<256> OutName;
804 llvm::raw_svector_ostream Out(OutName);
805 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000806 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000807 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000808 llvm::GlobalVariable::LinkageTypes linktype;
809 linktype = llvm::GlobalValue::WeakAnyLinkage;
810 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000811 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000812 // FIXME: descriptor
813 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000814 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000815 // FIXME: TS
816 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
817
818 llvm::Constant *C;
819 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
820 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000821 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000822 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000823 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
824 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000825}
826
Mike Stump86a859e2009-08-19 18:10:47 +0000827class VtableBuilder {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000828public:
829 /// Index_t - Vtable index type.
830 typedef uint64_t Index_t;
831private:
Mike Stumpad734d12009-08-18 20:50:28 +0000832 std::vector<llvm::Constant *> &methods;
Mike Stumpf3245642009-08-28 23:22:54 +0000833 std::vector<llvm::Constant *> submethods;
Mike Stumpad734d12009-08-18 20:50:28 +0000834 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000835 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000836 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000837 /// BLayout - Layout for the most derived class that this vtable is being
838 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000839 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000840 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000841 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000842 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000843 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000844 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000845 /// Index - Maps a method decl into a vtable index. Useful for virtual
846 /// dispatch codegen.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000847 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpf3245642009-08-28 23:22:54 +0000848 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
849 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCallOffset;
850 std::vector<Index_t> VCalls;
Mike Stumpd75d3232009-08-18 22:04:08 +0000851 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000852public:
Mike Stump86a859e2009-08-19 18:10:47 +0000853 VtableBuilder(std::vector<llvm::Constant *> &meth,
854 const CXXRecordDecl *c,
855 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000856 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
857 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
858 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000859 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
860 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000861
Mike Stumpf7d47a52009-08-26 20:46:33 +0000862 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000863
Mike Stumpf3245642009-08-28 23:22:54 +0000864 llvm::Constant *wrap(Index_t i) {
865 llvm::Constant *m;
866 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
867 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000868 }
869
Mike Stumpf3245642009-08-28 23:22:54 +0000870 llvm::Constant *wrap(llvm::Constant *m) {
871 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
Mike Stump23b238e2009-08-12 23:25:18 +0000872 }
Mike Stumpf640de52009-08-12 23:14:12 +0000873
Mike Stump2b9ba612009-08-20 02:11:48 +0000874 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000875 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000876 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
877 e = RD->bases_end(); i != e; ++i) {
878 const CXXRecordDecl *Base =
879 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
880 if (i->isVirtual() && !SeenVBase.count(Base)) {
881 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000882 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stumpf3245642009-08-28 23:22:54 +0000883 llvm::Constant *m = wrap(BaseOffset);
884 m = wrap((0?700:0) + BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000885 offsets.push_back(m);
886 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000887 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000888 }
889 }
890
Mike Stumpf07ede52009-08-21 01:45:00 +0000891 void StartNewTable() {
892 SeenVBase.clear();
893 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000894
Mike Stumpf3245642009-08-28 23:22:54 +0000895 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint,
896 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000897 typedef CXXMethodDecl::method_iterator meth_iter;
898
899 llvm::Constant *m;
Mike Stumpf3245642009-08-28 23:22:54 +0000900 m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stumpf07ede52009-08-21 01:45:00 +0000901
902 // FIXME: Don't like the nested loops. For very large inheritance
903 // heirarchies we could have a table on the side with the final overridder
904 // and just replace each instance of an overridden method once. Would be
905 // nice to measure the cost/benefit on real code.
906
907 // If we can find a previously allocated slot for this, reuse it.
908 for (meth_iter mi = MD->begin_overridden_methods(),
909 e = MD->end_overridden_methods();
910 mi != e; ++mi) {
911 const CXXMethodDecl *OMD = *mi;
912 llvm::Constant *om;
913 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
914 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
915
Mike Stumpf3245642009-08-28 23:22:54 +0000916 for (Index_t i = 0, e = submethods.size();
Mike Stumpf7d47a52009-08-26 20:46:33 +0000917 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000918 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stumpf3245642009-08-28 23:22:54 +0000919 if (submethods[i] == om) {
920 // FIXME: thunks
921 submethods[i] = m;
922 Index[MD] = i;
923 if (MorallyVirtual) {
924 VCallOffset[MD] = Offset/8;
925 VCalls[VCall[OMD]] = Offset/8 - VCallOffset[OMD];
926 }
927 // submethods[VCall[OMD]] = wrap(Offset/8 - VCallOffset[OMD]);
Mike Stumpf07ede52009-08-21 01:45:00 +0000928 return;
929 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000930 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000931 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000932
933 // else allocate a new slot.
Mike Stumpf3245642009-08-28 23:22:54 +0000934 Index[MD] = submethods.size();
935 // VCall[MD] = Offset;
936 if (MorallyVirtual) {
937 VCallOffset[MD] = Offset/8;
938 Index_t &idx = VCall[MD];
939 // Allocate the first one, after that, we reuse the previous one.
940 if (idx == 0) {
941 idx = VCalls.size()+1;
942 VCallOffset[MD] = Offset/8;
943 VCalls.push_back(0);
944 }
945 }
946 submethods.push_back(m);
Mike Stumpf07ede52009-08-21 01:45:00 +0000947 }
948
Mike Stumpf3245642009-08-28 23:22:54 +0000949 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
950 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000951 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
952 ++mi)
953 if (mi->isVirtual())
Mike Stumpf3245642009-08-28 23:22:54 +0000954 AddMethod(*mi, AddressPoint, MorallyVirtual, Offset);
Mike Stumpdecd7812009-08-12 23:00:59 +0000955 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000956
Mike Stump00962322009-08-21 23:09:30 +0000957 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stumpf3245642009-08-28 23:22:54 +0000958 bool forPrimary, bool Bottom,
959 bool MorallyVirtual,
Mike Stump00962322009-08-21 23:09:30 +0000960 int64_t Offset,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000961 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000962 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000963 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +0000964
Mike Stump7bae1282009-08-18 21:30:21 +0000965 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +0000966 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +0000967
968 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
969 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
970 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
971
Mike Stumpf3245642009-08-28 23:22:54 +0000972 std::vector<llvm::Constant *> offsets;
Mike Stump7bae1282009-08-18 21:30:21 +0000973 // FIXME: Audit, is this right?
Mike Stumpf3245642009-08-28 23:22:54 +0000974 if (Bottom && (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual
975 || Bottom))
Mike Stumpaf0d0452009-08-20 07:22:17 +0000976 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000977
Mike Stump7bae1282009-08-18 21:30:21 +0000978 bool Top = true;
979
980 // vtables are composed from the chain of primaries.
981 if (PrimaryBase) {
982 if (PrimaryBaseWasVirtual)
983 IndirectPrimary.insert(PrimaryBase);
984 Top = false;
Mike Stumpf3245642009-08-28 23:22:54 +0000985 AddressPoint = GenerateVtableForBase(PrimaryBase, true, false,
986 PrimaryBaseWasVirtual|MorallyVirtual,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000987 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +0000988 }
989
Mike Stumpf3245642009-08-28 23:22:54 +0000990 // And add the virtuals for the class to the primary vtable.
991 GenerateMethods(RD, AddressPoint, MorallyVirtual, Offset);
992
993 if (!Bottom)
994 return AddressPoint;
995
996 StartNewTable();
997 // FIXME: Cleanup.
998 if (!ForVirtualBase) {
999 // then virtual base offsets...
1000 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1001 e = offsets.rend(); i != e; ++i)
1002 methods.push_back(*i);
Mike Stumpc57b8272009-08-16 01:46:26 +00001003 }
Mike Stump2eade572009-08-13 22:53:07 +00001004
Mike Stumpf3245642009-08-28 23:22:54 +00001005 // The vcalls come first...
1006 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1007 i < e; ++i)
1008 methods.push_back(wrap((0?600:0) + *i));
1009 VCalls.clear();
1010
1011 if (ForVirtualBase) {
1012 // then virtual base offsets...
1013 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1014 e = offsets.rend(); i != e; ++i)
1015 methods.push_back(*i);
1016 }
1017
1018 int64_t BaseOffset;
1019 if (ForVirtualBase) {
1020 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1021 // FIXME: The above is redundant with the other case.
1022 assert(BaseOffset == -Offset/8);
1023 } else
1024 BaseOffset = -Offset/8;
1025 m = wrap(BaseOffset);
1026 methods.push_back(m);
1027 methods.push_back(rtti);
1028 AddressPoint = methods.size();
1029
1030 methods.insert(methods.end(), submethods.begin(), submethods.end());
1031 submethods.clear();
Mike Stump7bae1282009-08-18 21:30:21 +00001032
1033 // and then the non-virtual bases.
1034 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1035 e = RD->bases_end(); i != e; ++i) {
1036 if (i->isVirtual())
1037 continue;
1038 const CXXRecordDecl *Base =
1039 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1040 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1041 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001042 StartNewTable();
Mike Stumpf3245642009-08-28 23:22:54 +00001043 GenerateVtableForBase(Base, true, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001044 }
1045 }
Mike Stump00962322009-08-21 23:09:30 +00001046 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001047 }
1048
1049 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001050 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001051 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1052 e = RD->bases_end(); i != e; ++i) {
1053 const CXXRecordDecl *Base =
1054 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1055 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1056 // Mark it so we don't output it twice.
1057 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001058 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001059 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf3245642009-08-28 23:22:54 +00001060 GenerateVtableForBase(Base, false, true, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001061 }
1062 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001063 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001064 }
1065 }
Mike Stump7bae1282009-08-18 21:30:21 +00001066};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001067
Mike Stumpf7d47a52009-08-26 20:46:33 +00001068class VtableInfo {
1069public:
1070 typedef VtableBuilder::Index_t Index_t;
1071private:
1072 CodeGenModule &CGM; // Per-module state.
1073 /// Index_t - Vtable index type.
1074 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1075 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1076 // FIXME: Move to Context.
1077 static MapTy IndexFor;
1078public:
1079 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1080 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1081 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1082 // We own a copy of this, it will go away shortly.
1083 new ElTy (e);
1084 IndexFor[RD] = new ElTy (e);
1085 }
1086 Index_t lookup(const CXXMethodDecl *MD) {
1087 const CXXRecordDecl *RD = MD->getParent();
1088 MapTy::iterator I = IndexFor.find(RD);
1089 if (I == IndexFor.end()) {
1090 std::vector<llvm::Constant *> methods;
1091 VtableBuilder b(methods, RD, CGM);
Mike Stumpf3245642009-08-28 23:22:54 +00001092 b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001093 b.GenerateVtableForVBases(RD, RD);
1094 register_index(RD, b.getIndex());
1095 I = IndexFor.find(RD);
1096 }
1097 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1098 return (*I->second)[MD];
1099 }
1100};
1101
1102// FIXME: Move to Context.
1103VtableInfo::MapTy VtableInfo::IndexFor;
1104
Mike Stump7e8c9932009-07-31 18:25:34 +00001105llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001106 llvm::SmallString<256> OutName;
1107 llvm::raw_svector_ostream Out(OutName);
1108 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001109 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001110 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001111 llvm::GlobalVariable::LinkageTypes linktype;
1112 linktype = llvm::GlobalValue::WeakAnyLinkage;
1113 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001114 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001115 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001116
Mike Stump86a859e2009-08-19 18:10:47 +00001117 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001118
Mike Stumpc57b8272009-08-16 01:46:26 +00001119 // First comes the vtables for all the non-virtual bases...
Mike Stumpf3245642009-08-28 23:22:54 +00001120 Offset = b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001121
Mike Stumpc57b8272009-08-16 01:46:26 +00001122 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001123 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001124
Mike Stumpd0672782009-07-31 21:43:43 +00001125 llvm::Constant *C;
1126 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1127 C = llvm::ConstantArray::get(type, methods);
1128 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001129 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001130 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001131 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001132 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001133 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001134 return vtable;
1135}
1136
Mike Stumpf7d47a52009-08-26 20:46:33 +00001137// FIXME: move to Context
1138static VtableInfo *vtableinfo;
1139
1140llvm::Value *
1141CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1142 const llvm::Type *Ty) {
1143 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1144
1145 // FIXME: move to Context
1146 if (vtableinfo == 0)
1147 vtableinfo = new VtableInfo(CGM);
1148
1149 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1150
1151 Ty = llvm::PointerType::get(Ty, 0);
1152 Ty = llvm::PointerType::get(Ty, 0);
1153 Ty = llvm::PointerType::get(Ty, 0);
1154 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1155 vtbl = Builder.CreateLoad(vtbl);
1156 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1157 Idx, "vfn");
1158 vfn = Builder.CreateLoad(vfn);
1159 return vfn;
1160}
1161
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001162/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1163/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1164/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001165// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001166void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1167 llvm::Value *Src,
1168 const ArrayType *Array,
1169 const CXXRecordDecl *BaseClassDecl,
1170 QualType Ty) {
1171 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1172 assert(CA && "VLA cannot be copied over");
1173 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1174
1175 // Create a temporary for the loop index and initialize it with 0.
1176 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1177 "loop.index");
1178 llvm::Value* zeroConstant =
1179 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1180 Builder.CreateStore(zeroConstant, IndexPtr, false);
1181 // Start the loop with a block that tests the condition.
1182 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1183 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1184
1185 EmitBlock(CondBlock);
1186
1187 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1188 // Generate: if (loop-index < number-of-elements fall to the loop body,
1189 // otherwise, go to the block after the for-loop.
1190 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1191 llvm::Value * NumElementsPtr =
1192 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1193 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1194 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1195 "isless");
1196 // If the condition is true, execute the body.
1197 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1198
1199 EmitBlock(ForBody);
1200 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1201 // Inside the loop body, emit the constructor call on the array element.
1202 Counter = Builder.CreateLoad(IndexPtr);
1203 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1204 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1205 if (BitwiseCopy)
1206 EmitAggregateCopy(Dest, Src, Ty);
1207 else if (CXXConstructorDecl *BaseCopyCtor =
1208 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1209 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1210 Ctor_Complete);
1211 CallArgList CallArgs;
1212 // Push the this (Dest) ptr.
1213 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1214 BaseCopyCtor->getThisType(getContext())));
1215
1216 // Push the Src ptr.
1217 CallArgs.push_back(std::make_pair(RValue::get(Src),
1218 BaseCopyCtor->getParamDecl(0)->getType()));
1219 QualType ResultType =
1220 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1221 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1222 Callee, CallArgs, BaseCopyCtor);
1223 }
1224 EmitBlock(ContinueBlock);
1225
1226 // Emit the increment of the loop counter.
1227 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1228 Counter = Builder.CreateLoad(IndexPtr);
1229 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1230 Builder.CreateStore(NextVal, IndexPtr, false);
1231
1232 // Finally, branch back up to the condition for the next iteration.
1233 EmitBranch(CondBlock);
1234
1235 // Emit the fall-through block.
1236 EmitBlock(AfterFor, true);
1237}
1238
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001239/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1240/// array of objects from SrcValue to DestValue. Assignment can be either a
1241/// bitwise assignment or via a copy assignment operator function call.
1242/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1243void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1244 llvm::Value *Src,
1245 const ArrayType *Array,
1246 const CXXRecordDecl *BaseClassDecl,
1247 QualType Ty) {
1248 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1249 assert(CA && "VLA cannot be asssigned");
1250 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1251
1252 // Create a temporary for the loop index and initialize it with 0.
1253 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1254 "loop.index");
1255 llvm::Value* zeroConstant =
1256 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1257 Builder.CreateStore(zeroConstant, IndexPtr, false);
1258 // Start the loop with a block that tests the condition.
1259 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1260 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1261
1262 EmitBlock(CondBlock);
1263
1264 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1265 // Generate: if (loop-index < number-of-elements fall to the loop body,
1266 // otherwise, go to the block after the for-loop.
1267 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1268 llvm::Value * NumElementsPtr =
1269 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1270 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1271 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1272 "isless");
1273 // If the condition is true, execute the body.
1274 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1275
1276 EmitBlock(ForBody);
1277 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1278 // Inside the loop body, emit the assignment operator call on array element.
1279 Counter = Builder.CreateLoad(IndexPtr);
1280 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1281 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1282 const CXXMethodDecl *MD = 0;
1283 if (BitwiseAssign)
1284 EmitAggregateCopy(Dest, Src, Ty);
1285 else {
1286 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1287 MD);
1288 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1289 (void)hasCopyAssign;
1290 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1291 const llvm::Type *LTy =
1292 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1293 FPT->isVariadic());
1294 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1295
1296 CallArgList CallArgs;
1297 // Push the this (Dest) ptr.
1298 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1299 MD->getThisType(getContext())));
1300
1301 // Push the Src ptr.
1302 CallArgs.push_back(std::make_pair(RValue::get(Src),
1303 MD->getParamDecl(0)->getType()));
1304 QualType ResultType =
1305 MD->getType()->getAsFunctionType()->getResultType();
1306 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1307 Callee, CallArgs, MD);
1308 }
1309 EmitBlock(ContinueBlock);
1310
1311 // Emit the increment of the loop counter.
1312 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1313 Counter = Builder.CreateLoad(IndexPtr);
1314 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1315 Builder.CreateStore(NextVal, IndexPtr, false);
1316
1317 // Finally, branch back up to the condition for the next iteration.
1318 EmitBranch(CondBlock);
1319
1320 // Emit the fall-through block.
1321 EmitBlock(AfterFor, true);
1322}
1323
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001324/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1325/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001326/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001327void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001328 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001329 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001330 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1331 if (ClassDecl) {
1332 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1333 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1334 }
1335 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1336 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001337 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001338 }
1339
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001340 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001341 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001342 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1343 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001344 CallArgList CallArgs;
1345 // Push the this (Dest) ptr.
1346 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1347 BaseCopyCtor->getThisType(getContext())));
1348
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001349 // Push the Src ptr.
1350 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001351 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001352 QualType ResultType =
1353 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1354 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1355 Callee, CallArgs, BaseCopyCtor);
1356 }
1357}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001358
Fariborz Jahanian04500242009-08-12 23:34:46 +00001359/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1360/// object from SrcValue to DestValue. Assignment can be either a bitwise
1361/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001362// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001363void CodeGenFunction::EmitClassCopyAssignment(
1364 llvm::Value *Dest, llvm::Value *Src,
1365 const CXXRecordDecl *ClassDecl,
1366 const CXXRecordDecl *BaseClassDecl,
1367 QualType Ty) {
1368 if (ClassDecl) {
1369 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1370 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1371 }
1372 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1373 EmitAggregateCopy(Dest, Src, Ty);
1374 return;
1375 }
1376
1377 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001378 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1379 MD);
1380 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1381 (void)ConstCopyAssignOp;
1382
1383 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1384 const llvm::Type *LTy =
1385 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1386 FPT->isVariadic());
1387 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001388
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001389 CallArgList CallArgs;
1390 // Push the this (Dest) ptr.
1391 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1392 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001393
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001394 // Push the Src ptr.
1395 CallArgs.push_back(std::make_pair(RValue::get(Src),
1396 MD->getParamDecl(0)->getType()));
1397 QualType ResultType =
1398 MD->getType()->getAsFunctionType()->getResultType();
1399 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1400 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001401}
1402
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001403/// SynthesizeDefaultConstructor - synthesize a default constructor
1404void
1405CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1406 const FunctionDecl *FD,
1407 llvm::Function *Fn,
1408 const FunctionArgList &Args) {
1409 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1410 EmitCtorPrologue(CD);
1411 FinishFunction();
1412}
1413
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001414/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001415/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1416/// The implicitly-defined copy constructor for class X performs a memberwise
1417/// copy of its subobjects. The order of copying is the same as the order
1418/// of initialization of bases and members in a user-defined constructor
1419/// Each subobject is copied in the manner appropriate to its type:
1420/// if the subobject is of class type, the copy constructor for the class is
1421/// used;
1422/// if the subobject is an array, each element is copied, in the manner
1423/// appropriate to the element type;
1424/// if the subobject is of scalar type, the built-in assignment operator is
1425/// used.
1426/// Virtual base class subobjects shall be copied only once by the
1427/// implicitly-defined copy constructor
1428
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001429void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1430 const FunctionDecl *FD,
1431 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001432 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001433 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1434 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001435 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1436 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001437
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001438 FunctionArgList::const_iterator i = Args.begin();
1439 const VarDecl *ThisArg = i->first;
1440 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1441 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1442 const VarDecl *SrcArg = (i+1)->first;
1443 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1444 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1445
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001446 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1447 Base != ClassDecl->bases_end(); ++Base) {
1448 // FIXME. copy constrution of virtual base NYI
1449 if (Base->isVirtual())
1450 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001451
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001452 CXXRecordDecl *BaseClassDecl
1453 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001454 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1455 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001456 }
1457
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001458 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1459 FieldEnd = ClassDecl->field_end();
1460 Field != FieldEnd; ++Field) {
1461 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001462 const ConstantArrayType *Array =
1463 getContext().getAsConstantArrayType(FieldType);
1464 if (Array)
1465 FieldType = getContext().getBaseElementType(FieldType);
1466
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001467 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1468 CXXRecordDecl *FieldClassDecl
1469 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1470 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1471 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001472 if (Array) {
1473 const llvm::Type *BasePtr = ConvertType(FieldType);
1474 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1475 llvm::Value *DestBaseAddrPtr =
1476 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1477 llvm::Value *SrcBaseAddrPtr =
1478 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1479 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1480 FieldClassDecl, FieldType);
1481 }
1482 else
1483 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1484 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001485 continue;
1486 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001487 // Do a built-in assignment of scalar data members.
1488 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1489 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1490 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1491 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001492 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001493 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001494}
1495
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001496/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1497/// Before the implicitly-declared copy assignment operator for a class is
1498/// implicitly defined, all implicitly- declared copy assignment operators for
1499/// its direct base classes and its nonstatic data members shall have been
1500/// implicitly defined. [12.8-p12]
1501/// The implicitly-defined copy assignment operator for class X performs
1502/// memberwise assignment of its subob- jects. The direct base classes of X are
1503/// assigned first, in the order of their declaration in
1504/// the base-specifier-list, and then the immediate nonstatic data members of X
1505/// are assigned, in the order in which they were declared in the class
1506/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001507/// if the subobject is of class type, the copy assignment operator for the
1508/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001509/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001510///
1511/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001512/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001513///
1514/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001515/// used.
1516void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1517 const FunctionDecl *FD,
1518 llvm::Function *Fn,
1519 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001520
1521 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1522 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1523 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001524 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1525
Fariborz Jahanian04500242009-08-12 23:34:46 +00001526 FunctionArgList::const_iterator i = Args.begin();
1527 const VarDecl *ThisArg = i->first;
1528 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1529 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1530 const VarDecl *SrcArg = (i+1)->first;
1531 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1532 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1533
1534 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1535 Base != ClassDecl->bases_end(); ++Base) {
1536 // FIXME. copy assignment of virtual base NYI
1537 if (Base->isVirtual())
1538 continue;
1539
1540 CXXRecordDecl *BaseClassDecl
1541 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1542 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1543 Base->getType());
1544 }
1545
1546 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1547 FieldEnd = ClassDecl->field_end();
1548 Field != FieldEnd; ++Field) {
1549 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001550 const ConstantArrayType *Array =
1551 getContext().getAsConstantArrayType(FieldType);
1552 if (Array)
1553 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001554
1555 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1556 CXXRecordDecl *FieldClassDecl
1557 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1558 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1559 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001560 if (Array) {
1561 const llvm::Type *BasePtr = ConvertType(FieldType);
1562 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1563 llvm::Value *DestBaseAddrPtr =
1564 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1565 llvm::Value *SrcBaseAddrPtr =
1566 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1567 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1568 FieldClassDecl, FieldType);
1569 }
1570 else
1571 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1572 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001573 continue;
1574 }
1575 // Do a built-in assignment of scalar data members.
1576 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1577 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1578 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1579 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001580 }
1581
1582 // return *this;
1583 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001584
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001585 FinishFunction();
1586}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001587
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001588/// EmitCtorPrologue - This routine generates necessary code to initialize
1589/// base classes and non-static data members belonging to this constructor.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001590/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001591void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001592 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001593 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001594 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001595
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001596 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001597 E = CD->init_end();
1598 B != E; ++B) {
1599 CXXBaseOrMemberInitializer *Member = (*B);
1600 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001601 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001602 Type *BaseType = Member->getBaseClass();
1603 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001604 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001605 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1606 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001607 EmitCXXConstructorCall(Member->getConstructor(),
1608 Ctor_Complete, V,
1609 Member->const_arg_begin(),
1610 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001611 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001612 // non-static data member initilaizers.
1613 FieldDecl *Field = Member->getMember();
1614 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001615 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001616 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001617 if (Array)
1618 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001619
Mike Stump7e8c9932009-07-31 18:25:34 +00001620 LoadOfThis = LoadCXXThis();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001621 LValue LHS;
1622 if (FieldType->isReferenceType()) {
1623 // FIXME: This is really ugly; should be refactored somehow
1624 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1625 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1626 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1627 QualType::GCNone, FieldType.getAddressSpace());
1628 } else {
1629 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1630 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001631 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001632 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001633 assert(Member->getConstructor() &&
1634 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001635 if (Array) {
1636 const llvm::Type *BasePtr = ConvertType(FieldType);
1637 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1638 llvm::Value *BaseAddrPtr =
1639 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1640 EmitCXXAggrConstructorCall(Member->getConstructor(),
1641 Array, BaseAddrPtr);
1642 }
1643 else
1644 EmitCXXConstructorCall(Member->getConstructor(),
1645 Ctor_Complete, LHS.getAddress(),
1646 Member->const_arg_begin(),
1647 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001648 continue;
1649 }
1650 else {
1651 // Initializing an anonymous union data member.
1652 FieldDecl *anonMember = Member->getAnonUnionMember();
1653 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1654 FieldType = anonMember->getType();
1655 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001656 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001657
1658 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001659 Expr *RhsExpr = *Member->arg_begin();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001660 RValue RHS;
1661 if (FieldType->isReferenceType())
1662 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1663 /*IsInitializer=*/true);
1664 else
1665 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1666 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001667 }
1668 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001669
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001670 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001671 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001672 // have bases classes and/or contain non-static data members which require
1673 // construction.
1674 for (CXXRecordDecl::base_class_const_iterator Base =
1675 ClassDecl->bases_begin();
1676 Base != ClassDecl->bases_end(); ++Base) {
1677 // FIXME. copy assignment of virtual base NYI
1678 if (Base->isVirtual())
1679 continue;
1680
1681 CXXRecordDecl *BaseClassDecl
1682 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1683 if (BaseClassDecl->hasTrivialConstructor())
1684 continue;
1685 if (CXXConstructorDecl *BaseCX =
1686 BaseClassDecl->getDefaultConstructor(getContext())) {
1687 LoadOfThis = LoadCXXThis();
1688 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1689 BaseClassDecl);
1690 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1691 }
1692 }
1693
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1695 FieldEnd = ClassDecl->field_end();
1696 Field != FieldEnd; ++Field) {
1697 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001698 const ConstantArrayType *Array =
1699 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001700 if (Array)
1701 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001702 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1703 continue;
1704 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001705 CXXRecordDecl *MemberClassDecl =
1706 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1707 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1708 continue;
1709 if (CXXConstructorDecl *MamberCX =
1710 MemberClassDecl->getDefaultConstructor(getContext())) {
1711 LoadOfThis = LoadCXXThis();
1712 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001713 if (Array) {
1714 const llvm::Type *BasePtr = ConvertType(FieldType);
1715 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1716 llvm::Value *BaseAddrPtr =
1717 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1718 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1719 }
1720 else
1721 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1722 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001723 }
1724 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001725 }
1726
Mike Stump7e8c9932009-07-31 18:25:34 +00001727 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001728 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001729 if (!LoadOfThis)
1730 LoadOfThis = LoadCXXThis();
1731 llvm::Value *VtableField;
1732 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001733 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001734 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1735 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1736 llvm::Value *vtable = GenerateVtable(ClassDecl);
1737 Builder.CreateStore(vtable, VtableField);
1738 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001739}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001740
1741/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1742/// destructor. This is to call destructors on members and base classes
1743/// in reverse order of their construction.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001744/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001745void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1746 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1747 assert(!ClassDecl->isPolymorphic() &&
1748 "FIXME. polymorphic destruction not supported");
1749 (void)ClassDecl; // prevent warning.
1750
1751 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1752 *E = DD->destr_end(); B != E; ++B) {
1753 uintptr_t BaseOrMember = (*B);
1754 if (DD->isMemberToDestroy(BaseOrMember)) {
1755 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1756 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001757 const ConstantArrayType *Array =
1758 getContext().getAsConstantArrayType(FieldType);
1759 if (Array)
1760 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001761 const RecordType *RT = FieldType->getAs<RecordType>();
1762 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1763 if (FieldClassDecl->hasTrivialDestructor())
1764 continue;
1765 llvm::Value *LoadOfThis = LoadCXXThis();
1766 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001767 if (Array) {
1768 const llvm::Type *BasePtr = ConvertType(FieldType);
1769 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1770 llvm::Value *BaseAddrPtr =
1771 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1772 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1773 Array, BaseAddrPtr);
1774 }
1775 else
1776 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1777 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001778 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001779 const RecordType *RT =
1780 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1781 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1782 if (BaseClassDecl->hasTrivialDestructor())
1783 continue;
1784 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1785 ClassDecl,BaseClassDecl);
1786 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1787 Dtor_Complete, V);
1788 }
1789 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001790 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1791 return;
1792 // Case of destructor synthesis with fields and base classes
1793 // which have non-trivial destructors. They must be destructed in
1794 // reverse order of their construction.
1795 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1796
1797 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1798 FieldEnd = ClassDecl->field_end();
1799 Field != FieldEnd; ++Field) {
1800 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001801 if (getContext().getAsConstantArrayType(FieldType))
1802 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001803 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1804 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1805 if (FieldClassDecl->hasTrivialDestructor())
1806 continue;
1807 DestructedFields.push_back(*Field);
1808 }
1809 }
1810 if (!DestructedFields.empty())
1811 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1812 FieldDecl *Field = DestructedFields[i];
1813 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001814 const ConstantArrayType *Array =
1815 getContext().getAsConstantArrayType(FieldType);
1816 if (Array)
1817 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001818 const RecordType *RT = FieldType->getAs<RecordType>();
1819 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1820 llvm::Value *LoadOfThis = LoadCXXThis();
1821 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001822 if (Array) {
1823 const llvm::Type *BasePtr = ConvertType(FieldType);
1824 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1825 llvm::Value *BaseAddrPtr =
1826 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1827 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1828 Array, BaseAddrPtr);
1829 }
1830 else
1831 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1832 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001833 }
1834
1835 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1836 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1837 Base != ClassDecl->bases_end(); ++Base) {
1838 // FIXME. copy assignment of virtual base NYI
1839 if (Base->isVirtual())
1840 continue;
1841
1842 CXXRecordDecl *BaseClassDecl
1843 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1844 if (BaseClassDecl->hasTrivialDestructor())
1845 continue;
1846 DestructedBases.push_back(BaseClassDecl);
1847 }
1848 if (DestructedBases.empty())
1849 return;
1850 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1851 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1852 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1853 ClassDecl,BaseClassDecl);
1854 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1855 Dtor_Complete, V);
1856 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001857}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001858
1859void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1860 const FunctionDecl *FD,
1861 llvm::Function *Fn,
1862 const FunctionArgList &Args) {
1863
1864 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1865 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1866 "SynthesizeDefaultDestructor - destructor has user declaration");
1867 (void) ClassDecl;
1868
1869 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1870 EmitDtorEpilogue(CD);
1871 FinishFunction();
1872}