blob: 5405ac07d9e0267f1b3614228e5d6964de9bf82f [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
215 llvm::Value *Callee;
216 // FIXME: Someone needs to keep track of the qualifications.
217 if (MD->isVirtual() /* && !ME->NotQualified() */)
218 Callee = BuildVirtualCall(MD, This, Ty);
219 else
220 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000221
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000222 return EmitCXXMemberCall(MD, Callee, This,
223 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000224}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000225
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000226RValue
227CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
228 const CXXMethodDecl *MD) {
229 assert(MD->isInstance() &&
230 "Trying to emit a member call expr on a static method!");
231
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000232 if (MD->isCopyAssignment()) {
233 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
234 if (ClassDecl->hasTrivialCopyAssignment()) {
235 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
236 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
237 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
238 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
239 QualType Ty = E->getType();
240 EmitAggregateCopy(This, Src, Ty);
241 return RValue::get(This);
242 }
243 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000244
245 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
246 const llvm::Type *Ty =
247 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
248 FPT->isVariadic());
249 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
250
251 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
252
253 return EmitCXXMemberCall(MD, Callee, This,
254 E->arg_begin() + 1, E->arg_end());
255}
256
Anders Carlsson49d4a572009-04-14 16:58:56 +0000257llvm::Value *CodeGenFunction::LoadCXXThis() {
258 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
259 "Must be in a C++ member function decl to load 'this'");
260 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
261 "Must be in a C++ member function decl to load 'this'");
262
263 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000264 // ans: See how CodeGenFunction::LoadObjCSelf() uses
265 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000266 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
267}
Anders Carlsson652951a2009-04-15 15:55:24 +0000268
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000269static bool
270GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
271 const CXXRecordDecl *ClassDecl,
272 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000273 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
274 e = ClassDecl->bases_end(); i != e; ++i) {
275 if (i->isVirtual())
276 continue;
277 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000278 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000279 if (Base == BaseClassDecl) {
280 NestedBasePaths.push_back(BaseClassDecl);
281 return true;
282 }
283 }
284 // BaseClassDecl not an immediate base of ClassDecl.
285 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
286 e = ClassDecl->bases_end(); i != e; ++i) {
287 if (i->isVirtual())
288 continue;
289 const CXXRecordDecl *Base =
290 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
291 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
292 NestedBasePaths.push_back(Base);
293 return true;
294 }
295 }
296 return false;
297}
298
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000299llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000300 const CXXRecordDecl *ClassDecl,
301 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000302 if (ClassDecl == BaseClassDecl)
303 return BaseValue;
304
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000305 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000306 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
307 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
308 assert(NestedBasePaths.size() > 0 &&
309 "AddressCXXOfBaseClass - inheritence path failed");
310 NestedBasePaths.push_back(ClassDecl);
311 uint64_t Offset = 0;
312
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000313 // Accessing a member of the base class. Must add delata to
314 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000315 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
316 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
317 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
318 const ASTRecordLayout &Layout =
319 getContext().getASTRecordLayout(DerivedClass);
320 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
321 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000322 llvm::Value *OffsetVal =
323 llvm::ConstantInt::get(
324 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000325 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
326 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
327 QualType BTy =
328 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000329 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000330 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000331 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000332 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
333 return BaseValue;
334}
335
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000336/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
337/// for-loop to call the default constructor on individual members of the
338/// array. 'Array' is the array type, 'This' is llvm pointer of the start
339/// of the array and 'D' is the default costructor Decl for elements of the
340/// array. It is assumed that all relevant checks have been made by the
341/// caller.
342void
343CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
344 const ArrayType *Array,
345 llvm::Value *This) {
346 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
347 assert(CA && "Do we support VLA for construction ?");
348
349 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000350 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000351 "loop.index");
352 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000353 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000354 Builder.CreateStore(zeroConstant, IndexPtr, false);
355
356 // Start the loop with a block that tests the condition.
357 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
358 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
359
360 EmitBlock(CondBlock);
361
362 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
363
364 // Generate: if (loop-index < number-of-elements fall to the loop body,
365 // otherwise, go to the block after the for-loop.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000366 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000367 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000368 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000369 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
370 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
371 "isless");
372 // If the condition is true, execute the body.
373 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
374
375 EmitBlock(ForBody);
376
377 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000378 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000379 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000380 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
381 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000382
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000383 EmitBlock(ContinueBlock);
384
385 // Emit the increment of the loop counter.
386 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
387 Counter = Builder.CreateLoad(IndexPtr);
388 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
389 Builder.CreateStore(NextVal, IndexPtr, false);
390
391 // Finally, branch back up to the condition for the next iteration.
392 EmitBranch(CondBlock);
393
394 // Emit the fall-through block.
395 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000396}
397
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000398/// EmitCXXAggrDestructorCall - calls the default destructor on array
399/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000400void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000401CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
402 const ArrayType *Array,
403 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000404 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
405 assert(CA && "Do we support VLA for destruction ?");
406 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
407 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000408 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000409 // Create a temporary for the loop index and initialize it with count of
410 // array elements.
411 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
412 "loop.index");
413 // Index = ElementCount;
414 llvm::Value* UpperCount =
415 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
416 Builder.CreateStore(UpperCount, IndexPtr, false);
417
418 // Start the loop with a block that tests the condition.
419 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
420 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
421
422 EmitBlock(CondBlock);
423
424 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
425
426 // Generate: if (loop-index != 0 fall to the loop body,
427 // otherwise, go to the block after the for-loop.
428 llvm::Value* zeroConstant =
429 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
430 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
431 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
432 "isne");
433 // If the condition is true, execute the body.
434 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
435
436 EmitBlock(ForBody);
437
438 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
439 // Inside the loop body, emit the constructor call on the array element.
440 Counter = Builder.CreateLoad(IndexPtr);
441 Counter = Builder.CreateSub(Counter, One);
442 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
443 EmitCXXDestructorCall(D, Dtor_Complete, Address);
444
445 EmitBlock(ContinueBlock);
446
447 // Emit the decrement of the loop counter.
448 Counter = Builder.CreateLoad(IndexPtr);
449 Counter = Builder.CreateSub(Counter, One, "dec");
450 Builder.CreateStore(Counter, IndexPtr, false);
451
452 // Finally, branch back up to the condition for the next iteration.
453 EmitBranch(CondBlock);
454
455 // Emit the fall-through block.
456 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000457}
458
459void
Anders Carlsson72f48292009-04-17 00:06:03 +0000460CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
461 CXXCtorType Type,
462 llvm::Value *This,
463 CallExpr::const_arg_iterator ArgBeg,
464 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000465 if (D->isCopyConstructor(getContext())) {
466 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
467 if (ClassDecl->hasTrivialCopyConstructor()) {
468 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
469 "EmitCXXConstructorCall - user declared copy constructor");
470 const Expr *E = (*ArgBeg);
471 QualType Ty = E->getType();
472 llvm::Value *Src = EmitLValue(E).getAddress();
473 EmitAggregateCopy(This, Src, Ty);
474 return;
475 }
476 }
477
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000478 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
479
480 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000481}
482
Anders Carlssond3f6b162009-05-29 21:03:38 +0000483void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
484 CXXDtorType Type,
485 llvm::Value *This) {
486 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
487
488 EmitCXXMemberCall(D, Callee, This, 0, 0);
489}
490
Anders Carlsson72f48292009-04-17 00:06:03 +0000491void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000492CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
493 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000494 assert(Dest && "Must have a destination!");
495
496 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000497 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000498 if (RD->hasTrivialConstructor())
499 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000500
501 // Code gen optimization to eliminate copy constructor and return
502 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000503 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000504 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000505 EmitAggExpr((*i), Dest, false);
506 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000507 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000508 // Call the constructor.
509 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
510 E->arg_begin(), E->arg_end());
511}
512
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000513llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000514 if (E->isArray()) {
515 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000516 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000517 }
518
519 QualType AllocType = E->getAllocatedType();
520 FunctionDecl *NewFD = E->getOperatorNew();
521 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
522
523 CallArgList NewArgs;
524
525 // The allocation size is the first argument.
526 QualType SizeTy = getContext().getSizeType();
527 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000528 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000529 getContext().getTypeSize(AllocType) / 8);
530
531 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
532
533 // Emit the rest of the arguments.
534 // FIXME: Ideally, this should just use EmitCallArgs.
535 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
536
537 // First, use the types from the function type.
538 // We start at 1 here because the first argument (the allocation size)
539 // has already been emitted.
540 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
541 QualType ArgType = NewFTy->getArgType(i);
542
543 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
544 getTypePtr() ==
545 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
546 "type mismatch in call argument!");
547
548 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
549 ArgType));
550
551 }
552
553 // Either we've emitted all the call args, or we have a call to a
554 // variadic function.
555 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
556 "Extra arguments in non-variadic function!");
557
558 // If we still have any arguments, emit them using the type of the argument.
559 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
560 NewArg != NewArgEnd; ++NewArg) {
561 QualType ArgType = NewArg->getType();
562 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
563 ArgType));
564 }
565
566 // Emit the call to new.
567 RValue RV =
568 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
569 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
570 NewArgs, NewFD);
571
Anders Carlsson11269042009-05-31 21:53:59 +0000572 // If an allocation function is declared with an empty exception specification
573 // it returns null to indicate failure to allocate storage. [expr.new]p13.
574 // (We don't need to check for null when there's no new initializer and
575 // we're allocating a POD type).
576 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
577 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000578
Anders Carlssondbee9a52009-06-01 00:05:16 +0000579 llvm::BasicBlock *NewNull = 0;
580 llvm::BasicBlock *NewNotNull = 0;
581 llvm::BasicBlock *NewEnd = 0;
582
583 llvm::Value *NewPtr = RV.getScalarVal();
584
Anders Carlsson11269042009-05-31 21:53:59 +0000585 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000586 NewNull = createBasicBlock("new.null");
587 NewNotNull = createBasicBlock("new.notnull");
588 NewEnd = createBasicBlock("new.end");
589
590 llvm::Value *IsNull =
591 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000592 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000593 "isnull");
594
595 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
596 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000597 }
598
Anders Carlssondbee9a52009-06-01 00:05:16 +0000599 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000600
Anders Carlsson7c294782009-05-31 20:56:36 +0000601 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000602 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000603 assert(E->getNumConstructorArgs() == 1 &&
604 "Can only have one argument to initializer of POD type.");
605
606 const Expr *Init = E->getConstructorArg(0);
607
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000608 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000609 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000610 else if (AllocType->isAnyComplexType())
611 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000612 else
613 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000614 }
Anders Carlsson11269042009-05-31 21:53:59 +0000615 } else {
616 // Call the constructor.
617 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000618
Anders Carlsson11269042009-05-31 21:53:59 +0000619 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
620 E->constructor_arg_begin(),
621 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000622 }
Anders Carlsson11269042009-05-31 21:53:59 +0000623
Anders Carlssondbee9a52009-06-01 00:05:16 +0000624 if (NullCheckResult) {
625 Builder.CreateBr(NewEnd);
626 EmitBlock(NewNull);
627 Builder.CreateBr(NewEnd);
628 EmitBlock(NewEnd);
629
630 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
631 PHI->reserveOperandSpace(2);
632 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000633 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000634
635 NewPtr = PHI;
636 }
637
Anders Carlsson11269042009-05-31 21:53:59 +0000638 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000639}
640
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000641void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
642 if (E->isArrayForm()) {
643 ErrorUnsupported(E, "delete[] expression");
644 return;
645 };
646
647 QualType DeleteTy =
648 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
649
650 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
651
652 // Null check the pointer.
653 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
654 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
655
656 llvm::Value *IsNull =
657 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
658 "isnull");
659
660 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
661 EmitBlock(DeleteNotNull);
662
663 // Call the destructor if necessary.
664 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
665 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
666 if (!RD->hasTrivialDestructor()) {
667 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
668 if (Dtor->isVirtual()) {
669 ErrorUnsupported(E, "delete expression with virtual destructor");
670 return;
671 }
672
673 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
674 }
675 }
676 }
677
678 // Call delete.
679 FunctionDecl *DeleteFD = E->getOperatorDelete();
680 const FunctionProtoType *DeleteFTy =
681 DeleteFD->getType()->getAsFunctionProtoType();
682
683 CallArgList DeleteArgs;
684
685 QualType ArgTy = DeleteFTy->getArgType(0);
686 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
687 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
688
689 // Emit the call to delete.
690 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
691 DeleteArgs),
692 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
693 DeleteArgs, DeleteFD);
694
695 EmitBlock(DeleteEnd);
696}
697
Anders Carlsson4811c302009-04-17 01:58:57 +0000698static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
699 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000700 // The class has base classes - we don't support that right now.
701 if (RD->getNumBases() > 0)
702 return false;
703
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000704 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
705 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000706 // We don't support ctors for fields that aren't POD.
707 if (!I->getType()->isPODType())
708 return false;
709 }
710
711 return true;
712}
713
Anders Carlsson652951a2009-04-15 15:55:24 +0000714void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000715 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000716 ErrorUnsupported(D, "C++ constructor", true);
717 return;
718 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000719
Anders Carlsson1764af42009-05-05 04:44:02 +0000720 EmitGlobal(GlobalDecl(D, Ctor_Complete));
721 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000722}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000723
Anders Carlsson4811c302009-04-17 01:58:57 +0000724void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
725 CXXCtorType Type) {
726
727 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
728
729 CodeGenFunction(*this).GenerateCode(D, Fn);
730
731 SetFunctionDefinitionAttributes(D, Fn);
732 SetLLVMFunctionAttributesForDefinition(D, Fn);
733}
734
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000735llvm::Function *
736CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
737 CXXCtorType Type) {
738 const llvm::FunctionType *FTy =
739 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
740
741 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000742 return cast<llvm::Function>(
743 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000744}
Anders Carlsson4811c302009-04-17 01:58:57 +0000745
746const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
747 CXXCtorType Type) {
748 llvm::SmallString<256> Name;
749 llvm::raw_svector_ostream Out(Name);
750 mangleCXXCtor(D, Type, Context, Out);
751
752 Name += '\0';
753 return UniqueMangledName(Name.begin(), Name.end());
754}
755
756void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
757 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
758 ErrorUnsupported(D, "C++ destructor", true);
759 return;
760 }
761
762 EmitCXXDestructor(D, Dtor_Complete);
763 EmitCXXDestructor(D, Dtor_Base);
764}
765
766void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
767 CXXDtorType Type) {
768 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
769
770 CodeGenFunction(*this).GenerateCode(D, Fn);
771
772 SetFunctionDefinitionAttributes(D, Fn);
773 SetLLVMFunctionAttributesForDefinition(D, Fn);
774}
775
776llvm::Function *
777CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
778 CXXDtorType Type) {
779 const llvm::FunctionType *FTy =
780 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
781
782 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000783 return cast<llvm::Function>(
784 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000785}
786
787const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
788 CXXDtorType Type) {
789 llvm::SmallString<256> Name;
790 llvm::raw_svector_ostream Out(Name);
791 mangleCXXDtor(D, Type, Context, Out);
792
793 Name += '\0';
794 return UniqueMangledName(Name.begin(), Name.end());
795}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000796
Mike Stumpdca5e512009-08-18 21:49:00 +0000797llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000798 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000799 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000800 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000801
802 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000803 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000804
805 llvm::SmallString<256> OutName;
806 llvm::raw_svector_ostream Out(OutName);
807 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000808 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000809 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000810 llvm::GlobalVariable::LinkageTypes linktype;
811 linktype = llvm::GlobalValue::WeakAnyLinkage;
812 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000813 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000814 // FIXME: descriptor
815 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000816 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000817 // FIXME: TS
818 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
819
820 llvm::Constant *C;
821 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
822 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000823 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000824 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000825 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
826 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000827}
828
Mike Stump86a859e2009-08-19 18:10:47 +0000829class VtableBuilder {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000830public:
831 /// Index_t - Vtable index type.
832 typedef uint64_t Index_t;
833private:
Mike Stumpad734d12009-08-18 20:50:28 +0000834 std::vector<llvm::Constant *> &methods;
835 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000836 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000837 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000838 /// BLayout - Layout for the most derived class that this vtable is being
839 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000840 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000841 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000842 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000843 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000844 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000845 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000846 /// Index - Maps a method decl into a vtable index. Useful for virtual
847 /// dispatch codegen.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000848 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpd75d3232009-08-18 22:04:08 +0000849 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000850public:
Mike Stump86a859e2009-08-19 18:10:47 +0000851 VtableBuilder(std::vector<llvm::Constant *> &meth,
852 const CXXRecordDecl *c,
853 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000854 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
855 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
856 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000857 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
858 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000859
Mike Stumpf7d47a52009-08-26 20:46:33 +0000860 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000861 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
862 const CXXRecordDecl *RD,
863 bool VBoundary,
864 bool SecondaryVirtual) {
Mike Stump00962322009-08-21 23:09:30 +0000865 typedef CXXMethodDecl::method_iterator meth_iter;
866 // No vcall for methods that don't override in primary vtables.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000867 llvm::Constant *m = 0;
868
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000869 if (SecondaryVirtual || VBoundary)
870 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000871
872 int64_t Offset = 0;
873 int64_t BaseOffset = 0;
874 for (meth_iter mi = MD->begin_overridden_methods(),
875 me = MD->end_overridden_methods();
876 mi != me; ++mi) {
877 const CXXRecordDecl *DefBase = (*mi)->getParent();
878 // FIXME: vcall: offset for virtual base for this function
879 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
880 // m = llvm::Constant::getNullValue(Ptr8Ty);
881 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
882 e = RD->bases_end(); i != e; ++i) {
883 const CXXRecordDecl *Base =
884 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
885 if (DefBase == Base) {
886 if (!i->isVirtual())
887 break;
888
889 // FIXME: drop the 700-, just for debugging
890 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
891 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
892 BaseOffset);
893 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
894 break;
895 } else {
896 // FIXME: more searching.
897 (void)Offset;
898 }
899 }
900 }
901
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000902 return m;
903 }
904
905 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
906 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000907 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000908
Mike Stumpd75d3232009-08-18 22:04:08 +0000909 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000910 me = RD->method_end(); mi != me; ++mi) {
911 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000912 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
913 if (m)
914 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000915 }
Mike Stumpf640de52009-08-12 23:14:12 +0000916 }
Mike Stump23b238e2009-08-12 23:25:18 +0000917 }
Mike Stumpf640de52009-08-12 23:14:12 +0000918
Mike Stump2b9ba612009-08-20 02:11:48 +0000919 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000920 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000921 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
922 e = RD->bases_end(); i != e; ++i) {
923 const CXXRecordDecl *Base =
924 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
925 if (i->isVirtual() && !SeenVBase.count(Base)) {
926 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000927 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000928 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000929 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000930 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
931 offsets.push_back(m);
932 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000933 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000934 }
935 }
936
Mike Stumpf07ede52009-08-21 01:45:00 +0000937 void StartNewTable() {
938 SeenVBase.clear();
939 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000940
Mike Stumpf7d47a52009-08-26 20:46:33 +0000941 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000942 typedef CXXMethodDecl::method_iterator meth_iter;
943
944 llvm::Constant *m;
945 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
946 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
947
948 // FIXME: Don't like the nested loops. For very large inheritance
949 // heirarchies we could have a table on the side with the final overridder
950 // and just replace each instance of an overridden method once. Would be
951 // nice to measure the cost/benefit on real code.
952
953 // If we can find a previously allocated slot for this, reuse it.
954 for (meth_iter mi = MD->begin_overridden_methods(),
955 e = MD->end_overridden_methods();
956 mi != e; ++mi) {
957 const CXXMethodDecl *OMD = *mi;
958 llvm::Constant *om;
959 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
960 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
961
Mike Stumpf7d47a52009-08-26 20:46:33 +0000962 for (Index_t i = AddressPoint, e = methods.size();
963 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000964 // FIXME: begin_overridden_methods might be too lax, covariance */
965 if (methods[i] == om) {
966 methods[i] = m;
Mike Stumpf7d47a52009-08-26 20:46:33 +0000967 Index[MD] = i - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000968 return;
969 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000970 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000971 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000972
973 // else allocate a new slot.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000974 Index[MD] = methods.size() - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000975 methods.push_back(m);
976 }
977
Mike Stumpf7d47a52009-08-26 20:46:33 +0000978 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000979 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
980 ++mi)
981 if (mi->isVirtual())
Mike Stumpf7d47a52009-08-26 20:46:33 +0000982 AddMethod(*mi, AddressPoint);
Mike Stumpdecd7812009-08-12 23:00:59 +0000983 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000984
Mike Stump00962322009-08-21 23:09:30 +0000985 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
986 bool forPrimary,
987 bool VBoundary,
988 int64_t Offset,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000989 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000990 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000991 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +0000992
Mike Stump7bae1282009-08-18 21:30:21 +0000993 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +0000994 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +0000995
996 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
997 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
998 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
999
Mike Stumpb6ff81e2009-08-19 02:06:38 +00001000 if (VBoundary || forPrimary || ForVirtualBase) {
1001 // then comes the the vcall offsets for all our functions...
1002 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1003 }
1004
Mike Stump7bae1282009-08-18 21:30:21 +00001005 // The virtual base offsets come first...
1006 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +00001007 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +00001008 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +00001009 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +00001010 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1011 e = offsets.rend(); i != e; ++i)
1012 methods.push_back(*i);
1013 }
1014
Mike Stump7bae1282009-08-18 21:30:21 +00001015 bool Top = true;
1016
1017 // vtables are composed from the chain of primaries.
1018 if (PrimaryBase) {
1019 if (PrimaryBaseWasVirtual)
1020 IndirectPrimary.insert(PrimaryBase);
1021 Top = false;
Mike Stumpf7d47a52009-08-26 20:46:33 +00001022 AddressPoint = GenerateVtableForBase(PrimaryBase, true,
1023 PrimaryBaseWasVirtual|VBoundary,
1024 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +00001025 }
1026
1027 if (Top) {
1028 int64_t BaseOffset;
1029 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +00001030 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1031 } else
1032 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +00001033 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1034 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1035 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +00001036 methods.push_back(rtti);
Mike Stump00962322009-08-21 23:09:30 +00001037 AddressPoint = methods.size();
Mike Stumpc57b8272009-08-16 01:46:26 +00001038 }
Mike Stump2eade572009-08-13 22:53:07 +00001039
Mike Stump7bae1282009-08-18 21:30:21 +00001040 // And add the virtuals for the class to the primary vtable.
Mike Stumpf7d47a52009-08-26 20:46:33 +00001041 GenerateMethods(RD, AddressPoint);
Mike Stump7bae1282009-08-18 21:30:21 +00001042
1043 // and then the non-virtual bases.
1044 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1045 e = RD->bases_end(); i != e; ++i) {
1046 if (i->isVirtual())
1047 continue;
1048 const CXXRecordDecl *Base =
1049 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1050 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1051 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001052 StartNewTable();
Mike Stumpf7d47a52009-08-26 20:46:33 +00001053 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001054 }
1055 }
Mike Stump00962322009-08-21 23:09:30 +00001056 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001057 }
1058
1059 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001060 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001061 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1062 e = RD->bases_end(); i != e; ++i) {
1063 const CXXRecordDecl *Base =
1064 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1065 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1066 // Mark it so we don't output it twice.
1067 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001068 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001069 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001070 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001071 }
1072 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001073 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001074 }
1075 }
Mike Stump7bae1282009-08-18 21:30:21 +00001076};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001077
Mike Stumpf7d47a52009-08-26 20:46:33 +00001078class VtableInfo {
1079public:
1080 typedef VtableBuilder::Index_t Index_t;
1081private:
1082 CodeGenModule &CGM; // Per-module state.
1083 /// Index_t - Vtable index type.
1084 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1085 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1086 // FIXME: Move to Context.
1087 static MapTy IndexFor;
1088public:
1089 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1090 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1091 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1092 // We own a copy of this, it will go away shortly.
1093 new ElTy (e);
1094 IndexFor[RD] = new ElTy (e);
1095 }
1096 Index_t lookup(const CXXMethodDecl *MD) {
1097 const CXXRecordDecl *RD = MD->getParent();
1098 MapTy::iterator I = IndexFor.find(RD);
1099 if (I == IndexFor.end()) {
1100 std::vector<llvm::Constant *> methods;
1101 VtableBuilder b(methods, RD, CGM);
1102 b.GenerateVtableForBase(RD, true, false, 0, false);
1103 b.GenerateVtableForVBases(RD, RD);
1104 register_index(RD, b.getIndex());
1105 I = IndexFor.find(RD);
1106 }
1107 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1108 return (*I->second)[MD];
1109 }
1110};
1111
1112// FIXME: Move to Context.
1113VtableInfo::MapTy VtableInfo::IndexFor;
1114
Mike Stump7e8c9932009-07-31 18:25:34 +00001115llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001116 llvm::SmallString<256> OutName;
1117 llvm::raw_svector_ostream Out(OutName);
1118 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001119 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001120 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001121 llvm::GlobalVariable::LinkageTypes linktype;
1122 linktype = llvm::GlobalValue::WeakAnyLinkage;
1123 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001124 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001125 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001126
Mike Stump86a859e2009-08-19 18:10:47 +00001127 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001128
Mike Stumpc57b8272009-08-16 01:46:26 +00001129 // First comes the vtables for all the non-virtual bases...
Mike Stumpf7d47a52009-08-26 20:46:33 +00001130 Offset = b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001131
Mike Stumpc57b8272009-08-16 01:46:26 +00001132 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001133 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001134
Mike Stumpd0672782009-07-31 21:43:43 +00001135 llvm::Constant *C;
1136 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1137 C = llvm::ConstantArray::get(type, methods);
1138 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001139 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001140 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001141 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001142 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001143 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001144 return vtable;
1145}
1146
Mike Stumpf7d47a52009-08-26 20:46:33 +00001147// FIXME: move to Context
1148static VtableInfo *vtableinfo;
1149
1150llvm::Value *
1151CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1152 const llvm::Type *Ty) {
1153 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1154
1155 // FIXME: move to Context
1156 if (vtableinfo == 0)
1157 vtableinfo = new VtableInfo(CGM);
1158
1159 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1160
1161 Ty = llvm::PointerType::get(Ty, 0);
1162 Ty = llvm::PointerType::get(Ty, 0);
1163 Ty = llvm::PointerType::get(Ty, 0);
1164 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1165 vtbl = Builder.CreateLoad(vtbl);
1166 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1167 Idx, "vfn");
1168 vfn = Builder.CreateLoad(vfn);
1169 return vfn;
1170}
1171
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001172/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1173/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1174/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001175// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001176void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1177 llvm::Value *Src,
1178 const ArrayType *Array,
1179 const CXXRecordDecl *BaseClassDecl,
1180 QualType Ty) {
1181 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1182 assert(CA && "VLA cannot be copied over");
1183 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1184
1185 // Create a temporary for the loop index and initialize it with 0.
1186 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1187 "loop.index");
1188 llvm::Value* zeroConstant =
1189 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1190 Builder.CreateStore(zeroConstant, IndexPtr, false);
1191 // Start the loop with a block that tests the condition.
1192 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1193 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1194
1195 EmitBlock(CondBlock);
1196
1197 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1198 // Generate: if (loop-index < number-of-elements fall to the loop body,
1199 // otherwise, go to the block after the for-loop.
1200 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1201 llvm::Value * NumElementsPtr =
1202 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1203 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1204 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1205 "isless");
1206 // If the condition is true, execute the body.
1207 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1208
1209 EmitBlock(ForBody);
1210 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1211 // Inside the loop body, emit the constructor call on the array element.
1212 Counter = Builder.CreateLoad(IndexPtr);
1213 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1214 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1215 if (BitwiseCopy)
1216 EmitAggregateCopy(Dest, Src, Ty);
1217 else if (CXXConstructorDecl *BaseCopyCtor =
1218 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1219 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1220 Ctor_Complete);
1221 CallArgList CallArgs;
1222 // Push the this (Dest) ptr.
1223 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1224 BaseCopyCtor->getThisType(getContext())));
1225
1226 // Push the Src ptr.
1227 CallArgs.push_back(std::make_pair(RValue::get(Src),
1228 BaseCopyCtor->getParamDecl(0)->getType()));
1229 QualType ResultType =
1230 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1231 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1232 Callee, CallArgs, BaseCopyCtor);
1233 }
1234 EmitBlock(ContinueBlock);
1235
1236 // Emit the increment of the loop counter.
1237 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1238 Counter = Builder.CreateLoad(IndexPtr);
1239 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1240 Builder.CreateStore(NextVal, IndexPtr, false);
1241
1242 // Finally, branch back up to the condition for the next iteration.
1243 EmitBranch(CondBlock);
1244
1245 // Emit the fall-through block.
1246 EmitBlock(AfterFor, true);
1247}
1248
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001249/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1250/// array of objects from SrcValue to DestValue. Assignment can be either a
1251/// bitwise assignment or via a copy assignment operator function call.
1252/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1253void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1254 llvm::Value *Src,
1255 const ArrayType *Array,
1256 const CXXRecordDecl *BaseClassDecl,
1257 QualType Ty) {
1258 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1259 assert(CA && "VLA cannot be asssigned");
1260 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1261
1262 // Create a temporary for the loop index and initialize it with 0.
1263 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1264 "loop.index");
1265 llvm::Value* zeroConstant =
1266 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1267 Builder.CreateStore(zeroConstant, IndexPtr, false);
1268 // Start the loop with a block that tests the condition.
1269 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1270 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1271
1272 EmitBlock(CondBlock);
1273
1274 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1275 // Generate: if (loop-index < number-of-elements fall to the loop body,
1276 // otherwise, go to the block after the for-loop.
1277 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1278 llvm::Value * NumElementsPtr =
1279 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1280 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1281 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1282 "isless");
1283 // If the condition is true, execute the body.
1284 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1285
1286 EmitBlock(ForBody);
1287 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1288 // Inside the loop body, emit the assignment operator call on array element.
1289 Counter = Builder.CreateLoad(IndexPtr);
1290 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1291 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1292 const CXXMethodDecl *MD = 0;
1293 if (BitwiseAssign)
1294 EmitAggregateCopy(Dest, Src, Ty);
1295 else {
1296 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1297 MD);
1298 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1299 (void)hasCopyAssign;
1300 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1301 const llvm::Type *LTy =
1302 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1303 FPT->isVariadic());
1304 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1305
1306 CallArgList CallArgs;
1307 // Push the this (Dest) ptr.
1308 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1309 MD->getThisType(getContext())));
1310
1311 // Push the Src ptr.
1312 CallArgs.push_back(std::make_pair(RValue::get(Src),
1313 MD->getParamDecl(0)->getType()));
1314 QualType ResultType =
1315 MD->getType()->getAsFunctionType()->getResultType();
1316 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1317 Callee, CallArgs, MD);
1318 }
1319 EmitBlock(ContinueBlock);
1320
1321 // Emit the increment of the loop counter.
1322 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1323 Counter = Builder.CreateLoad(IndexPtr);
1324 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1325 Builder.CreateStore(NextVal, IndexPtr, false);
1326
1327 // Finally, branch back up to the condition for the next iteration.
1328 EmitBranch(CondBlock);
1329
1330 // Emit the fall-through block.
1331 EmitBlock(AfterFor, true);
1332}
1333
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001334/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1335/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001336/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001337void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001338 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001339 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001340 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1341 if (ClassDecl) {
1342 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1343 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1344 }
1345 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1346 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001347 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001348 }
1349
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001350 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001351 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001352 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1353 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001354 CallArgList CallArgs;
1355 // Push the this (Dest) ptr.
1356 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1357 BaseCopyCtor->getThisType(getContext())));
1358
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001359 // Push the Src ptr.
1360 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001361 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001362 QualType ResultType =
1363 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1364 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1365 Callee, CallArgs, BaseCopyCtor);
1366 }
1367}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001368
Fariborz Jahanian04500242009-08-12 23:34:46 +00001369/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1370/// object from SrcValue to DestValue. Assignment can be either a bitwise
1371/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001372// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001373void CodeGenFunction::EmitClassCopyAssignment(
1374 llvm::Value *Dest, llvm::Value *Src,
1375 const CXXRecordDecl *ClassDecl,
1376 const CXXRecordDecl *BaseClassDecl,
1377 QualType Ty) {
1378 if (ClassDecl) {
1379 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1380 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1381 }
1382 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1383 EmitAggregateCopy(Dest, Src, Ty);
1384 return;
1385 }
1386
1387 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001388 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1389 MD);
1390 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1391 (void)ConstCopyAssignOp;
1392
1393 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1394 const llvm::Type *LTy =
1395 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1396 FPT->isVariadic());
1397 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001398
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001399 CallArgList CallArgs;
1400 // Push the this (Dest) ptr.
1401 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1402 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001403
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001404 // Push the Src ptr.
1405 CallArgs.push_back(std::make_pair(RValue::get(Src),
1406 MD->getParamDecl(0)->getType()));
1407 QualType ResultType =
1408 MD->getType()->getAsFunctionType()->getResultType();
1409 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1410 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001411}
1412
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001413/// SynthesizeDefaultConstructor - synthesize a default constructor
1414void
1415CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1416 const FunctionDecl *FD,
1417 llvm::Function *Fn,
1418 const FunctionArgList &Args) {
1419 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1420 EmitCtorPrologue(CD);
1421 FinishFunction();
1422}
1423
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001424/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001425/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1426/// The implicitly-defined copy constructor for class X performs a memberwise
1427/// copy of its subobjects. The order of copying is the same as the order
1428/// of initialization of bases and members in a user-defined constructor
1429/// Each subobject is copied in the manner appropriate to its type:
1430/// if the subobject is of class type, the copy constructor for the class is
1431/// used;
1432/// if the subobject is an array, each element is copied, in the manner
1433/// appropriate to the element type;
1434/// if the subobject is of scalar type, the built-in assignment operator is
1435/// used.
1436/// Virtual base class subobjects shall be copied only once by the
1437/// implicitly-defined copy constructor
1438
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001439void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1440 const FunctionDecl *FD,
1441 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001442 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001443 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1444 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001445 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1446 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001447
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001448 FunctionArgList::const_iterator i = Args.begin();
1449 const VarDecl *ThisArg = i->first;
1450 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1451 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1452 const VarDecl *SrcArg = (i+1)->first;
1453 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1454 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1455
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001456 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1457 Base != ClassDecl->bases_end(); ++Base) {
1458 // FIXME. copy constrution of virtual base NYI
1459 if (Base->isVirtual())
1460 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001461
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001462 CXXRecordDecl *BaseClassDecl
1463 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001464 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1465 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001466 }
1467
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001468 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1469 FieldEnd = ClassDecl->field_end();
1470 Field != FieldEnd; ++Field) {
1471 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001472 const ConstantArrayType *Array =
1473 getContext().getAsConstantArrayType(FieldType);
1474 if (Array)
1475 FieldType = getContext().getBaseElementType(FieldType);
1476
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001477 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1478 CXXRecordDecl *FieldClassDecl
1479 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1480 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1481 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001482 if (Array) {
1483 const llvm::Type *BasePtr = ConvertType(FieldType);
1484 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1485 llvm::Value *DestBaseAddrPtr =
1486 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1487 llvm::Value *SrcBaseAddrPtr =
1488 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1489 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1490 FieldClassDecl, FieldType);
1491 }
1492 else
1493 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1494 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001495 continue;
1496 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001497 // Do a built-in assignment of scalar data members.
1498 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1499 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1500 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1501 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001502 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001503 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001504}
1505
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001506/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1507/// Before the implicitly-declared copy assignment operator for a class is
1508/// implicitly defined, all implicitly- declared copy assignment operators for
1509/// its direct base classes and its nonstatic data members shall have been
1510/// implicitly defined. [12.8-p12]
1511/// The implicitly-defined copy assignment operator for class X performs
1512/// memberwise assignment of its subob- jects. The direct base classes of X are
1513/// assigned first, in the order of their declaration in
1514/// the base-specifier-list, and then the immediate nonstatic data members of X
1515/// are assigned, in the order in which they were declared in the class
1516/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001517/// if the subobject is of class type, the copy assignment operator for the
1518/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001519/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001520///
1521/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001522/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001523///
1524/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001525/// used.
1526void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1527 const FunctionDecl *FD,
1528 llvm::Function *Fn,
1529 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001530
1531 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1532 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1533 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001534 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1535
Fariborz Jahanian04500242009-08-12 23:34:46 +00001536 FunctionArgList::const_iterator i = Args.begin();
1537 const VarDecl *ThisArg = i->first;
1538 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1539 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1540 const VarDecl *SrcArg = (i+1)->first;
1541 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1542 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1543
1544 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1545 Base != ClassDecl->bases_end(); ++Base) {
1546 // FIXME. copy assignment of virtual base NYI
1547 if (Base->isVirtual())
1548 continue;
1549
1550 CXXRecordDecl *BaseClassDecl
1551 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1552 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1553 Base->getType());
1554 }
1555
1556 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1557 FieldEnd = ClassDecl->field_end();
1558 Field != FieldEnd; ++Field) {
1559 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001560 const ConstantArrayType *Array =
1561 getContext().getAsConstantArrayType(FieldType);
1562 if (Array)
1563 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001564
1565 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1566 CXXRecordDecl *FieldClassDecl
1567 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1568 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1569 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001570 if (Array) {
1571 const llvm::Type *BasePtr = ConvertType(FieldType);
1572 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1573 llvm::Value *DestBaseAddrPtr =
1574 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1575 llvm::Value *SrcBaseAddrPtr =
1576 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1577 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1578 FieldClassDecl, FieldType);
1579 }
1580 else
1581 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1582 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001583 continue;
1584 }
1585 // Do a built-in assignment of scalar data members.
1586 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1587 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1588 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1589 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001590 }
1591
1592 // return *this;
1593 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001594
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001595 FinishFunction();
1596}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001597
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001598/// EmitCtorPrologue - This routine generates necessary code to initialize
1599/// base classes and non-static data members belonging to this constructor.
1600void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001601 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001602 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001603 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001604
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001605 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001606 E = CD->init_end();
1607 B != E; ++B) {
1608 CXXBaseOrMemberInitializer *Member = (*B);
1609 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001610 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001611 Type *BaseType = Member->getBaseClass();
1612 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001613 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001614 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1615 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001616 EmitCXXConstructorCall(Member->getConstructor(),
1617 Ctor_Complete, V,
1618 Member->const_arg_begin(),
1619 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001620 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001621 // non-static data member initilaizers.
1622 FieldDecl *Field = Member->getMember();
1623 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001624 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001625 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001626 if (Array)
1627 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001628
Mike Stump7e8c9932009-07-31 18:25:34 +00001629 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001630 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001631 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001632 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001633 assert(Member->getConstructor() &&
1634 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001635 if (Array) {
1636 const llvm::Type *BasePtr = ConvertType(FieldType);
1637 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1638 llvm::Value *BaseAddrPtr =
1639 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1640 EmitCXXAggrConstructorCall(Member->getConstructor(),
1641 Array, BaseAddrPtr);
1642 }
1643 else
1644 EmitCXXConstructorCall(Member->getConstructor(),
1645 Ctor_Complete, LHS.getAddress(),
1646 Member->const_arg_begin(),
1647 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001648 continue;
1649 }
1650 else {
1651 // Initializing an anonymous union data member.
1652 FieldDecl *anonMember = Member->getAnonUnionMember();
1653 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1654 FieldType = anonMember->getType();
1655 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001656 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001657
1658 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001659 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001660 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001661 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001662 }
1663 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001664
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001665 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001666 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001667 // have bases classes and/or contain non-static data members which require
1668 // construction.
1669 for (CXXRecordDecl::base_class_const_iterator Base =
1670 ClassDecl->bases_begin();
1671 Base != ClassDecl->bases_end(); ++Base) {
1672 // FIXME. copy assignment of virtual base NYI
1673 if (Base->isVirtual())
1674 continue;
1675
1676 CXXRecordDecl *BaseClassDecl
1677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1678 if (BaseClassDecl->hasTrivialConstructor())
1679 continue;
1680 if (CXXConstructorDecl *BaseCX =
1681 BaseClassDecl->getDefaultConstructor(getContext())) {
1682 LoadOfThis = LoadCXXThis();
1683 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1684 BaseClassDecl);
1685 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1686 }
1687 }
1688
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1690 FieldEnd = ClassDecl->field_end();
1691 Field != FieldEnd; ++Field) {
1692 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001693 const ConstantArrayType *Array =
1694 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001695 if (Array)
1696 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001697 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1698 continue;
1699 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001700 CXXRecordDecl *MemberClassDecl =
1701 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1702 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1703 continue;
1704 if (CXXConstructorDecl *MamberCX =
1705 MemberClassDecl->getDefaultConstructor(getContext())) {
1706 LoadOfThis = LoadCXXThis();
1707 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001708 if (Array) {
1709 const llvm::Type *BasePtr = ConvertType(FieldType);
1710 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1711 llvm::Value *BaseAddrPtr =
1712 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1713 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1714 }
1715 else
1716 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1717 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001718 }
1719 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001720 }
1721
Mike Stump7e8c9932009-07-31 18:25:34 +00001722 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001723 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001724 if (!LoadOfThis)
1725 LoadOfThis = LoadCXXThis();
1726 llvm::Value *VtableField;
1727 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001728 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001729 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1730 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1731 llvm::Value *vtable = GenerateVtable(ClassDecl);
1732 Builder.CreateStore(vtable, VtableField);
1733 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001734}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001735
1736/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1737/// destructor. This is to call destructors on members and base classes
1738/// in reverse order of their construction.
1739void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1740 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1741 assert(!ClassDecl->isPolymorphic() &&
1742 "FIXME. polymorphic destruction not supported");
1743 (void)ClassDecl; // prevent warning.
1744
1745 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1746 *E = DD->destr_end(); B != E; ++B) {
1747 uintptr_t BaseOrMember = (*B);
1748 if (DD->isMemberToDestroy(BaseOrMember)) {
1749 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1750 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001751 const ConstantArrayType *Array =
1752 getContext().getAsConstantArrayType(FieldType);
1753 if (Array)
1754 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001755 const RecordType *RT = FieldType->getAs<RecordType>();
1756 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1757 if (FieldClassDecl->hasTrivialDestructor())
1758 continue;
1759 llvm::Value *LoadOfThis = LoadCXXThis();
1760 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001761 if (Array) {
1762 const llvm::Type *BasePtr = ConvertType(FieldType);
1763 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1764 llvm::Value *BaseAddrPtr =
1765 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1766 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1767 Array, BaseAddrPtr);
1768 }
1769 else
1770 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1771 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001772 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001773 const RecordType *RT =
1774 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1775 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1776 if (BaseClassDecl->hasTrivialDestructor())
1777 continue;
1778 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1779 ClassDecl,BaseClassDecl);
1780 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1781 Dtor_Complete, V);
1782 }
1783 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001784 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1785 return;
1786 // Case of destructor synthesis with fields and base classes
1787 // which have non-trivial destructors. They must be destructed in
1788 // reverse order of their construction.
1789 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1790
1791 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1792 FieldEnd = ClassDecl->field_end();
1793 Field != FieldEnd; ++Field) {
1794 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001795 if (getContext().getAsConstantArrayType(FieldType))
1796 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001797 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1798 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1799 if (FieldClassDecl->hasTrivialDestructor())
1800 continue;
1801 DestructedFields.push_back(*Field);
1802 }
1803 }
1804 if (!DestructedFields.empty())
1805 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1806 FieldDecl *Field = DestructedFields[i];
1807 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001808 const ConstantArrayType *Array =
1809 getContext().getAsConstantArrayType(FieldType);
1810 if (Array)
1811 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001812 const RecordType *RT = FieldType->getAs<RecordType>();
1813 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1814 llvm::Value *LoadOfThis = LoadCXXThis();
1815 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001816 if (Array) {
1817 const llvm::Type *BasePtr = ConvertType(FieldType);
1818 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1819 llvm::Value *BaseAddrPtr =
1820 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1821 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1822 Array, BaseAddrPtr);
1823 }
1824 else
1825 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1826 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001827 }
1828
1829 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1830 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1831 Base != ClassDecl->bases_end(); ++Base) {
1832 // FIXME. copy assignment of virtual base NYI
1833 if (Base->isVirtual())
1834 continue;
1835
1836 CXXRecordDecl *BaseClassDecl
1837 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1838 if (BaseClassDecl->hasTrivialDestructor())
1839 continue;
1840 DestructedBases.push_back(BaseClassDecl);
1841 }
1842 if (DestructedBases.empty())
1843 return;
1844 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1845 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1846 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1847 ClassDecl,BaseClassDecl);
1848 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1849 Dtor_Complete, V);
1850 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001851}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001852
1853void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1854 const FunctionDecl *FD,
1855 llvm::Function *Fn,
1856 const FunctionArgList &Args) {
1857
1858 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1859 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1860 "SynthesizeDefaultDestructor - destructor has user declaration");
1861 (void) ClassDecl;
1862
1863 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1864 EmitDtorEpilogue(CD);
1865 FinishFunction();
1866}