blob: 97837b364af54cfc11f04c9334302c0651de1ef8 [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 Stump35af2b12009-09-01 22:20:28 +0000895 bool OverrideMethod(const CXXMethodDecl *MD, llvm::Constant *m,
896 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000897 typedef CXXMethodDecl::method_iterator meth_iter;
898
Mike Stumpf07ede52009-08-21 01:45:00 +0000899 // FIXME: Don't like the nested loops. For very large inheritance
900 // heirarchies we could have a table on the side with the final overridder
901 // and just replace each instance of an overridden method once. Would be
902 // nice to measure the cost/benefit on real code.
903
904 // If we can find a previously allocated slot for this, reuse it.
905 for (meth_iter mi = MD->begin_overridden_methods(),
906 e = MD->end_overridden_methods();
907 mi != e; ++mi) {
908 const CXXMethodDecl *OMD = *mi;
909 llvm::Constant *om;
910 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
911 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
912
Mike Stumpf3245642009-08-28 23:22:54 +0000913 for (Index_t i = 0, e = submethods.size();
Mike Stumpf7d47a52009-08-26 20:46:33 +0000914 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000915 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stumpf3245642009-08-28 23:22:54 +0000916 if (submethods[i] == om) {
917 // FIXME: thunks
918 submethods[i] = m;
919 Index[MD] = i;
920 if (MorallyVirtual) {
921 VCallOffset[MD] = Offset/8;
922 VCalls[VCall[OMD]] = Offset/8 - VCallOffset[OMD];
923 }
924 // submethods[VCall[OMD]] = wrap(Offset/8 - VCallOffset[OMD]);
Mike Stump35af2b12009-09-01 22:20:28 +0000925 return true;
Mike Stumpf07ede52009-08-21 01:45:00 +0000926 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000927 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000928 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000929
Mike Stump35af2b12009-09-01 22:20:28 +0000930 return false;
931 }
932
933 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint,
934 bool MorallyVirtual, Index_t Offset) {
935 llvm::Constant *m;
936 m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
937 if (OverrideMethod(MD, m, MorallyVirtual, Offset))
938 return;
939
Mike Stumpf07ede52009-08-21 01:45:00 +0000940 // else allocate a new slot.
Mike Stumpf3245642009-08-28 23:22:54 +0000941 Index[MD] = submethods.size();
942 // VCall[MD] = Offset;
943 if (MorallyVirtual) {
944 VCallOffset[MD] = Offset/8;
945 Index_t &idx = VCall[MD];
946 // Allocate the first one, after that, we reuse the previous one.
947 if (idx == 0) {
948 idx = VCalls.size()+1;
949 VCallOffset[MD] = Offset/8;
950 VCalls.push_back(0);
951 }
952 }
953 submethods.push_back(m);
Mike Stumpf07ede52009-08-21 01:45:00 +0000954 }
955
Mike Stumpf3245642009-08-28 23:22:54 +0000956 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
957 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000958 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
959 ++mi)
960 if (mi->isVirtual())
Mike Stumpf3245642009-08-28 23:22:54 +0000961 AddMethod(*mi, AddressPoint, MorallyVirtual, Offset);
Mike Stumpdecd7812009-08-12 23:00:59 +0000962 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000963
Mike Stump00962322009-08-21 23:09:30 +0000964 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stumpf3245642009-08-28 23:22:54 +0000965 bool forPrimary, bool Bottom,
966 bool MorallyVirtual,
Mike Stump00962322009-08-21 23:09:30 +0000967 int64_t Offset,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000968 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000969 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000970 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +0000971
Mike Stump7bae1282009-08-18 21:30:21 +0000972 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +0000973 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +0000974
975 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
976 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
977 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
978
Mike Stumpf3245642009-08-28 23:22:54 +0000979 std::vector<llvm::Constant *> offsets;
Mike Stump7bae1282009-08-18 21:30:21 +0000980 // FIXME: Audit, is this right?
Mike Stumpf3245642009-08-28 23:22:54 +0000981 if (Bottom && (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual
982 || Bottom))
Mike Stumpaf0d0452009-08-20 07:22:17 +0000983 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000984
Mike Stump7bae1282009-08-18 21:30:21 +0000985 bool Top = true;
986
987 // vtables are composed from the chain of primaries.
988 if (PrimaryBase) {
989 if (PrimaryBaseWasVirtual)
990 IndirectPrimary.insert(PrimaryBase);
991 Top = false;
Mike Stumpf3245642009-08-28 23:22:54 +0000992 AddressPoint = GenerateVtableForBase(PrimaryBase, true, false,
993 PrimaryBaseWasVirtual|MorallyVirtual,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000994 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +0000995 }
996
Mike Stumpf3245642009-08-28 23:22:54 +0000997 // And add the virtuals for the class to the primary vtable.
998 GenerateMethods(RD, AddressPoint, MorallyVirtual, Offset);
999
1000 if (!Bottom)
1001 return AddressPoint;
1002
1003 StartNewTable();
1004 // FIXME: Cleanup.
1005 if (!ForVirtualBase) {
1006 // then virtual base offsets...
1007 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1008 e = offsets.rend(); i != e; ++i)
1009 methods.push_back(*i);
Mike Stumpc57b8272009-08-16 01:46:26 +00001010 }
Mike Stump2eade572009-08-13 22:53:07 +00001011
Mike Stumpf3245642009-08-28 23:22:54 +00001012 // The vcalls come first...
1013 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1014 i < e; ++i)
1015 methods.push_back(wrap((0?600:0) + *i));
1016 VCalls.clear();
1017
1018 if (ForVirtualBase) {
1019 // then virtual base offsets...
1020 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1021 e = offsets.rend(); i != e; ++i)
1022 methods.push_back(*i);
1023 }
1024
1025 int64_t BaseOffset;
1026 if (ForVirtualBase) {
1027 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1028 // FIXME: The above is redundant with the other case.
1029 assert(BaseOffset == -Offset/8);
1030 } else
1031 BaseOffset = -Offset/8;
1032 m = wrap(BaseOffset);
1033 methods.push_back(m);
1034 methods.push_back(rtti);
1035 AddressPoint = methods.size();
1036
1037 methods.insert(methods.end(), submethods.begin(), submethods.end());
1038 submethods.clear();
Mike Stump7bae1282009-08-18 21:30:21 +00001039
1040 // and then the non-virtual bases.
1041 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1042 e = RD->bases_end(); i != e; ++i) {
1043 if (i->isVirtual())
1044 continue;
1045 const CXXRecordDecl *Base =
1046 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1047 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1048 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001049 StartNewTable();
Mike Stumpf3245642009-08-28 23:22:54 +00001050 GenerateVtableForBase(Base, true, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001051 }
1052 }
Mike Stump00962322009-08-21 23:09:30 +00001053 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001054 }
1055
1056 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001057 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001058 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1059 e = RD->bases_end(); i != e; ++i) {
1060 const CXXRecordDecl *Base =
1061 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1062 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1063 // Mark it so we don't output it twice.
1064 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001065 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001066 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf3245642009-08-28 23:22:54 +00001067 GenerateVtableForBase(Base, false, true, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001068 }
1069 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001070 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001071 }
1072 }
Mike Stump7bae1282009-08-18 21:30:21 +00001073};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001074
Mike Stumpf7d47a52009-08-26 20:46:33 +00001075class VtableInfo {
1076public:
1077 typedef VtableBuilder::Index_t Index_t;
1078private:
1079 CodeGenModule &CGM; // Per-module state.
1080 /// Index_t - Vtable index type.
1081 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1082 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1083 // FIXME: Move to Context.
1084 static MapTy IndexFor;
1085public:
1086 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1087 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1088 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1089 // We own a copy of this, it will go away shortly.
1090 new ElTy (e);
1091 IndexFor[RD] = new ElTy (e);
1092 }
1093 Index_t lookup(const CXXMethodDecl *MD) {
1094 const CXXRecordDecl *RD = MD->getParent();
1095 MapTy::iterator I = IndexFor.find(RD);
1096 if (I == IndexFor.end()) {
1097 std::vector<llvm::Constant *> methods;
1098 VtableBuilder b(methods, RD, CGM);
Mike Stumpf3245642009-08-28 23:22:54 +00001099 b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001100 b.GenerateVtableForVBases(RD, RD);
1101 register_index(RD, b.getIndex());
1102 I = IndexFor.find(RD);
1103 }
1104 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1105 return (*I->second)[MD];
1106 }
1107};
1108
1109// FIXME: Move to Context.
1110VtableInfo::MapTy VtableInfo::IndexFor;
1111
Mike Stump7e8c9932009-07-31 18:25:34 +00001112llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001113 llvm::SmallString<256> OutName;
1114 llvm::raw_svector_ostream Out(OutName);
1115 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001116 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001117 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001118 llvm::GlobalVariable::LinkageTypes linktype;
1119 linktype = llvm::GlobalValue::WeakAnyLinkage;
1120 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001121 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001122 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001123
Mike Stump86a859e2009-08-19 18:10:47 +00001124 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001125
Mike Stumpc57b8272009-08-16 01:46:26 +00001126 // First comes the vtables for all the non-virtual bases...
Mike Stumpf3245642009-08-28 23:22:54 +00001127 Offset = b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001128
Mike Stumpc57b8272009-08-16 01:46:26 +00001129 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001130 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001131
Mike Stumpd0672782009-07-31 21:43:43 +00001132 llvm::Constant *C;
1133 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1134 C = llvm::ConstantArray::get(type, methods);
1135 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001136 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001137 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001138 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001139 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001140 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001141 return vtable;
1142}
1143
Mike Stumpf7d47a52009-08-26 20:46:33 +00001144// FIXME: move to Context
1145static VtableInfo *vtableinfo;
1146
1147llvm::Value *
1148CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1149 const llvm::Type *Ty) {
1150 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1151
1152 // FIXME: move to Context
1153 if (vtableinfo == 0)
1154 vtableinfo = new VtableInfo(CGM);
1155
1156 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1157
1158 Ty = llvm::PointerType::get(Ty, 0);
1159 Ty = llvm::PointerType::get(Ty, 0);
1160 Ty = llvm::PointerType::get(Ty, 0);
1161 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1162 vtbl = Builder.CreateLoad(vtbl);
1163 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1164 Idx, "vfn");
1165 vfn = Builder.CreateLoad(vfn);
1166 return vfn;
1167}
1168
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001169/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1170/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1171/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001172// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001173void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1174 llvm::Value *Src,
1175 const ArrayType *Array,
1176 const CXXRecordDecl *BaseClassDecl,
1177 QualType Ty) {
1178 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1179 assert(CA && "VLA cannot be copied over");
1180 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1181
1182 // Create a temporary for the loop index and initialize it with 0.
1183 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1184 "loop.index");
1185 llvm::Value* zeroConstant =
1186 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1187 Builder.CreateStore(zeroConstant, IndexPtr, false);
1188 // Start the loop with a block that tests the condition.
1189 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1190 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1191
1192 EmitBlock(CondBlock);
1193
1194 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1195 // Generate: if (loop-index < number-of-elements fall to the loop body,
1196 // otherwise, go to the block after the for-loop.
1197 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1198 llvm::Value * NumElementsPtr =
1199 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1200 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1201 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1202 "isless");
1203 // If the condition is true, execute the body.
1204 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1205
1206 EmitBlock(ForBody);
1207 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1208 // Inside the loop body, emit the constructor call on the array element.
1209 Counter = Builder.CreateLoad(IndexPtr);
1210 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1211 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1212 if (BitwiseCopy)
1213 EmitAggregateCopy(Dest, Src, Ty);
1214 else if (CXXConstructorDecl *BaseCopyCtor =
1215 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1216 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1217 Ctor_Complete);
1218 CallArgList CallArgs;
1219 // Push the this (Dest) ptr.
1220 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1221 BaseCopyCtor->getThisType(getContext())));
1222
1223 // Push the Src ptr.
1224 CallArgs.push_back(std::make_pair(RValue::get(Src),
1225 BaseCopyCtor->getParamDecl(0)->getType()));
1226 QualType ResultType =
1227 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1228 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1229 Callee, CallArgs, BaseCopyCtor);
1230 }
1231 EmitBlock(ContinueBlock);
1232
1233 // Emit the increment of the loop counter.
1234 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1235 Counter = Builder.CreateLoad(IndexPtr);
1236 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1237 Builder.CreateStore(NextVal, IndexPtr, false);
1238
1239 // Finally, branch back up to the condition for the next iteration.
1240 EmitBranch(CondBlock);
1241
1242 // Emit the fall-through block.
1243 EmitBlock(AfterFor, true);
1244}
1245
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001246/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1247/// array of objects from SrcValue to DestValue. Assignment can be either a
1248/// bitwise assignment or via a copy assignment operator function call.
1249/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1250void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1251 llvm::Value *Src,
1252 const ArrayType *Array,
1253 const CXXRecordDecl *BaseClassDecl,
1254 QualType Ty) {
1255 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1256 assert(CA && "VLA cannot be asssigned");
1257 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1258
1259 // Create a temporary for the loop index and initialize it with 0.
1260 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1261 "loop.index");
1262 llvm::Value* zeroConstant =
1263 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1264 Builder.CreateStore(zeroConstant, IndexPtr, false);
1265 // Start the loop with a block that tests the condition.
1266 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1267 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1268
1269 EmitBlock(CondBlock);
1270
1271 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1272 // Generate: if (loop-index < number-of-elements fall to the loop body,
1273 // otherwise, go to the block after the for-loop.
1274 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1275 llvm::Value * NumElementsPtr =
1276 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1277 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1278 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1279 "isless");
1280 // If the condition is true, execute the body.
1281 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1282
1283 EmitBlock(ForBody);
1284 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1285 // Inside the loop body, emit the assignment operator call on array element.
1286 Counter = Builder.CreateLoad(IndexPtr);
1287 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1288 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1289 const CXXMethodDecl *MD = 0;
1290 if (BitwiseAssign)
1291 EmitAggregateCopy(Dest, Src, Ty);
1292 else {
1293 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1294 MD);
1295 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1296 (void)hasCopyAssign;
1297 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1298 const llvm::Type *LTy =
1299 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1300 FPT->isVariadic());
1301 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1302
1303 CallArgList CallArgs;
1304 // Push the this (Dest) ptr.
1305 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1306 MD->getThisType(getContext())));
1307
1308 // Push the Src ptr.
1309 CallArgs.push_back(std::make_pair(RValue::get(Src),
1310 MD->getParamDecl(0)->getType()));
1311 QualType ResultType =
1312 MD->getType()->getAsFunctionType()->getResultType();
1313 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1314 Callee, CallArgs, MD);
1315 }
1316 EmitBlock(ContinueBlock);
1317
1318 // Emit the increment of the loop counter.
1319 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1320 Counter = Builder.CreateLoad(IndexPtr);
1321 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1322 Builder.CreateStore(NextVal, IndexPtr, false);
1323
1324 // Finally, branch back up to the condition for the next iteration.
1325 EmitBranch(CondBlock);
1326
1327 // Emit the fall-through block.
1328 EmitBlock(AfterFor, true);
1329}
1330
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001331/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1332/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001333/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001334void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001335 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001336 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001337 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1338 if (ClassDecl) {
1339 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1340 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1341 }
1342 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1343 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001344 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001345 }
1346
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001347 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001348 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001349 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1350 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001351 CallArgList CallArgs;
1352 // Push the this (Dest) ptr.
1353 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1354 BaseCopyCtor->getThisType(getContext())));
1355
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001356 // Push the Src ptr.
1357 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001358 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001359 QualType ResultType =
1360 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1361 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1362 Callee, CallArgs, BaseCopyCtor);
1363 }
1364}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001365
Fariborz Jahanian04500242009-08-12 23:34:46 +00001366/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1367/// object from SrcValue to DestValue. Assignment can be either a bitwise
1368/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001369// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001370void CodeGenFunction::EmitClassCopyAssignment(
1371 llvm::Value *Dest, llvm::Value *Src,
1372 const CXXRecordDecl *ClassDecl,
1373 const CXXRecordDecl *BaseClassDecl,
1374 QualType Ty) {
1375 if (ClassDecl) {
1376 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1377 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1378 }
1379 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1380 EmitAggregateCopy(Dest, Src, Ty);
1381 return;
1382 }
1383
1384 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001385 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1386 MD);
1387 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1388 (void)ConstCopyAssignOp;
1389
1390 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1391 const llvm::Type *LTy =
1392 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1393 FPT->isVariadic());
1394 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001395
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001396 CallArgList CallArgs;
1397 // Push the this (Dest) ptr.
1398 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1399 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001400
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001401 // Push the Src ptr.
1402 CallArgs.push_back(std::make_pair(RValue::get(Src),
1403 MD->getParamDecl(0)->getType()));
1404 QualType ResultType =
1405 MD->getType()->getAsFunctionType()->getResultType();
1406 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1407 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001408}
1409
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001410/// SynthesizeDefaultConstructor - synthesize a default constructor
1411void
1412CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1413 const FunctionDecl *FD,
1414 llvm::Function *Fn,
1415 const FunctionArgList &Args) {
1416 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1417 EmitCtorPrologue(CD);
1418 FinishFunction();
1419}
1420
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001421/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001422/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1423/// The implicitly-defined copy constructor for class X performs a memberwise
1424/// copy of its subobjects. The order of copying is the same as the order
1425/// of initialization of bases and members in a user-defined constructor
1426/// Each subobject is copied in the manner appropriate to its type:
1427/// if the subobject is of class type, the copy constructor for the class is
1428/// used;
1429/// if the subobject is an array, each element is copied, in the manner
1430/// appropriate to the element type;
1431/// if the subobject is of scalar type, the built-in assignment operator is
1432/// used.
1433/// Virtual base class subobjects shall be copied only once by the
1434/// implicitly-defined copy constructor
1435
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001436void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1437 const FunctionDecl *FD,
1438 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001439 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001440 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1441 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001442 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1443 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001444
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001445 FunctionArgList::const_iterator i = Args.begin();
1446 const VarDecl *ThisArg = i->first;
1447 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1448 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1449 const VarDecl *SrcArg = (i+1)->first;
1450 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1451 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1452
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001453 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1454 Base != ClassDecl->bases_end(); ++Base) {
1455 // FIXME. copy constrution of virtual base NYI
1456 if (Base->isVirtual())
1457 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001458
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001459 CXXRecordDecl *BaseClassDecl
1460 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001461 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1462 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001463 }
1464
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001465 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1466 FieldEnd = ClassDecl->field_end();
1467 Field != FieldEnd; ++Field) {
1468 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001469 const ConstantArrayType *Array =
1470 getContext().getAsConstantArrayType(FieldType);
1471 if (Array)
1472 FieldType = getContext().getBaseElementType(FieldType);
1473
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001474 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1475 CXXRecordDecl *FieldClassDecl
1476 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1477 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1478 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001479 if (Array) {
1480 const llvm::Type *BasePtr = ConvertType(FieldType);
1481 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1482 llvm::Value *DestBaseAddrPtr =
1483 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1484 llvm::Value *SrcBaseAddrPtr =
1485 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1486 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1487 FieldClassDecl, FieldType);
1488 }
1489 else
1490 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1491 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001492 continue;
1493 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001494 // Do a built-in assignment of scalar data members.
1495 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1496 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1497 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1498 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001499 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001500 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001501}
1502
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001503/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1504/// Before the implicitly-declared copy assignment operator for a class is
1505/// implicitly defined, all implicitly- declared copy assignment operators for
1506/// its direct base classes and its nonstatic data members shall have been
1507/// implicitly defined. [12.8-p12]
1508/// The implicitly-defined copy assignment operator for class X performs
1509/// memberwise assignment of its subob- jects. The direct base classes of X are
1510/// assigned first, in the order of their declaration in
1511/// the base-specifier-list, and then the immediate nonstatic data members of X
1512/// are assigned, in the order in which they were declared in the class
1513/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001514/// if the subobject is of class type, the copy assignment operator for the
1515/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001516/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001517///
1518/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001519/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001520///
1521/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001522/// used.
1523void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1524 const FunctionDecl *FD,
1525 llvm::Function *Fn,
1526 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001527
1528 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1529 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1530 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001531 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1532
Fariborz Jahanian04500242009-08-12 23:34:46 +00001533 FunctionArgList::const_iterator i = Args.begin();
1534 const VarDecl *ThisArg = i->first;
1535 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1536 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1537 const VarDecl *SrcArg = (i+1)->first;
1538 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1539 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1540
1541 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1542 Base != ClassDecl->bases_end(); ++Base) {
1543 // FIXME. copy assignment of virtual base NYI
1544 if (Base->isVirtual())
1545 continue;
1546
1547 CXXRecordDecl *BaseClassDecl
1548 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1549 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1550 Base->getType());
1551 }
1552
1553 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1554 FieldEnd = ClassDecl->field_end();
1555 Field != FieldEnd; ++Field) {
1556 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001557 const ConstantArrayType *Array =
1558 getContext().getAsConstantArrayType(FieldType);
1559 if (Array)
1560 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001561
1562 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1563 CXXRecordDecl *FieldClassDecl
1564 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1565 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1566 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001567 if (Array) {
1568 const llvm::Type *BasePtr = ConvertType(FieldType);
1569 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1570 llvm::Value *DestBaseAddrPtr =
1571 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1572 llvm::Value *SrcBaseAddrPtr =
1573 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1574 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1575 FieldClassDecl, FieldType);
1576 }
1577 else
1578 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1579 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001580 continue;
1581 }
1582 // Do a built-in assignment of scalar data members.
1583 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1584 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1585 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1586 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001587 }
1588
1589 // return *this;
1590 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001591
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001592 FinishFunction();
1593}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001594
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001595/// EmitCtorPrologue - This routine generates necessary code to initialize
1596/// base classes and non-static data members belonging to this constructor.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001597/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001598void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001599 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001600 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001601 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001602
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001603 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001604 E = CD->init_end();
1605 B != E; ++B) {
1606 CXXBaseOrMemberInitializer *Member = (*B);
1607 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001608 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001609 Type *BaseType = Member->getBaseClass();
1610 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001611 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001612 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1613 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001614 EmitCXXConstructorCall(Member->getConstructor(),
1615 Ctor_Complete, V,
1616 Member->const_arg_begin(),
1617 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001618 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001619 // non-static data member initilaizers.
1620 FieldDecl *Field = Member->getMember();
1621 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001622 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001623 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001624 if (Array)
1625 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001626
Mike Stump7e8c9932009-07-31 18:25:34 +00001627 LoadOfThis = LoadCXXThis();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001628 LValue LHS;
1629 if (FieldType->isReferenceType()) {
1630 // FIXME: This is really ugly; should be refactored somehow
1631 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1632 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1633 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1634 QualType::GCNone, FieldType.getAddressSpace());
1635 } else {
1636 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1637 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001638 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001639 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001640 assert(Member->getConstructor() &&
1641 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001642 if (Array) {
1643 const llvm::Type *BasePtr = ConvertType(FieldType);
1644 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1645 llvm::Value *BaseAddrPtr =
1646 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1647 EmitCXXAggrConstructorCall(Member->getConstructor(),
1648 Array, BaseAddrPtr);
1649 }
1650 else
1651 EmitCXXConstructorCall(Member->getConstructor(),
1652 Ctor_Complete, LHS.getAddress(),
1653 Member->const_arg_begin(),
1654 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001655 continue;
1656 }
1657 else {
1658 // Initializing an anonymous union data member.
1659 FieldDecl *anonMember = Member->getAnonUnionMember();
1660 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1661 FieldType = anonMember->getType();
1662 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001663 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001664
1665 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001666 Expr *RhsExpr = *Member->arg_begin();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001667 RValue RHS;
1668 if (FieldType->isReferenceType())
1669 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1670 /*IsInitializer=*/true);
1671 else
1672 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1673 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001674 }
1675 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001676
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001677 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001678 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001679 // have bases classes and/or contain non-static data members which require
1680 // construction.
1681 for (CXXRecordDecl::base_class_const_iterator Base =
1682 ClassDecl->bases_begin();
1683 Base != ClassDecl->bases_end(); ++Base) {
1684 // FIXME. copy assignment of virtual base NYI
1685 if (Base->isVirtual())
1686 continue;
1687
1688 CXXRecordDecl *BaseClassDecl
1689 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1690 if (BaseClassDecl->hasTrivialConstructor())
1691 continue;
1692 if (CXXConstructorDecl *BaseCX =
1693 BaseClassDecl->getDefaultConstructor(getContext())) {
1694 LoadOfThis = LoadCXXThis();
1695 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1696 BaseClassDecl);
1697 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1698 }
1699 }
1700
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001701 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1702 FieldEnd = ClassDecl->field_end();
1703 Field != FieldEnd; ++Field) {
1704 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001705 const ConstantArrayType *Array =
1706 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001707 if (Array)
1708 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001709 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1710 continue;
1711 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001712 CXXRecordDecl *MemberClassDecl =
1713 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1714 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1715 continue;
1716 if (CXXConstructorDecl *MamberCX =
1717 MemberClassDecl->getDefaultConstructor(getContext())) {
1718 LoadOfThis = LoadCXXThis();
1719 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001720 if (Array) {
1721 const llvm::Type *BasePtr = ConvertType(FieldType);
1722 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1723 llvm::Value *BaseAddrPtr =
1724 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1725 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1726 }
1727 else
1728 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1729 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001730 }
1731 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001732 }
1733
Mike Stump7e8c9932009-07-31 18:25:34 +00001734 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001735 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001736 if (!LoadOfThis)
1737 LoadOfThis = LoadCXXThis();
1738 llvm::Value *VtableField;
1739 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001740 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001741 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1742 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1743 llvm::Value *vtable = GenerateVtable(ClassDecl);
1744 Builder.CreateStore(vtable, VtableField);
1745 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001746}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001747
1748/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1749/// destructor. This is to call destructors on members and base classes
1750/// in reverse order of their construction.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001751/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001752void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1753 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
Anders Carlssona82465d2009-09-01 21:12:16 +00001754 assert(!ClassDecl->getNumVBases() &&
1755 "FIXME: Destruction of virtual bases not supported");
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001756 (void)ClassDecl; // prevent warning.
1757
1758 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1759 *E = DD->destr_end(); B != E; ++B) {
1760 uintptr_t BaseOrMember = (*B);
1761 if (DD->isMemberToDestroy(BaseOrMember)) {
1762 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1763 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001764 const ConstantArrayType *Array =
1765 getContext().getAsConstantArrayType(FieldType);
1766 if (Array)
1767 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001768 const RecordType *RT = FieldType->getAs<RecordType>();
1769 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1770 if (FieldClassDecl->hasTrivialDestructor())
1771 continue;
1772 llvm::Value *LoadOfThis = LoadCXXThis();
1773 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001774 if (Array) {
1775 const llvm::Type *BasePtr = ConvertType(FieldType);
1776 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1777 llvm::Value *BaseAddrPtr =
1778 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1779 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1780 Array, BaseAddrPtr);
1781 }
1782 else
1783 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1784 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001785 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001786 const RecordType *RT =
1787 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1788 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1789 if (BaseClassDecl->hasTrivialDestructor())
1790 continue;
1791 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1792 ClassDecl,BaseClassDecl);
1793 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1794 Dtor_Complete, V);
1795 }
1796 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001797 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1798 return;
1799 // Case of destructor synthesis with fields and base classes
1800 // which have non-trivial destructors. They must be destructed in
1801 // reverse order of their construction.
1802 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1803
1804 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1805 FieldEnd = ClassDecl->field_end();
1806 Field != FieldEnd; ++Field) {
1807 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001808 if (getContext().getAsConstantArrayType(FieldType))
1809 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001810 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1811 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1812 if (FieldClassDecl->hasTrivialDestructor())
1813 continue;
1814 DestructedFields.push_back(*Field);
1815 }
1816 }
1817 if (!DestructedFields.empty())
1818 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1819 FieldDecl *Field = DestructedFields[i];
1820 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001821 const ConstantArrayType *Array =
1822 getContext().getAsConstantArrayType(FieldType);
1823 if (Array)
1824 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001825 const RecordType *RT = FieldType->getAs<RecordType>();
1826 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1827 llvm::Value *LoadOfThis = LoadCXXThis();
1828 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001829 if (Array) {
1830 const llvm::Type *BasePtr = ConvertType(FieldType);
1831 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1832 llvm::Value *BaseAddrPtr =
1833 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1834 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1835 Array, BaseAddrPtr);
1836 }
1837 else
1838 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1839 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001840 }
1841
1842 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1843 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1844 Base != ClassDecl->bases_end(); ++Base) {
1845 // FIXME. copy assignment of virtual base NYI
1846 if (Base->isVirtual())
1847 continue;
1848
1849 CXXRecordDecl *BaseClassDecl
1850 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1851 if (BaseClassDecl->hasTrivialDestructor())
1852 continue;
1853 DestructedBases.push_back(BaseClassDecl);
1854 }
1855 if (DestructedBases.empty())
1856 return;
1857 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1858 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1859 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1860 ClassDecl,BaseClassDecl);
1861 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1862 Dtor_Complete, V);
1863 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001864}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001865
1866void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1867 const FunctionDecl *FD,
1868 llvm::Function *Fn,
1869 const FunctionArgList &Args) {
1870
1871 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1872 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1873 "SynthesizeDefaultDestructor - destructor has user declaration");
1874 (void) ClassDecl;
1875
1876 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1877 EmitDtorEpilogue(CD);
1878 FinishFunction();
1879}