blob: c8e3d88e00e1ec29264701f9d3d1825966d7fe4e [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
Mike Stump35240ec2009-09-01 23:22:44 +0000933 void OverrideMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
934 bool MorallyVirtual, Index_t Offset) {
935 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
936 ++mi)
937 if (mi->isVirtual()) {
938 const CXXMethodDecl *MD = *mi;
939 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
940 OverrideMethod(MD, m, MorallyVirtual, Offset);
941 }
942 }
943
Mike Stump35af2b12009-09-01 22:20:28 +0000944 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint,
945 bool MorallyVirtual, Index_t Offset) {
Mike Stump35240ec2009-09-01 23:22:44 +0000946 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stump35af2b12009-09-01 22:20:28 +0000947 if (OverrideMethod(MD, m, MorallyVirtual, Offset))
948 return;
949
Mike Stumpf07ede52009-08-21 01:45:00 +0000950 // else allocate a new slot.
Mike Stumpf3245642009-08-28 23:22:54 +0000951 Index[MD] = submethods.size();
952 // VCall[MD] = Offset;
953 if (MorallyVirtual) {
954 VCallOffset[MD] = Offset/8;
955 Index_t &idx = VCall[MD];
956 // Allocate the first one, after that, we reuse the previous one.
957 if (idx == 0) {
958 idx = VCalls.size()+1;
959 VCallOffset[MD] = Offset/8;
960 VCalls.push_back(0);
961 }
962 }
963 submethods.push_back(m);
Mike Stumpf07ede52009-08-21 01:45:00 +0000964 }
965
Mike Stump35240ec2009-09-01 23:22:44 +0000966 void AddMethods(const CXXRecordDecl *RD, Index_t AddressPoint,
967 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000968 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
969 ++mi)
970 if (mi->isVirtual())
Mike Stumpf3245642009-08-28 23:22:54 +0000971 AddMethod(*mi, AddressPoint, MorallyVirtual, Offset);
Mike Stumpdecd7812009-08-12 23:00:59 +0000972 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000973
Mike Stump35240ec2009-09-01 23:22:44 +0000974 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, bool forPrimary,
975 bool Bottom, bool MorallyVirtual,
976 int64_t Offset, bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000977 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000978 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +0000979
Mike Stump7bae1282009-08-18 21:30:21 +0000980 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +0000981 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +0000982
983 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
984 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
985 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
986
Mike Stumpf3245642009-08-28 23:22:54 +0000987 std::vector<llvm::Constant *> offsets;
Mike Stump7bae1282009-08-18 21:30:21 +0000988 // FIXME: Audit, is this right?
Mike Stumpf3245642009-08-28 23:22:54 +0000989 if (Bottom && (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual
990 || Bottom))
Mike Stumpaf0d0452009-08-20 07:22:17 +0000991 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000992
Mike Stump7bae1282009-08-18 21:30:21 +0000993 bool Top = true;
994
995 // vtables are composed from the chain of primaries.
996 if (PrimaryBase) {
997 if (PrimaryBaseWasVirtual)
998 IndirectPrimary.insert(PrimaryBase);
999 Top = false;
Mike Stumpf3245642009-08-28 23:22:54 +00001000 AddressPoint = GenerateVtableForBase(PrimaryBase, true, false,
1001 PrimaryBaseWasVirtual|MorallyVirtual,
Mike Stumpf7d47a52009-08-26 20:46:33 +00001002 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +00001003 }
1004
Mike Stumpf3245642009-08-28 23:22:54 +00001005 // And add the virtuals for the class to the primary vtable.
Mike Stump35240ec2009-09-01 23:22:44 +00001006 AddMethods(RD, AddressPoint, MorallyVirtual, Offset);
Mike Stumpf3245642009-08-28 23:22:54 +00001007
1008 if (!Bottom)
1009 return AddressPoint;
1010
1011 StartNewTable();
1012 // FIXME: Cleanup.
1013 if (!ForVirtualBase) {
1014 // then virtual base offsets...
1015 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1016 e = offsets.rend(); i != e; ++i)
1017 methods.push_back(*i);
Mike Stumpc57b8272009-08-16 01:46:26 +00001018 }
Mike Stump2eade572009-08-13 22:53:07 +00001019
Mike Stumpf3245642009-08-28 23:22:54 +00001020 // The vcalls come first...
1021 for (std::vector<Index_t>::iterator i=VCalls.begin(), e=VCalls.end();
1022 i < e; ++i)
1023 methods.push_back(wrap((0?600:0) + *i));
1024 VCalls.clear();
1025
1026 if (ForVirtualBase) {
1027 // then virtual base offsets...
1028 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1029 e = offsets.rend(); i != e; ++i)
1030 methods.push_back(*i);
1031 }
1032
Mike Stump35240ec2009-09-01 23:22:44 +00001033 m = wrap(-(Offset/8));
Mike Stumpf3245642009-08-28 23:22:54 +00001034 methods.push_back(m);
1035 methods.push_back(rtti);
1036 AddressPoint = methods.size();
1037
1038 methods.insert(methods.end(), submethods.begin(), submethods.end());
1039 submethods.clear();
Mike Stump7bae1282009-08-18 21:30:21 +00001040
1041 // and then the non-virtual bases.
1042 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1043 e = RD->bases_end(); i != e; ++i) {
1044 if (i->isVirtual())
1045 continue;
1046 const CXXRecordDecl *Base =
1047 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1048 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1049 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001050 StartNewTable();
Mike Stumpf3245642009-08-28 23:22:54 +00001051 GenerateVtableForBase(Base, true, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001052 }
1053 }
Mike Stump00962322009-08-21 23:09:30 +00001054 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001055 }
1056
1057 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001058 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001059 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1060 e = RD->bases_end(); i != e; ++i) {
1061 const CXXRecordDecl *Base =
1062 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1063 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1064 // Mark it so we don't output it twice.
1065 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001066 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001067 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf3245642009-08-28 23:22:54 +00001068 GenerateVtableForBase(Base, false, true, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001069 }
1070 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001071 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001072 }
1073 }
Mike Stump7bae1282009-08-18 21:30:21 +00001074};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001075
Mike Stumpf7d47a52009-08-26 20:46:33 +00001076class VtableInfo {
1077public:
1078 typedef VtableBuilder::Index_t Index_t;
1079private:
1080 CodeGenModule &CGM; // Per-module state.
1081 /// Index_t - Vtable index type.
1082 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1083 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1084 // FIXME: Move to Context.
1085 static MapTy IndexFor;
1086public:
1087 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1088 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1089 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1090 // We own a copy of this, it will go away shortly.
1091 new ElTy (e);
1092 IndexFor[RD] = new ElTy (e);
1093 }
1094 Index_t lookup(const CXXMethodDecl *MD) {
1095 const CXXRecordDecl *RD = MD->getParent();
1096 MapTy::iterator I = IndexFor.find(RD);
1097 if (I == IndexFor.end()) {
1098 std::vector<llvm::Constant *> methods;
1099 VtableBuilder b(methods, RD, CGM);
Mike Stumpf3245642009-08-28 23:22:54 +00001100 b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001101 b.GenerateVtableForVBases(RD, RD);
1102 register_index(RD, b.getIndex());
1103 I = IndexFor.find(RD);
1104 }
1105 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1106 return (*I->second)[MD];
1107 }
1108};
1109
1110// FIXME: Move to Context.
1111VtableInfo::MapTy VtableInfo::IndexFor;
1112
Mike Stump7e8c9932009-07-31 18:25:34 +00001113llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001114 llvm::SmallString<256> OutName;
1115 llvm::raw_svector_ostream Out(OutName);
1116 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001117 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001118 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001119 llvm::GlobalVariable::LinkageTypes linktype;
1120 linktype = llvm::GlobalValue::WeakAnyLinkage;
1121 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001122 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001123 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001124
Mike Stump86a859e2009-08-19 18:10:47 +00001125 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001126
Mike Stumpc57b8272009-08-16 01:46:26 +00001127 // First comes the vtables for all the non-virtual bases...
Mike Stumpf3245642009-08-28 23:22:54 +00001128 Offset = b.GenerateVtableForBase(RD, true, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001129
Mike Stumpc57b8272009-08-16 01:46:26 +00001130 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001131 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001132
Mike Stumpd0672782009-07-31 21:43:43 +00001133 llvm::Constant *C;
1134 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1135 C = llvm::ConstantArray::get(type, methods);
1136 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001137 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001138 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001139 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001140 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001141 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001142 return vtable;
1143}
1144
Mike Stumpf7d47a52009-08-26 20:46:33 +00001145// FIXME: move to Context
1146static VtableInfo *vtableinfo;
1147
1148llvm::Value *
1149CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1150 const llvm::Type *Ty) {
1151 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1152
1153 // FIXME: move to Context
1154 if (vtableinfo == 0)
1155 vtableinfo = new VtableInfo(CGM);
1156
1157 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1158
1159 Ty = llvm::PointerType::get(Ty, 0);
1160 Ty = llvm::PointerType::get(Ty, 0);
1161 Ty = llvm::PointerType::get(Ty, 0);
1162 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1163 vtbl = Builder.CreateLoad(vtbl);
1164 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1165 Idx, "vfn");
1166 vfn = Builder.CreateLoad(vfn);
1167 return vfn;
1168}
1169
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001170/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1171/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1172/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001173// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001174void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1175 llvm::Value *Src,
1176 const ArrayType *Array,
1177 const CXXRecordDecl *BaseClassDecl,
1178 QualType Ty) {
1179 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1180 assert(CA && "VLA cannot be copied over");
1181 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1182
1183 // Create a temporary for the loop index and initialize it with 0.
1184 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1185 "loop.index");
1186 llvm::Value* zeroConstant =
1187 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1188 Builder.CreateStore(zeroConstant, IndexPtr, false);
1189 // Start the loop with a block that tests the condition.
1190 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1191 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1192
1193 EmitBlock(CondBlock);
1194
1195 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1196 // Generate: if (loop-index < number-of-elements fall to the loop body,
1197 // otherwise, go to the block after the for-loop.
1198 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1199 llvm::Value * NumElementsPtr =
1200 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1201 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1202 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1203 "isless");
1204 // If the condition is true, execute the body.
1205 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1206
1207 EmitBlock(ForBody);
1208 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1209 // Inside the loop body, emit the constructor call on the array element.
1210 Counter = Builder.CreateLoad(IndexPtr);
1211 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1212 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1213 if (BitwiseCopy)
1214 EmitAggregateCopy(Dest, Src, Ty);
1215 else if (CXXConstructorDecl *BaseCopyCtor =
1216 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1217 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1218 Ctor_Complete);
1219 CallArgList CallArgs;
1220 // Push the this (Dest) ptr.
1221 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1222 BaseCopyCtor->getThisType(getContext())));
1223
1224 // Push the Src ptr.
1225 CallArgs.push_back(std::make_pair(RValue::get(Src),
1226 BaseCopyCtor->getParamDecl(0)->getType()));
1227 QualType ResultType =
1228 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1229 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1230 Callee, CallArgs, BaseCopyCtor);
1231 }
1232 EmitBlock(ContinueBlock);
1233
1234 // Emit the increment of the loop counter.
1235 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1236 Counter = Builder.CreateLoad(IndexPtr);
1237 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1238 Builder.CreateStore(NextVal, IndexPtr, false);
1239
1240 // Finally, branch back up to the condition for the next iteration.
1241 EmitBranch(CondBlock);
1242
1243 // Emit the fall-through block.
1244 EmitBlock(AfterFor, true);
1245}
1246
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001247/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1248/// array of objects from SrcValue to DestValue. Assignment can be either a
1249/// bitwise assignment or via a copy assignment operator function call.
1250/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1251void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1252 llvm::Value *Src,
1253 const ArrayType *Array,
1254 const CXXRecordDecl *BaseClassDecl,
1255 QualType Ty) {
1256 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1257 assert(CA && "VLA cannot be asssigned");
1258 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1259
1260 // Create a temporary for the loop index and initialize it with 0.
1261 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1262 "loop.index");
1263 llvm::Value* zeroConstant =
1264 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1265 Builder.CreateStore(zeroConstant, IndexPtr, false);
1266 // Start the loop with a block that tests the condition.
1267 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1268 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1269
1270 EmitBlock(CondBlock);
1271
1272 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1273 // Generate: if (loop-index < number-of-elements fall to the loop body,
1274 // otherwise, go to the block after the for-loop.
1275 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1276 llvm::Value * NumElementsPtr =
1277 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1278 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1279 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1280 "isless");
1281 // If the condition is true, execute the body.
1282 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1283
1284 EmitBlock(ForBody);
1285 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1286 // Inside the loop body, emit the assignment operator call on array element.
1287 Counter = Builder.CreateLoad(IndexPtr);
1288 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1289 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1290 const CXXMethodDecl *MD = 0;
1291 if (BitwiseAssign)
1292 EmitAggregateCopy(Dest, Src, Ty);
1293 else {
1294 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1295 MD);
1296 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1297 (void)hasCopyAssign;
1298 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1299 const llvm::Type *LTy =
1300 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1301 FPT->isVariadic());
1302 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1303
1304 CallArgList CallArgs;
1305 // Push the this (Dest) ptr.
1306 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1307 MD->getThisType(getContext())));
1308
1309 // Push the Src ptr.
1310 CallArgs.push_back(std::make_pair(RValue::get(Src),
1311 MD->getParamDecl(0)->getType()));
1312 QualType ResultType =
1313 MD->getType()->getAsFunctionType()->getResultType();
1314 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1315 Callee, CallArgs, MD);
1316 }
1317 EmitBlock(ContinueBlock);
1318
1319 // Emit the increment of the loop counter.
1320 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1321 Counter = Builder.CreateLoad(IndexPtr);
1322 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1323 Builder.CreateStore(NextVal, IndexPtr, false);
1324
1325 // Finally, branch back up to the condition for the next iteration.
1326 EmitBranch(CondBlock);
1327
1328 // Emit the fall-through block.
1329 EmitBlock(AfterFor, true);
1330}
1331
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001332/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1333/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001334/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001335void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001336 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001337 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001338 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1339 if (ClassDecl) {
1340 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1341 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1342 }
1343 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1344 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001345 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001346 }
1347
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001348 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001349 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001350 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1351 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001352 CallArgList CallArgs;
1353 // Push the this (Dest) ptr.
1354 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1355 BaseCopyCtor->getThisType(getContext())));
1356
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001357 // Push the Src ptr.
1358 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001359 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001360 QualType ResultType =
1361 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1362 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1363 Callee, CallArgs, BaseCopyCtor);
1364 }
1365}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001366
Fariborz Jahanian04500242009-08-12 23:34:46 +00001367/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1368/// object from SrcValue to DestValue. Assignment can be either a bitwise
1369/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001370// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001371void CodeGenFunction::EmitClassCopyAssignment(
1372 llvm::Value *Dest, llvm::Value *Src,
1373 const CXXRecordDecl *ClassDecl,
1374 const CXXRecordDecl *BaseClassDecl,
1375 QualType Ty) {
1376 if (ClassDecl) {
1377 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1378 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1379 }
1380 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1381 EmitAggregateCopy(Dest, Src, Ty);
1382 return;
1383 }
1384
1385 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001386 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1387 MD);
1388 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1389 (void)ConstCopyAssignOp;
1390
1391 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1392 const llvm::Type *LTy =
1393 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1394 FPT->isVariadic());
1395 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001396
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001397 CallArgList CallArgs;
1398 // Push the this (Dest) ptr.
1399 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1400 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001401
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001402 // Push the Src ptr.
1403 CallArgs.push_back(std::make_pair(RValue::get(Src),
1404 MD->getParamDecl(0)->getType()));
1405 QualType ResultType =
1406 MD->getType()->getAsFunctionType()->getResultType();
1407 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1408 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001409}
1410
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001411/// SynthesizeDefaultConstructor - synthesize a default constructor
1412void
1413CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1414 const FunctionDecl *FD,
1415 llvm::Function *Fn,
1416 const FunctionArgList &Args) {
1417 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1418 EmitCtorPrologue(CD);
1419 FinishFunction();
1420}
1421
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001422/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001423/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1424/// The implicitly-defined copy constructor for class X performs a memberwise
1425/// copy of its subobjects. The order of copying is the same as the order
1426/// of initialization of bases and members in a user-defined constructor
1427/// Each subobject is copied in the manner appropriate to its type:
1428/// if the subobject is of class type, the copy constructor for the class is
1429/// used;
1430/// if the subobject is an array, each element is copied, in the manner
1431/// appropriate to the element type;
1432/// if the subobject is of scalar type, the built-in assignment operator is
1433/// used.
1434/// Virtual base class subobjects shall be copied only once by the
1435/// implicitly-defined copy constructor
1436
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001437void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1438 const FunctionDecl *FD,
1439 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001440 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001441 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1442 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001443 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1444 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001445
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001446 FunctionArgList::const_iterator i = Args.begin();
1447 const VarDecl *ThisArg = i->first;
1448 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1449 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1450 const VarDecl *SrcArg = (i+1)->first;
1451 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1452 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1453
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001454 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1455 Base != ClassDecl->bases_end(); ++Base) {
1456 // FIXME. copy constrution of virtual base NYI
1457 if (Base->isVirtual())
1458 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001459
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001460 CXXRecordDecl *BaseClassDecl
1461 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001462 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1463 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001464 }
1465
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001466 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1467 FieldEnd = ClassDecl->field_end();
1468 Field != FieldEnd; ++Field) {
1469 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001470 const ConstantArrayType *Array =
1471 getContext().getAsConstantArrayType(FieldType);
1472 if (Array)
1473 FieldType = getContext().getBaseElementType(FieldType);
1474
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001475 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1476 CXXRecordDecl *FieldClassDecl
1477 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1478 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1479 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001480 if (Array) {
1481 const llvm::Type *BasePtr = ConvertType(FieldType);
1482 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1483 llvm::Value *DestBaseAddrPtr =
1484 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1485 llvm::Value *SrcBaseAddrPtr =
1486 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1487 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1488 FieldClassDecl, FieldType);
1489 }
1490 else
1491 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1492 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001493 continue;
1494 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001495 // Do a built-in assignment of scalar data members.
1496 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1497 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1498 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1499 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001500 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001501 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001502}
1503
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001504/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1505/// Before the implicitly-declared copy assignment operator for a class is
1506/// implicitly defined, all implicitly- declared copy assignment operators for
1507/// its direct base classes and its nonstatic data members shall have been
1508/// implicitly defined. [12.8-p12]
1509/// The implicitly-defined copy assignment operator for class X performs
1510/// memberwise assignment of its subob- jects. The direct base classes of X are
1511/// assigned first, in the order of their declaration in
1512/// the base-specifier-list, and then the immediate nonstatic data members of X
1513/// are assigned, in the order in which they were declared in the class
1514/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001515/// if the subobject is of class type, the copy assignment operator for the
1516/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001517/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001518///
1519/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001520/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001521///
1522/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001523/// used.
1524void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1525 const FunctionDecl *FD,
1526 llvm::Function *Fn,
1527 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001528
1529 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1530 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1531 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001532 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1533
Fariborz Jahanian04500242009-08-12 23:34:46 +00001534 FunctionArgList::const_iterator i = Args.begin();
1535 const VarDecl *ThisArg = i->first;
1536 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1537 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1538 const VarDecl *SrcArg = (i+1)->first;
1539 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1540 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1541
1542 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1543 Base != ClassDecl->bases_end(); ++Base) {
1544 // FIXME. copy assignment of virtual base NYI
1545 if (Base->isVirtual())
1546 continue;
1547
1548 CXXRecordDecl *BaseClassDecl
1549 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1550 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1551 Base->getType());
1552 }
1553
1554 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1555 FieldEnd = ClassDecl->field_end();
1556 Field != FieldEnd; ++Field) {
1557 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001558 const ConstantArrayType *Array =
1559 getContext().getAsConstantArrayType(FieldType);
1560 if (Array)
1561 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001562
1563 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1564 CXXRecordDecl *FieldClassDecl
1565 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1566 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1567 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001568 if (Array) {
1569 const llvm::Type *BasePtr = ConvertType(FieldType);
1570 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1571 llvm::Value *DestBaseAddrPtr =
1572 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1573 llvm::Value *SrcBaseAddrPtr =
1574 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1575 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1576 FieldClassDecl, FieldType);
1577 }
1578 else
1579 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1580 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001581 continue;
1582 }
1583 // Do a built-in assignment of scalar data members.
1584 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1585 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1586 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1587 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001588 }
1589
1590 // return *this;
1591 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001592
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001593 FinishFunction();
1594}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001595
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001596/// EmitCtorPrologue - This routine generates necessary code to initialize
1597/// base classes and non-static data members belonging to this constructor.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001598/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001599void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001600 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001601 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001602 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001603
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001604 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001605 E = CD->init_end();
1606 B != E; ++B) {
1607 CXXBaseOrMemberInitializer *Member = (*B);
1608 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001609 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001610 Type *BaseType = Member->getBaseClass();
1611 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001612 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001613 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1614 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001615 EmitCXXConstructorCall(Member->getConstructor(),
1616 Ctor_Complete, V,
1617 Member->const_arg_begin(),
1618 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001619 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001620 // non-static data member initilaizers.
1621 FieldDecl *Field = Member->getMember();
1622 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001623 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001624 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001625 if (Array)
1626 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001627
Mike Stump7e8c9932009-07-31 18:25:34 +00001628 LoadOfThis = LoadCXXThis();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001629 LValue LHS;
1630 if (FieldType->isReferenceType()) {
1631 // FIXME: This is really ugly; should be refactored somehow
1632 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1633 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1634 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1635 QualType::GCNone, FieldType.getAddressSpace());
1636 } else {
1637 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1638 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001639 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001640 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001641 assert(Member->getConstructor() &&
1642 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001643 if (Array) {
1644 const llvm::Type *BasePtr = ConvertType(FieldType);
1645 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1646 llvm::Value *BaseAddrPtr =
1647 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1648 EmitCXXAggrConstructorCall(Member->getConstructor(),
1649 Array, BaseAddrPtr);
1650 }
1651 else
1652 EmitCXXConstructorCall(Member->getConstructor(),
1653 Ctor_Complete, LHS.getAddress(),
1654 Member->const_arg_begin(),
1655 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001656 continue;
1657 }
1658 else {
1659 // Initializing an anonymous union data member.
1660 FieldDecl *anonMember = Member->getAnonUnionMember();
Anders Carlsson9e00ce72009-09-02 21:14:47 +00001661 LHS = EmitLValueForField(LHS.getAddress(), anonMember,
1662 /*IsUnion=*/true, 0);
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001663 FieldType = anonMember->getType();
1664 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001665 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001666
1667 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001668 Expr *RhsExpr = *Member->arg_begin();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001669 RValue RHS;
1670 if (FieldType->isReferenceType())
1671 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1672 /*IsInitializer=*/true);
1673 else
1674 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1675 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001676 }
1677 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001678
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001679 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001680 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001681 // have bases classes and/or contain non-static data members which require
1682 // construction.
1683 for (CXXRecordDecl::base_class_const_iterator Base =
1684 ClassDecl->bases_begin();
1685 Base != ClassDecl->bases_end(); ++Base) {
1686 // FIXME. copy assignment of virtual base NYI
1687 if (Base->isVirtual())
1688 continue;
1689
1690 CXXRecordDecl *BaseClassDecl
1691 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1692 if (BaseClassDecl->hasTrivialConstructor())
1693 continue;
1694 if (CXXConstructorDecl *BaseCX =
1695 BaseClassDecl->getDefaultConstructor(getContext())) {
1696 LoadOfThis = LoadCXXThis();
1697 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1698 BaseClassDecl);
1699 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1700 }
1701 }
1702
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001703 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1704 FieldEnd = ClassDecl->field_end();
1705 Field != FieldEnd; ++Field) {
1706 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001707 const ConstantArrayType *Array =
1708 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001709 if (Array)
1710 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001711 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1712 continue;
1713 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001714 CXXRecordDecl *MemberClassDecl =
1715 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1716 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1717 continue;
1718 if (CXXConstructorDecl *MamberCX =
1719 MemberClassDecl->getDefaultConstructor(getContext())) {
1720 LoadOfThis = LoadCXXThis();
1721 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001722 if (Array) {
1723 const llvm::Type *BasePtr = ConvertType(FieldType);
1724 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1725 llvm::Value *BaseAddrPtr =
1726 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1727 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1728 }
1729 else
1730 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1731 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001732 }
1733 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001734 }
1735
Mike Stump7e8c9932009-07-31 18:25:34 +00001736 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001737 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001738 if (!LoadOfThis)
1739 LoadOfThis = LoadCXXThis();
1740 llvm::Value *VtableField;
1741 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001742 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001743 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1744 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1745 llvm::Value *vtable = GenerateVtable(ClassDecl);
1746 Builder.CreateStore(vtable, VtableField);
1747 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001748}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001749
1750/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1751/// destructor. This is to call destructors on members and base classes
1752/// in reverse order of their construction.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001753/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001754void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1755 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
Anders Carlssona82465d2009-09-01 21:12:16 +00001756 assert(!ClassDecl->getNumVBases() &&
1757 "FIXME: Destruction of virtual bases not supported");
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001758 (void)ClassDecl; // prevent warning.
1759
1760 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1761 *E = DD->destr_end(); B != E; ++B) {
1762 uintptr_t BaseOrMember = (*B);
1763 if (DD->isMemberToDestroy(BaseOrMember)) {
1764 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1765 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001766 const ConstantArrayType *Array =
1767 getContext().getAsConstantArrayType(FieldType);
1768 if (Array)
1769 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001770 const RecordType *RT = FieldType->getAs<RecordType>();
1771 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1772 if (FieldClassDecl->hasTrivialDestructor())
1773 continue;
1774 llvm::Value *LoadOfThis = LoadCXXThis();
1775 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001776 if (Array) {
1777 const llvm::Type *BasePtr = ConvertType(FieldType);
1778 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1779 llvm::Value *BaseAddrPtr =
1780 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1781 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1782 Array, BaseAddrPtr);
1783 }
1784 else
1785 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1786 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001787 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001788 const RecordType *RT =
1789 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1790 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1791 if (BaseClassDecl->hasTrivialDestructor())
1792 continue;
1793 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1794 ClassDecl,BaseClassDecl);
1795 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1796 Dtor_Complete, V);
1797 }
1798 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001799 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1800 return;
1801 // Case of destructor synthesis with fields and base classes
1802 // which have non-trivial destructors. They must be destructed in
1803 // reverse order of their construction.
1804 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1805
1806 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1807 FieldEnd = ClassDecl->field_end();
1808 Field != FieldEnd; ++Field) {
1809 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001810 if (getContext().getAsConstantArrayType(FieldType))
1811 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001812 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1813 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1814 if (FieldClassDecl->hasTrivialDestructor())
1815 continue;
1816 DestructedFields.push_back(*Field);
1817 }
1818 }
1819 if (!DestructedFields.empty())
1820 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1821 FieldDecl *Field = DestructedFields[i];
1822 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001823 const ConstantArrayType *Array =
1824 getContext().getAsConstantArrayType(FieldType);
1825 if (Array)
1826 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001827 const RecordType *RT = FieldType->getAs<RecordType>();
1828 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1829 llvm::Value *LoadOfThis = LoadCXXThis();
1830 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001831 if (Array) {
1832 const llvm::Type *BasePtr = ConvertType(FieldType);
1833 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1834 llvm::Value *BaseAddrPtr =
1835 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1836 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1837 Array, BaseAddrPtr);
1838 }
1839 else
1840 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1841 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001842 }
1843
1844 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1845 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1846 Base != ClassDecl->bases_end(); ++Base) {
1847 // FIXME. copy assignment of virtual base NYI
1848 if (Base->isVirtual())
1849 continue;
1850
1851 CXXRecordDecl *BaseClassDecl
1852 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1853 if (BaseClassDecl->hasTrivialDestructor())
1854 continue;
1855 DestructedBases.push_back(BaseClassDecl);
1856 }
1857 if (DestructedBases.empty())
1858 return;
1859 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1860 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1861 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1862 ClassDecl,BaseClassDecl);
1863 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1864 Dtor_Complete, V);
1865 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001866}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001867
1868void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1869 const FunctionDecl *FD,
1870 llvm::Function *Fn,
1871 const FunctionArgList &Args) {
1872
1873 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1874 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1875 "SynthesizeDefaultDestructor - destructor has user declaration");
1876 (void) ClassDecl;
1877
1878 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1879 EmitDtorEpilogue(CD);
1880 FinishFunction();
1881}