blob: 7b492fba17afc8568bb552279343402de77a0b7a [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
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 of classes
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld67ef0e2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000021
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Ken Dyck55c02582011-03-22 00:53:26 +000025static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000030 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000031
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallf871d0c2010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000035 const CXXBaseSpecifier *Base = *I;
36 assert(!Base->isVirtual() && "Should not see virtual bases here!");
37
38 // Get the layout.
39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40
41 const CXXRecordDecl *BaseDecl =
42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43
44 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000045 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
Ken Dyck55c02582011-03-22 00:53:26 +000050 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000051}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000052
Anders Carlsson84080ec2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000055 CastExpr::path_const_iterator PathBegin,
56 CastExpr::path_const_iterator PathEnd) {
57 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000058
Ken Dyck55c02582011-03-22 00:53:26 +000059 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000062 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000063 return 0;
64
Chris Lattner2acc6e32011-07-18 04:24:23 +000065 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000066 Types.ConvertType(getContext().getPointerDiffType());
67
Ken Dyck55c02582011-03-22 00:53:26 +000068 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000069}
70
Anders Carlsson8561a862010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000072/// This should only be used for (1) non-virtual bases or (2) virtual bases
73/// when the type is known to be complete (e.g. in complete destructors).
74///
75/// The object pointed to by 'This' is assumed to be non-null.
76llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000081 // 'this' must be a pointer (in some address space) to Derived.
82 assert(This->getType()->isPointerTy() &&
83 cast<llvm::PointerType>(This->getType())->getElementType()
84 == ConvertType(Derived));
85
86 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000087 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000090 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000092 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000093
94 // Shift and cast down to the base type.
95 // TODO: for complete types, this should be possible with a GEP.
96 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000097 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +000098 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +000099 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000100 }
101 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
102
103 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000104}
John McCallbff225e2010-02-16 04:15:37 +0000105
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000106static llvm::Value *
107ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000108 CharUnits NonVirtual, llvm::Value *Virtual) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000109 llvm::Type *PtrDiffTy =
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000110 CGF.ConvertType(CGF.getContext().getPointerDiffType());
111
112 llvm::Value *NonVirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000113 if (!NonVirtual.isZero())
114 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
115 NonVirtual.getQuantity());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000116
117 llvm::Value *BaseOffset;
118 if (Virtual) {
119 if (NonVirtualOffset)
120 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
121 else
122 BaseOffset = Virtual;
123 } else
124 BaseOffset = NonVirtualOffset;
125
126 // Apply the base offset.
Chris Lattner8b418682012-02-07 00:39:47 +0000127 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000128 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
129
130 return ThisPtr;
131}
132
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000133llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000134CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000135 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000136 CastExpr::path_const_iterator PathBegin,
137 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000138 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000139 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140
John McCallf871d0c2010-08-07 06:22:56 +0000141 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142 const CXXRecordDecl *VBase = 0;
143
144 // Get the virtual base.
145 if ((*Start)->isVirtual()) {
146 VBase =
147 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
148 ++Start;
149 }
150
Ken Dyck55c02582011-03-22 00:53:26 +0000151 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000152 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000153 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000154
155 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000156 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000157 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000158
Ken Dyck55c02582011-03-22 00:53:26 +0000159 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000160 // Just cast back.
161 return Builder.CreateBitCast(Value, BasePtrTy);
162 }
163
164 llvm::BasicBlock *CastNull = 0;
165 llvm::BasicBlock *CastNotNull = 0;
166 llvm::BasicBlock *CastEnd = 0;
167
168 if (NullCheckValue) {
169 CastNull = createBasicBlock("cast.null");
170 CastNotNull = createBasicBlock("cast.notnull");
171 CastEnd = createBasicBlock("cast.end");
172
Anders Carlssonb9241242011-04-11 00:30:07 +0000173 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000174 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
175 EmitBlock(CastNotNull);
176 }
177
178 llvm::Value *VirtualOffset = 0;
179
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000180 if (VBase) {
181 if (Derived->hasAttr<FinalAttr>()) {
182 VirtualOffset = 0;
183
184 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
185
Ken Dyck55c02582011-03-22 00:53:26 +0000186 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
187 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000188 } else
189 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
190 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000191
192 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000193 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000194 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000195 VirtualOffset);
196
197 // Cast back.
198 Value = Builder.CreateBitCast(Value, BasePtrTy);
199
200 if (NullCheckValue) {
201 Builder.CreateBr(CastEnd);
202 EmitBlock(CastNull);
203 Builder.CreateBr(CastEnd);
204 EmitBlock(CastEnd);
205
Jay Foadbbf3bac2011-03-30 11:28:58 +0000206 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000207 PHI->addIncoming(Value, CastNotNull);
208 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
209 CastNull);
210 Value = PHI;
211 }
212
213 return Value;
214}
215
216llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000217CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000218 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000219 CastExpr::path_const_iterator PathBegin,
220 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000221 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000222 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000223
Anders Carlssona3697c92009-11-23 17:57:54 +0000224 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000225 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000226 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlssona3697c92009-11-23 17:57:54 +0000227
Anders Carlssona552ea72010-01-31 01:43:37 +0000228 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000229 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000230
231 if (!NonVirtualOffset) {
232 // No offset, we can just cast back.
233 return Builder.CreateBitCast(Value, DerivedPtrTy);
234 }
235
Anders Carlssona3697c92009-11-23 17:57:54 +0000236 llvm::BasicBlock *CastNull = 0;
237 llvm::BasicBlock *CastNotNull = 0;
238 llvm::BasicBlock *CastEnd = 0;
239
240 if (NullCheckValue) {
241 CastNull = createBasicBlock("cast.null");
242 CastNotNull = createBasicBlock("cast.notnull");
243 CastEnd = createBasicBlock("cast.end");
244
Anders Carlssonb9241242011-04-11 00:30:07 +0000245 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000246 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
247 EmitBlock(CastNotNull);
248 }
249
Anders Carlssona552ea72010-01-31 01:43:37 +0000250 // Apply the offset.
251 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
252 Value = Builder.CreateSub(Value, NonVirtualOffset);
253 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
254
255 // Just cast.
256 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000257
258 if (NullCheckValue) {
259 Builder.CreateBr(CastEnd);
260 EmitBlock(CastNull);
261 Builder.CreateBr(CastEnd);
262 EmitBlock(CastEnd);
263
Jay Foadbbf3bac2011-03-30 11:28:58 +0000264 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000265 PHI->addIncoming(Value, CastNotNull);
266 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
267 CastNull);
268 Value = PHI;
269 }
270
271 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000272}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000273
Anders Carlssonc997d422010-01-02 01:01:18 +0000274/// GetVTTParameter - Return the VTT parameter that should be passed to a
275/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000276static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
277 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000278 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000279 // This constructor/destructor does not need a VTT parameter.
280 return 0;
281 }
282
283 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
284 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000285
Anders Carlssonc997d422010-01-02 01:01:18 +0000286 llvm::Value *VTT;
287
John McCall3b477332010-02-18 19:59:28 +0000288 uint64_t SubVTTIndex;
289
290 // If the record matches the base, this is the complete ctor/dtor
291 // variant calling the base variant in a class with virtual bases.
292 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000293 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000294 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000295 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000296 SubVTTIndex = 0;
297 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000298 const ASTRecordLayout &Layout =
299 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000300 CharUnits BaseOffset = ForVirtualBase ?
301 Layout.getVBaseClassOffset(Base) :
302 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000303
304 SubVTTIndex =
305 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000306 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
307 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000308
Anders Carlssonaf440352010-03-23 04:11:45 +0000309 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000310 // A VTT parameter was passed to the constructor, use it.
311 VTT = CGF.LoadCXXVTT();
312 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
313 } else {
314 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000315 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000316 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
317 }
318
319 return VTT;
320}
321
John McCall182ab512010-07-21 01:23:41 +0000322namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000323 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000324 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000325 const CXXRecordDecl *BaseClass;
326 bool BaseIsVirtual;
327 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
328 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000329
John McCallad346f42011-07-12 20:27:29 +0000330 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000331 const CXXRecordDecl *DerivedClass =
332 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
333
334 const CXXDestructorDecl *D = BaseClass->getDestructor();
335 llvm::Value *Addr =
336 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
337 DerivedClass, BaseClass,
338 BaseIsVirtual);
339 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000340 }
341 };
John McCall7e1dff72010-09-17 02:31:44 +0000342
343 /// A visitor which checks whether an initializer uses 'this' in a
344 /// way which requires the vtable to be properly set.
345 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
346 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
347
348 bool UsesThis;
349
350 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
351
352 // Black-list all explicit and implicit references to 'this'.
353 //
354 // Do we need to worry about external references to 'this' derived
355 // from arbitrary code? If so, then anything which runs arbitrary
356 // external code might potentially access the vtable.
357 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
358 };
359}
360
361static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
362 DynamicThisUseChecker Checker(C);
363 Checker.Visit(const_cast<Expr*>(Init));
364 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000365}
366
Anders Carlsson607d0372009-12-24 22:46:43 +0000367static void EmitBaseInitializer(CodeGenFunction &CGF,
368 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000369 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000370 CXXCtorType CtorType) {
371 assert(BaseInit->isBaseInitializer() &&
372 "Must have base initializer!");
373
374 llvm::Value *ThisPtr = CGF.LoadCXXThis();
375
376 const Type *BaseType = BaseInit->getBaseClass();
377 CXXRecordDecl *BaseClassDecl =
378 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
379
Anders Carlsson80638c52010-04-12 00:51:03 +0000380 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000381
382 // The base constructor doesn't construct virtual bases.
383 if (CtorType == Ctor_Base && isBaseVirtual)
384 return;
385
John McCall7e1dff72010-09-17 02:31:44 +0000386 // If the initializer for the base (other than the constructor
387 // itself) accesses 'this' in any way, we need to initialize the
388 // vtables.
389 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
390 CGF.InitializeVTablePointers(ClassDecl);
391
John McCallbff225e2010-02-16 04:15:37 +0000392 // We can pretend to be a complete class because it only matters for
393 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000394 llvm::Value *V =
395 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000396 BaseClassDecl,
397 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000398 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000399 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000400 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000401 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000402 AggValueSlot::DoesNotNeedGCBarriers,
403 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000404
405 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000406
Anders Carlsson7a178512011-02-28 00:33:03 +0000407 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000408 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000409 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
410 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000411}
412
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000413static void EmitAggMemberInitializer(CodeGenFunction &CGF,
414 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000415 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000416 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000417 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000418 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000419 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000420 if (Index == ArrayIndexes.size()) {
John McCallf1549f62010-07-06 01:34:17 +0000421 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000422
423 LValue LV = LHS;
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000424 if (ArrayIndexVar) {
425 // If we have an array index variable, load it and use it as an offset.
426 // Then, increment the value.
Eli Friedmanf3940782011-12-03 00:54:26 +0000427 llvm::Value *Dest = LHS.getAddress();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000428 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
429 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
430 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
431 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
Eli Friedmanf3940782011-12-03 00:54:26 +0000432 CGF.Builder.CreateStore(Next, ArrayIndexVar);
433
434 // Update the LValue.
435 LV.setAddress(Dest);
Eli Friedman6da2c712011-12-03 04:14:32 +0000436 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
Eli Friedmanf3940782011-12-03 00:54:26 +0000437 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000438 }
John McCall558d2ab2010-09-15 10:14:12 +0000439
John McCallf85e1932011-06-15 23:02:42 +0000440 if (!CGF.hasAggregateLLVMType(T)) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000441 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
John McCallf85e1932011-06-15 23:02:42 +0000442 } else if (T->isAnyComplexType()) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000443 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
Eli Friedmanf3940782011-12-03 00:54:26 +0000444 LV.isVolatileQualified());
445 } else {
John McCall7c2349b2011-08-25 20:40:09 +0000446 AggValueSlot Slot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000447 AggValueSlot::forLValue(LV,
448 AggValueSlot::IsDestructed,
449 AggValueSlot::DoesNotNeedGCBarriers,
450 AggValueSlot::IsNotAliased);
John McCallf85e1932011-06-15 23:02:42 +0000451
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000452 CGF.EmitAggExpr(Init, Slot);
John McCallf85e1932011-06-15 23:02:42 +0000453 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000454
455 return;
456 }
457
458 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
459 assert(Array && "Array initialization without the array type?");
460 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000461 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000462 assert(IndexVar && "Array index variable not loaded");
463
464 // Initialize this index variable to zero.
465 llvm::Value* Zero
466 = llvm::Constant::getNullValue(
467 CGF.ConvertType(CGF.getContext().getSizeType()));
468 CGF.Builder.CreateStore(Zero, IndexVar);
469
470 // Start the loop with a block that tests the condition.
471 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
472 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
473
474 CGF.EmitBlock(CondBlock);
475
476 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
477 // Generate: if (loop-index < number-of-elements) fall to the loop body,
478 // otherwise, go to the block after the for-loop.
479 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000480 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000481 llvm::Value *NumElementsPtr =
482 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000483 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
484 "isless");
485
486 // If the condition is true, execute the body.
487 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
488
489 CGF.EmitBlock(ForBody);
490 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
491
492 {
John McCallf1549f62010-07-06 01:34:17 +0000493 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000494
495 // Inside the loop body recurse to emit the inner loop or, eventually, the
496 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000497 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
498 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000499 }
500
501 CGF.EmitBlock(ContinueBlock);
502
503 // Emit the increment of the loop counter.
504 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
505 Counter = CGF.Builder.CreateLoad(IndexVar);
506 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
507 CGF.Builder.CreateStore(NextVal, IndexVar);
508
509 // Finally, branch back up to the condition for the next iteration.
510 CGF.EmitBranch(CondBlock);
511
512 // Emit the fall-through block.
513 CGF.EmitBlock(AfterFor, true);
514}
John McCall182ab512010-07-21 01:23:41 +0000515
516namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000517 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000518 llvm::Value *V;
John McCall182ab512010-07-21 01:23:41 +0000519 CXXDestructorDecl *Dtor;
520
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000521 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
522 : V(V), Dtor(Dtor) {}
John McCall182ab512010-07-21 01:23:41 +0000523
John McCallad346f42011-07-12 20:27:29 +0000524 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000525 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000526 V);
John McCall182ab512010-07-21 01:23:41 +0000527 }
528 };
529}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000530
531static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
532 bool Moving) {
533 return Moving ? Record->hasTrivialMoveConstructor() :
534 Record->hasTrivialCopyConstructor();
535}
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000536
Anders Carlsson607d0372009-12-24 22:46:43 +0000537static void EmitMemberInitializer(CodeGenFunction &CGF,
538 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000539 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000540 const CXXConstructorDecl *Constructor,
541 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000542 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000543 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000544 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000545
546 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000547 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000548 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000549
550 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000551 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000552
Anders Carlsson607d0372009-12-24 22:46:43 +0000553 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 if (MemberInit->isIndirectMemberInitializer()) {
555 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
556 MemberInit->getIndirectMember(), 0);
557 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000558 } else {
559 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000560 }
561
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000562 // Special case: if we are in a copy or move constructor, and we are copying
563 // an array of PODs or classes with trivial copy constructors, ignore the
564 // AST and perform the copy we know is equivalent.
565 // FIXME: This is hacky at best... if we had a bit more explicit information
566 // in the AST, we could generalize it more easily.
567 const ConstantArrayType *Array
568 = CGF.getContext().getAsConstantArrayType(FieldType);
569 if (Array && Constructor->isImplicitlyDefined() &&
570 Constructor->isCopyOrMoveConstructor()) {
571 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
572 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
573 if (BaseElementTy.isPODType(CGF.getContext()) ||
574 (Record && hasTrivialCopyOrMoveConstructor(Record,
575 Constructor->isMoveConstructor()))) {
576 // Find the source pointer. We knows it's the last argument because
577 // we know we're in a copy constructor.
578 unsigned SrcArgIndex = Args.size() - 1;
579 llvm::Value *SrcPtr
580 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
581 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
582
583 // Copy the aggregate.
584 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
585 LHS.isVolatileQualified());
586 return;
587 }
588 }
589
590 ArrayRef<VarDecl *> ArrayIndexes;
591 if (MemberInit->getNumArrayIndices())
592 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000593 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000594}
595
Eli Friedmanb74ed082012-02-14 02:31:03 +0000596void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
597 LValue LHS, Expr *Init,
598 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000599 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000601 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000602 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000603 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000604 RValue RHS = RValue::get(EmitScalarExpr(Init));
605 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000606 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000607 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000608 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000609 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000610 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000611 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000613
614 // The LHS is a pointer to the first object we'll be constructing, as
615 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000616 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
617 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000618 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000619 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
620 BasePtr);
621 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000622
623 // Create an array index that will be used to walk over all of the
624 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000625 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000626 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000627 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629
630 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000631 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633 }
634
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000636 ArrayIndexes, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000637
Eli Friedmanb74ed082012-02-14 02:31:03 +0000638 if (!CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000639 return;
640
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000641 // FIXME: If we have an array of classes w/ non-trivial destructors,
642 // we need to destroy in reverse order of construction along the exception
643 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000644 const RecordType *RT = FieldType->getAs<RecordType>();
645 if (!RT)
646 return;
647
648 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000649 if (!RD->hasTrivialDestructor())
Eli Friedmanb74ed082012-02-14 02:31:03 +0000650 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
651 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000652 }
653}
654
John McCallc0bf4622010-02-23 00:48:20 +0000655/// Checks whether the given constructor is a valid subject for the
656/// complete-to-base constructor delegation optimization, i.e.
657/// emitting the complete constructor as a simple call to the base
658/// constructor.
659static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
660
661 // Currently we disable the optimization for classes with virtual
662 // bases because (1) the addresses of parameter variables need to be
663 // consistent across all initializers but (2) the delegate function
664 // call necessarily creates a second copy of the parameter variable.
665 //
666 // The limiting example (purely theoretical AFAIK):
667 // struct A { A(int &c) { c++; } };
668 // struct B : virtual A {
669 // B(int count) : A(count) { printf("%d\n", count); }
670 // };
671 // ...although even this example could in principle be emitted as a
672 // delegation since the address of the parameter doesn't escape.
673 if (Ctor->getParent()->getNumVBases()) {
674 // TODO: white-list trivial vbase initializers. This case wouldn't
675 // be subject to the restrictions below.
676
677 // TODO: white-list cases where:
678 // - there are no non-reference parameters to the constructor
679 // - the initializers don't access any non-reference parameters
680 // - the initializers don't take the address of non-reference
681 // parameters
682 // - etc.
683 // If we ever add any of the above cases, remember that:
684 // - function-try-blocks will always blacklist this optimization
685 // - we need to perform the constructor prologue and cleanup in
686 // EmitConstructorBody.
687
688 return false;
689 }
690
691 // We also disable the optimization for variadic functions because
692 // it's impossible to "re-pass" varargs.
693 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
694 return false;
695
Sean Hunt059ce0d2011-05-01 07:04:31 +0000696 // FIXME: Decide if we can do a delegation of a delegating constructor.
697 if (Ctor->isDelegatingConstructor())
698 return false;
699
John McCallc0bf4622010-02-23 00:48:20 +0000700 return true;
701}
702
John McCall9fc6a772010-02-19 09:25:03 +0000703/// EmitConstructorBody - Emits the body of the current constructor.
704void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
705 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
706 CXXCtorType CtorType = CurGD.getCtorType();
707
John McCallc0bf4622010-02-23 00:48:20 +0000708 // Before we go any further, try the complete->base constructor
709 // delegation optimization.
710 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000711 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000712 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000713 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
714 return;
715 }
716
John McCall9fc6a772010-02-19 09:25:03 +0000717 Stmt *Body = Ctor->getBody();
718
John McCallc0bf4622010-02-23 00:48:20 +0000719 // Enter the function-try-block before the constructor prologue if
720 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000721 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000722 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000723 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000724
John McCallf1549f62010-07-06 01:34:17 +0000725 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000726
John McCallc0bf4622010-02-23 00:48:20 +0000727 // Emit the constructor prologue, i.e. the base and member
728 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000729 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000730
731 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000732 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000733 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
734 else if (Body)
735 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000736
737 // Emit any cleanup blocks associated with the member or base
738 // initializers, which includes (along the exceptional path) the
739 // destructors for those members and bases that were fully
740 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000741 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000742
John McCallc0bf4622010-02-23 00:48:20 +0000743 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000744 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000745}
746
Anders Carlsson607d0372009-12-24 22:46:43 +0000747/// EmitCtorPrologue - This routine generates necessary code to initialize
748/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000749void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000750 CXXCtorType CtorType,
751 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000752 if (CD->isDelegatingConstructor())
753 return EmitDelegatingCXXConstructorCall(CD, Args);
754
Anders Carlsson607d0372009-12-24 22:46:43 +0000755 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000756
Chris Lattner5f9e2722011-07-23 10:55:15 +0000757 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000758
Anders Carlsson607d0372009-12-24 22:46:43 +0000759 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
760 E = CD->init_end();
761 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000762 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000763
Sean Huntd49bd552011-05-03 20:19:28 +0000764 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000765 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000766 } else {
767 assert(Member->isAnyMemberInitializer() &&
768 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000769 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000770 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000771 }
772
Anders Carlsson603d6d12010-03-28 21:07:49 +0000773 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000774
John McCallf1549f62010-07-06 01:34:17 +0000775 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000776 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000777}
778
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000779static bool
780FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
781
782static bool
783HasTrivialDestructorBody(ASTContext &Context,
784 const CXXRecordDecl *BaseClassDecl,
785 const CXXRecordDecl *MostDerivedClassDecl)
786{
787 // If the destructor is trivial we don't have to check anything else.
788 if (BaseClassDecl->hasTrivialDestructor())
789 return true;
790
791 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
792 return false;
793
794 // Check fields.
795 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
796 E = BaseClassDecl->field_end(); I != E; ++I) {
797 const FieldDecl *Field = *I;
798
799 if (!FieldHasTrivialDestructorBody(Context, Field))
800 return false;
801 }
802
803 // Check non-virtual bases.
804 for (CXXRecordDecl::base_class_const_iterator I =
805 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
806 I != E; ++I) {
807 if (I->isVirtual())
808 continue;
809
810 const CXXRecordDecl *NonVirtualBase =
811 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
812 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
813 MostDerivedClassDecl))
814 return false;
815 }
816
817 if (BaseClassDecl == MostDerivedClassDecl) {
818 // Check virtual bases.
819 for (CXXRecordDecl::base_class_const_iterator I =
820 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
821 I != E; ++I) {
822 const CXXRecordDecl *VirtualBase =
823 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
824 if (!HasTrivialDestructorBody(Context, VirtualBase,
825 MostDerivedClassDecl))
826 return false;
827 }
828 }
829
830 return true;
831}
832
833static bool
834FieldHasTrivialDestructorBody(ASTContext &Context,
835 const FieldDecl *Field)
836{
837 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
838
839 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
840 if (!RT)
841 return true;
842
843 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
844 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
845}
846
Anders Carlssonffb945f2011-05-14 23:26:09 +0000847/// CanSkipVTablePointerInitialization - Check whether we need to initialize
848/// any vtable pointers before calling this destructor.
849static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000850 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000851 if (!Dtor->hasTrivialBody())
852 return false;
853
854 // Check the fields.
855 const CXXRecordDecl *ClassDecl = Dtor->getParent();
856 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
857 E = ClassDecl->field_end(); I != E; ++I) {
858 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000859
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000860 if (!FieldHasTrivialDestructorBody(Context, Field))
861 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000862 }
863
864 return true;
865}
866
John McCall9fc6a772010-02-19 09:25:03 +0000867/// EmitDestructorBody - Emits the body of the current destructor.
868void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
869 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
870 CXXDtorType DtorType = CurGD.getDtorType();
871
John McCall50da2ca2010-07-21 05:30:47 +0000872 // The call to operator delete in a deleting destructor happens
873 // outside of the function-try-block, which means it's always
874 // possible to delegate the destructor body to the complete
875 // destructor. Do so.
876 if (DtorType == Dtor_Deleting) {
877 EnterDtorCleanups(Dtor, Dtor_Deleting);
878 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
879 LoadCXXThis());
880 PopCleanupBlock();
881 return;
882 }
883
John McCall9fc6a772010-02-19 09:25:03 +0000884 Stmt *Body = Dtor->getBody();
885
886 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000887 // anything else.
888 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000889 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000890 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000891
John McCall50da2ca2010-07-21 05:30:47 +0000892 // Enter the epilogue cleanups.
893 RunCleanupsScope DtorEpilogue(*this);
894
John McCall9fc6a772010-02-19 09:25:03 +0000895 // If this is the complete variant, just invoke the base variant;
896 // the epilogue will destruct the virtual bases. But we can't do
897 // this optimization if the body is a function-try-block, because
898 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000899 switch (DtorType) {
900 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
901
902 case Dtor_Complete:
903 // Enter the cleanup scopes for virtual bases.
904 EnterDtorCleanups(Dtor, Dtor_Complete);
905
906 if (!isTryBody) {
907 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
908 LoadCXXThis());
909 break;
910 }
911 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000912
John McCall50da2ca2010-07-21 05:30:47 +0000913 case Dtor_Base:
914 // Enter the cleanup scopes for fields and non-virtual bases.
915 EnterDtorCleanups(Dtor, Dtor_Base);
916
917 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000918 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
919 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000920
921 if (isTryBody)
922 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
923 else if (Body)
924 EmitStmt(Body);
925 else {
926 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
927 // nothing to do besides what's in the epilogue
928 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000929 // -fapple-kext must inline any call to this dtor into
930 // the caller's body.
931 if (getContext().getLangOptions().AppleKext)
932 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000933 break;
John McCall9fc6a772010-02-19 09:25:03 +0000934 }
935
John McCall50da2ca2010-07-21 05:30:47 +0000936 // Jump out through the epilogue cleanups.
937 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000938
939 // Exit the try if applicable.
940 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000941 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000942}
943
John McCall50da2ca2010-07-21 05:30:47 +0000944namespace {
945 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000946 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000947 CallDtorDelete() {}
948
John McCallad346f42011-07-12 20:27:29 +0000949 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000950 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
951 const CXXRecordDecl *ClassDecl = Dtor->getParent();
952 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
953 CGF.getContext().getTagDeclType(ClassDecl));
954 }
955 };
956
John McCall9928c482011-07-12 16:41:08 +0000957 class DestroyField : public EHScopeStack::Cleanup {
958 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000959 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +0000960 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000961
John McCall9928c482011-07-12 16:41:08 +0000962 public:
963 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
964 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000965 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +0000966 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000967
John McCallad346f42011-07-12 20:27:29 +0000968 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000969 // Find the address of the field.
970 llvm::Value *thisValue = CGF.LoadCXXThis();
971 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
972 assert(LV.isSimple());
973
974 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000975 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +0000976 }
977 };
978}
979
Anders Carlsson607d0372009-12-24 22:46:43 +0000980/// EmitDtorEpilogue - Emit all code that comes at the end of class's
981/// destructor. This is to call destructors on members and base classes
982/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000983void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
984 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000985 assert(!DD->isTrivial() &&
986 "Should not emit dtor epilogue for trivial dtor!");
987
John McCall50da2ca2010-07-21 05:30:47 +0000988 // The deleting-destructor phase just needs to call the appropriate
989 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000990 if (DtorType == Dtor_Deleting) {
991 assert(DD->getOperatorDelete() &&
992 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000993 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000994 return;
995 }
996
John McCall50da2ca2010-07-21 05:30:47 +0000997 const CXXRecordDecl *ClassDecl = DD->getParent();
998
Richard Smith416f63e2011-09-18 12:11:43 +0000999 // Unions have no bases and do not call field destructors.
1000 if (ClassDecl->isUnion())
1001 return;
1002
John McCall50da2ca2010-07-21 05:30:47 +00001003 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001004 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001005
1006 // We push them in the forward order so that they'll be popped in
1007 // the reverse order.
1008 for (CXXRecordDecl::base_class_const_iterator I =
1009 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001010 I != E; ++I) {
1011 const CXXBaseSpecifier &Base = *I;
1012 CXXRecordDecl *BaseClassDecl
1013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1014
1015 // Ignore trivial destructors.
1016 if (BaseClassDecl->hasTrivialDestructor())
1017 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001018
John McCall1f0fca52010-07-21 07:22:38 +00001019 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1020 BaseClassDecl,
1021 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001022 }
John McCall50da2ca2010-07-21 05:30:47 +00001023
John McCall3b477332010-02-18 19:59:28 +00001024 return;
1025 }
1026
1027 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001028
1029 // Destroy non-virtual bases.
1030 for (CXXRecordDecl::base_class_const_iterator I =
1031 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1032 const CXXBaseSpecifier &Base = *I;
1033
1034 // Ignore virtual bases.
1035 if (Base.isVirtual())
1036 continue;
1037
1038 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1039
1040 // Ignore trivial destructors.
1041 if (BaseClassDecl->hasTrivialDestructor())
1042 continue;
John McCall3b477332010-02-18 19:59:28 +00001043
John McCall1f0fca52010-07-21 07:22:38 +00001044 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1045 BaseClassDecl,
1046 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001047 }
1048
1049 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001050 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001051 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1052 E = ClassDecl->field_end(); I != E; ++I) {
John McCall9928c482011-07-12 16:41:08 +00001053 const FieldDecl *field = *I;
1054 QualType type = field->getType();
1055 QualType::DestructionKind dtorKind = type.isDestructedType();
1056 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001057
John McCall9928c482011-07-12 16:41:08 +00001058 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1059 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1060 getDestroyer(dtorKind),
1061 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001062 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001063}
1064
John McCallc3c07662011-07-13 06:10:41 +00001065/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1066/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001067///
John McCallc3c07662011-07-13 06:10:41 +00001068/// \param ctor the constructor to call for each element
1069/// \param argBegin,argEnd the arguments to evaluate and pass to the
1070/// constructor
1071/// \param arrayType the type of the array to initialize
1072/// \param arrayBegin an arrayType*
1073/// \param zeroInitialize true if each element should be
1074/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001075void
John McCallc3c07662011-07-13 06:10:41 +00001076CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1077 const ConstantArrayType *arrayType,
1078 llvm::Value *arrayBegin,
1079 CallExpr::const_arg_iterator argBegin,
1080 CallExpr::const_arg_iterator argEnd,
1081 bool zeroInitialize) {
1082 QualType elementType;
1083 llvm::Value *numElements =
1084 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001085
John McCallc3c07662011-07-13 06:10:41 +00001086 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1087 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001088}
1089
John McCallc3c07662011-07-13 06:10:41 +00001090/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1091/// constructor for each of several members of an array.
1092///
1093/// \param ctor the constructor to call for each element
1094/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001095/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001096/// \param argBegin,argEnd the arguments to evaluate and pass to the
1097/// constructor
1098/// \param arrayBegin a T*, where T is the type constructed by ctor
1099/// \param zeroInitialize true if each element should be
1100/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001101void
John McCallc3c07662011-07-13 06:10:41 +00001102CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1103 llvm::Value *numElements,
1104 llvm::Value *arrayBegin,
1105 CallExpr::const_arg_iterator argBegin,
1106 CallExpr::const_arg_iterator argEnd,
1107 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001108
1109 // It's legal for numElements to be zero. This can happen both
1110 // dynamically, because x can be zero in 'new A[x]', and statically,
1111 // because of GCC extensions that permit zero-length arrays. There
1112 // are probably legitimate places where we could assume that this
1113 // doesn't happen, but it's not clear that it's worth it.
1114 llvm::BranchInst *zeroCheckBranch = 0;
1115
1116 // Optimize for a constant count.
1117 llvm::ConstantInt *constantCount
1118 = dyn_cast<llvm::ConstantInt>(numElements);
1119 if (constantCount) {
1120 // Just skip out if the constant count is zero.
1121 if (constantCount->isZero()) return;
1122
1123 // Otherwise, emit the check.
1124 } else {
1125 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1126 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1127 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1128 EmitBlock(loopBB);
1129 }
1130
John McCallc3c07662011-07-13 06:10:41 +00001131 // Find the end of the array.
1132 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1133 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001134
John McCallc3c07662011-07-13 06:10:41 +00001135 // Enter the loop, setting up a phi for the current location to initialize.
1136 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1137 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1138 EmitBlock(loopBB);
1139 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1140 "arrayctor.cur");
1141 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001142
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001143 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001144
1145 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001146
Douglas Gregor59174c02010-07-21 01:10:17 +00001147 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001148 if (zeroInitialize)
1149 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001150
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001151 // C++ [class.temporary]p4:
1152 // There are two contexts in which temporaries are destroyed at a different
1153 // point than the end of the full-expression. The first context is when a
1154 // default constructor is called to initialize an element of an array.
1155 // If the constructor has one or more default arguments, the destruction of
1156 // every temporary created in a default argument expression is sequenced
1157 // before the construction of the next array element, if any.
1158
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001159 {
John McCallf1549f62010-07-06 01:34:17 +00001160 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001161
John McCallc3c07662011-07-13 06:10:41 +00001162 // Evaluate the constructor and its arguments in a regular
1163 // partial-destroy cleanup.
1164 if (getLangOptions().Exceptions &&
1165 !ctor->getParent()->hasTrivialDestructor()) {
1166 Destroyer *destroyer = destroyCXXObject;
1167 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1168 }
1169
1170 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1171 cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001172 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001173
John McCallc3c07662011-07-13 06:10:41 +00001174 // Go to the next element.
1175 llvm::Value *next =
1176 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1177 "arrayctor.next");
1178 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001179
John McCallc3c07662011-07-13 06:10:41 +00001180 // Check whether that's the end of the loop.
1181 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1182 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1183 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001184
John McCalldd376ca2011-07-13 07:37:11 +00001185 // Patch the earlier check to skip over the loop.
1186 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1187
John McCallc3c07662011-07-13 06:10:41 +00001188 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001189}
1190
John McCallbdc4d802011-07-09 01:37:26 +00001191void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1192 llvm::Value *addr,
1193 QualType type) {
1194 const RecordType *rtype = type->castAs<RecordType>();
1195 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1196 const CXXDestructorDecl *dtor = record->getDestructor();
1197 assert(!dtor->isTrivial());
1198 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1199 addr);
1200}
1201
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001202void
1203CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001204 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001205 llvm::Value *This,
1206 CallExpr::const_arg_iterator ArgBeg,
1207 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001208
1209 CGDebugInfo *DI = getDebugInfo();
1210 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001211 // If debug info for this class has not been emitted then this is the
1212 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001213 const CXXRecordDecl *Parent = D->getParent();
1214 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1215 Parent->getLocation());
1216 }
1217
John McCall8b6bbeb2010-02-06 00:25:16 +00001218 if (D->isTrivial()) {
1219 if (ArgBeg == ArgEnd) {
1220 // Trivial default constructor, no codegen required.
1221 assert(D->isDefaultConstructor() &&
1222 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001223 return;
1224 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001225
1226 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001227 assert(D->isCopyOrMoveConstructor() &&
1228 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001229
John McCall8b6bbeb2010-02-06 00:25:16 +00001230 const Expr *E = (*ArgBeg);
1231 QualType Ty = E->getType();
1232 llvm::Value *Src = EmitLValue(E).getAddress();
1233 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001234 return;
1235 }
1236
Anders Carlsson314e6222010-05-02 23:33:10 +00001237 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001238 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1239
Anders Carlssonc997d422010-01-02 01:01:18 +00001240 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001241}
1242
John McCallc0bf4622010-02-23 00:48:20 +00001243void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001244CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1245 llvm::Value *This, llvm::Value *Src,
1246 CallExpr::const_arg_iterator ArgBeg,
1247 CallExpr::const_arg_iterator ArgEnd) {
1248 if (D->isTrivial()) {
1249 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001250 assert(D->isCopyOrMoveConstructor() &&
1251 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001252 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1253 return;
1254 }
1255 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1256 clang::Ctor_Complete);
1257 assert(D->isInstance() &&
1258 "Trying to emit a member call expr on a static method!");
1259
1260 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1261
1262 CallArgList Args;
1263
1264 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001265 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001266
1267
1268 // Push the src ptr.
1269 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001270 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001271 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001272 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001273
1274 // Skip over first argument (Src).
1275 ++ArgBeg;
1276 CallExpr::const_arg_iterator Arg = ArgBeg;
1277 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1278 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1279 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001280 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001281 }
1282 // Either we've emitted all the call args, or we have a call to a
1283 // variadic function.
1284 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1285 "Extra arguments in non-variadic function!");
1286 // If we still have any arguments, emit them using the type of the argument.
1287 for (; Arg != ArgEnd; ++Arg) {
1288 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001289 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001290 }
1291
John McCallde5d3c72012-02-17 03:33:10 +00001292 EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Eli Friedmanc55db3b2011-08-09 17:38:12 +00001293 ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001294}
1295
1296void
John McCallc0bf4622010-02-23 00:48:20 +00001297CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1298 CXXCtorType CtorType,
1299 const FunctionArgList &Args) {
1300 CallArgList DelegateArgs;
1301
1302 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1303 assert(I != E && "no parameters to constructor");
1304
1305 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001306 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001307 ++I;
1308
1309 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001310 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1311 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001312 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001313 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001314
Anders Carlssonaf440352010-03-23 04:11:45 +00001315 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001316 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001317 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001318 ++I;
1319 }
1320 }
1321
1322 // Explicit arguments.
1323 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001324 const VarDecl *param = *I;
1325 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001326 }
1327
John McCallde5d3c72012-02-17 03:33:10 +00001328 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001329 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1330 ReturnValueSlot(), DelegateArgs, Ctor);
1331}
1332
Sean Huntb76af9c2011-05-03 23:05:34 +00001333namespace {
1334 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1335 const CXXDestructorDecl *Dtor;
1336 llvm::Value *Addr;
1337 CXXDtorType Type;
1338
1339 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1340 CXXDtorType Type)
1341 : Dtor(D), Addr(Addr), Type(Type) {}
1342
John McCallad346f42011-07-12 20:27:29 +00001343 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001344 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1345 Addr);
1346 }
1347 };
1348}
1349
Sean Hunt059ce0d2011-05-01 07:04:31 +00001350void
1351CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1352 const FunctionArgList &Args) {
1353 assert(Ctor->isDelegatingConstructor());
1354
1355 llvm::Value *ThisPtr = LoadCXXThis();
1356
Eli Friedmanf3940782011-12-03 00:54:26 +00001357 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001358 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001359 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001360 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001361 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001362 AggValueSlot::DoesNotNeedGCBarriers,
1363 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001364
1365 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001366
Sean Huntb76af9c2011-05-03 23:05:34 +00001367 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1368 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1369 CXXDtorType Type =
1370 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1371
1372 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1373 ClassDecl->getDestructor(),
1374 ThisPtr, Type);
1375 }
1376}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001377
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001378void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1379 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001380 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001381 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001382 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1383 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001384 llvm::Value *Callee = 0;
1385 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001386 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1387 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001388
1389 if (!Callee)
1390 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001391
Anders Carlssonc997d422010-01-02 01:01:18 +00001392 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001393}
1394
John McCall291ae942010-07-21 01:41:18 +00001395namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001396 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001397 const CXXDestructorDecl *Dtor;
1398 llvm::Value *Addr;
1399
1400 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1401 : Dtor(D), Addr(Addr) {}
1402
John McCallad346f42011-07-12 20:27:29 +00001403 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001404 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1405 /*ForVirtualBase=*/false, Addr);
1406 }
1407 };
1408}
1409
John McCall81407d42010-07-21 06:29:51 +00001410void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1411 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001412 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001413}
1414
John McCallf1549f62010-07-06 01:34:17 +00001415void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1416 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1417 if (!ClassDecl) return;
1418 if (ClassDecl->hasTrivialDestructor()) return;
1419
1420 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001421 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001422 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001423}
1424
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001425llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001426CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1427 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001428 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001429 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001430 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001431 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001432
1433 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001434 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1435 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001436 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001437 ConvertType(getContext().getPointerDiffType());
1438
1439 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1440 PtrDiffTy->getPointerTo());
1441
1442 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1443
1444 return VBaseOffset;
1445}
1446
Anders Carlssond103f9f2010-03-28 19:40:00 +00001447void
1448CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001449 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001450 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001451 llvm::Constant *VTable,
1452 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001453 const CXXRecordDecl *RD = Base.getBase();
1454
Anders Carlssond103f9f2010-03-28 19:40:00 +00001455 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001456 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001457
Anders Carlssonc83f1062010-03-29 01:08:49 +00001458 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001459 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001460 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001461 // Get the secondary vpointer index.
1462 uint64_t VirtualPointerIndex =
1463 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1464
1465 /// Load the VTT.
1466 llvm::Value *VTT = LoadCXXVTT();
1467 if (VirtualPointerIndex)
1468 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1469
1470 // And load the address point from the VTT.
1471 VTableAddressPoint = Builder.CreateLoad(VTT);
1472 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001473 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001474 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001475 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001476 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001477 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001478
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001479 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001480 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001481 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001482
1483 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1484 // We need to use the virtual base offset offset because the virtual base
1485 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001486 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1487 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001488 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001489 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001490 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001491 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001492 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001493
1494 // Apply the offsets.
1495 llvm::Value *VTableField = LoadCXXThis();
1496
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001497 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001498 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1499 NonVirtualOffset,
1500 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001501
Anders Carlssond103f9f2010-03-28 19:40:00 +00001502 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001503 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001504 VTableAddressPoint->getType()->getPointerTo();
1505 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1506 Builder.CreateStore(VTableAddressPoint, VTableField);
1507}
1508
Anders Carlsson603d6d12010-03-28 21:07:49 +00001509void
1510CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001511 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001512 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001513 bool BaseIsNonVirtualPrimaryBase,
1514 llvm::Constant *VTable,
1515 const CXXRecordDecl *VTableClass,
1516 VisitedVirtualBasesSetTy& VBases) {
1517 // If this base is a non-virtual primary base the address point has already
1518 // been set.
1519 if (!BaseIsNonVirtualPrimaryBase) {
1520 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001521 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1522 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001523 }
1524
1525 const CXXRecordDecl *RD = Base.getBase();
1526
1527 // Traverse bases.
1528 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1529 E = RD->bases_end(); I != E; ++I) {
1530 CXXRecordDecl *BaseDecl
1531 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1532
1533 // Ignore classes without a vtable.
1534 if (!BaseDecl->isDynamicClass())
1535 continue;
1536
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001537 CharUnits BaseOffset;
1538 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001539 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001540
1541 if (I->isVirtual()) {
1542 // Check if we've visited this virtual base before.
1543 if (!VBases.insert(BaseDecl))
1544 continue;
1545
1546 const ASTRecordLayout &Layout =
1547 getContext().getASTRecordLayout(VTableClass);
1548
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001549 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1550 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001551 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001552 } else {
1553 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1554
Ken Dyck4230d522011-03-24 01:21:01 +00001555 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001556 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001557 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001558 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001559 }
1560
Ken Dyck4230d522011-03-24 01:21:01 +00001561 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001562 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001563 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001564 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001565 VTable, VTableClass, VBases);
1566 }
1567}
1568
1569void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1570 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001571 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001572 return;
1573
Anders Carlsson07036902010-03-26 04:39:42 +00001574 // Get the VTable.
1575 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001576
Anders Carlsson603d6d12010-03-28 21:07:49 +00001577 // Initialize the vtable pointers for this class and all of its bases.
1578 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001579 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1580 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001581 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001582 /*BaseIsNonVirtualPrimaryBase=*/false,
1583 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001584}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001585
1586llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001587 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001588 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1589 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1590}
Anders Carlssona2447e02011-05-08 20:32:23 +00001591
1592static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1593 const Expr *E = Base;
1594
1595 while (true) {
1596 E = E->IgnoreParens();
1597 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1598 if (CE->getCastKind() == CK_DerivedToBase ||
1599 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1600 CE->getCastKind() == CK_NoOp) {
1601 E = CE->getSubExpr();
1602 continue;
1603 }
1604 }
1605
1606 break;
1607 }
1608
1609 QualType DerivedType = E->getType();
1610 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1611 DerivedType = PTy->getPointeeType();
1612
1613 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1614}
1615
1616// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1617// quite what we want.
1618static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1619 while (true) {
1620 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1621 E = PE->getSubExpr();
1622 continue;
1623 }
1624
1625 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1626 if (CE->getCastKind() == CK_NoOp) {
1627 E = CE->getSubExpr();
1628 continue;
1629 }
1630 }
1631 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1632 if (UO->getOpcode() == UO_Extension) {
1633 E = UO->getSubExpr();
1634 continue;
1635 }
1636 }
1637 return E;
1638 }
1639}
1640
1641/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1642/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00001643static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1644 const CXXMethodDecl *MD) {
1645 // If the most derived class is marked final, we know that no subclass can
1646 // override this member function and so we can devirtualize it. For example:
1647 //
1648 // struct A { virtual void f(); }
1649 // struct B final : A { };
1650 //
1651 // void f(B *b) {
1652 // b->f();
1653 // }
1654 //
1655 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1656 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1657 return true;
1658
1659 // If the member function is marked 'final', we know that it can't be
1660 // overridden and can therefore devirtualize it.
1661 if (MD->hasAttr<FinalAttr>())
1662 return true;
1663
1664 // Similarly, if the class itself is marked 'final' it can't be overridden
1665 // and we can therefore devirtualize the member function call.
1666 if (MD->getParent()->hasAttr<FinalAttr>())
1667 return true;
1668
1669 Base = skipNoOpCastsAndParens(Base);
1670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1671 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1672 // This is a record decl. We know the type and can devirtualize it.
1673 return VD->getType()->isRecordType();
1674 }
1675
1676 return false;
1677 }
1678
1679 // We can always devirtualize calls on temporary object expressions.
1680 if (isa<CXXConstructExpr>(Base))
1681 return true;
1682
1683 // And calls on bound temporaries.
1684 if (isa<CXXBindTemporaryExpr>(Base))
1685 return true;
1686
1687 // Check if this is a call expr that returns a record type.
1688 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1689 return CE->getCallReturnType()->isRecordType();
1690
1691 // We can't devirtualize the call.
1692 return false;
1693}
1694
1695static bool UseVirtualCall(ASTContext &Context,
1696 const CXXOperatorCallExpr *CE,
1697 const CXXMethodDecl *MD) {
1698 if (!MD->isVirtual())
1699 return false;
1700
1701 // When building with -fapple-kext, all calls must go through the vtable since
1702 // the kernel linker can do runtime patching of vtables.
1703 if (Context.getLangOptions().AppleKext)
1704 return true;
1705
1706 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1707}
1708
1709llvm::Value *
1710CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1711 const CXXMethodDecl *MD,
1712 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00001713 llvm::FunctionType *fnType =
1714 CGM.getTypes().GetFunctionType(
1715 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00001716
1717 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00001718 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001719
John McCallde5d3c72012-02-17 03:33:10 +00001720 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001721}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001722
1723void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1724 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to block");
1725}
1726
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001727void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1728 const CXXRecordDecl *Lambda = MD->getParent();
Eli Friedman21f6ed92012-02-16 03:47:28 +00001729 DeclarationName Name
1730 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
1731 DeclContext::lookup_const_result Calls = Lambda->lookup(Name);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001732 CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001733 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1734 QualType ResultType = FPT->getResultType();
1735
Eli Friedman21f6ed92012-02-16 03:47:28 +00001736 // Start building arguments for forwarding call
1737 CallArgList CallArgs;
1738
1739 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1740 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1741 CallArgs.add(RValue::get(ThisPtr), ThisType);
1742
1743 // Add the rest of the parameters.
1744 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1745 E = MD->param_end(); I != E; ++I) {
1746 ParmVarDecl *param = *I;
1747 EmitDelegateCallArg(CallArgs, param);
1748 }
1749
1750 // Get the address of the call operator.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001751 GlobalDecl GD(CallOperator);
John McCallde5d3c72012-02-17 03:33:10 +00001752 const CGFunctionInfo &CalleeFnInfo =
1753 CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(),
1754 RequiredArgs::forPrototypePlus(FPT, 1));
1755 llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001756 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
1757
1758 // Determine whether we have a return value slot to use.
1759 ReturnValueSlot Slot;
1760 if (!ResultType->isVoidType() &&
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001761 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
Eli Friedman21f6ed92012-02-16 03:47:28 +00001762 hasAggregateLLVMType(CurFnInfo->getReturnType()))
1763 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
1764
1765 // Now emit our call.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001766 RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001767
1768 // Forward the returned value
1769 if (!ResultType->isVoidType() && Slot.isNull())
1770 EmitReturnOfRValue(RV, ResultType);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001771}
1772
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001773void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1774 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00001775 // FIXME: Making this work correctly is nasty because it requires either
1776 // cloning the body of the call operator or making the call operator forward.
1777 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman21f6ed92012-02-16 03:47:28 +00001778 }
1779
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001780 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001781}