blob: d5c5fd23222d2b4c2e7488d92e83056fbd32e0fa [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
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hames56c00c42013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000018#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000020#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000021#include "clang/AST/StmtCXX.h"
Lang Hames56c00c42013-02-17 07:22:09 +000022#include "clang/Basic/TargetBuiltins.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000023#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000024
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000025using namespace clang;
26using namespace CodeGen;
27
Ken Dyck55c02582011-03-22 00:53:26 +000028static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000029ComputeNonVirtualBaseClassOffset(ASTContext &Context,
30 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000031 CastExpr::path_const_iterator Start,
32 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000033 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000034
35 const CXXRecordDecl *RD = DerivedClass;
36
John McCallf871d0c2010-08-07 06:22:56 +000037 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000038 const CXXBaseSpecifier *Base = *I;
39 assert(!Base->isVirtual() && "Should not see virtual bases here!");
40
41 // Get the layout.
42 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
43
44 const CXXRecordDecl *BaseDecl =
45 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
46
47 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000048 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000049
50 RD = BaseDecl;
51 }
52
Ken Dyck55c02582011-03-22 00:53:26 +000053 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000054}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000055
Anders Carlsson84080ec2009-09-29 03:13:20 +000056llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000057CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000058 CastExpr::path_const_iterator PathBegin,
59 CastExpr::path_const_iterator PathEnd) {
60 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000061
Ken Dyck55c02582011-03-22 00:53:26 +000062 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000063 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
64 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000065 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000066 return 0;
67
Chris Lattner2acc6e32011-07-18 04:24:23 +000068 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000069 Types.ConvertType(getContext().getPointerDiffType());
70
Ken Dyck55c02582011-03-22 00:53:26 +000071 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000072}
73
Anders Carlsson8561a862010-04-24 23:01:49 +000074/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000075/// This should only be used for (1) non-virtual bases or (2) virtual bases
76/// when the type is known to be complete (e.g. in complete destructors).
77///
78/// The object pointed to by 'This' is assumed to be non-null.
79llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000080CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
81 const CXXRecordDecl *Derived,
82 const CXXRecordDecl *Base,
83 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000084 // 'this' must be a pointer (in some address space) to Derived.
85 assert(This->getType()->isPointerTy() &&
86 cast<llvm::PointerType>(This->getType())->getElementType()
87 == ConvertType(Derived));
88
89 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000090 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000091 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000092 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000093 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000094 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000095 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000096
97 // Shift and cast down to the base type.
98 // TODO: for complete types, this should be possible with a GEP.
99 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +0000101 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000102 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000103 }
104 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
105
106 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000107}
John McCallbff225e2010-02-16 04:15:37 +0000108
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000109static llvm::Value *
John McCall7916c992012-08-01 05:04:58 +0000110ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
111 CharUnits nonVirtualOffset,
112 llvm::Value *virtualOffset) {
113 // Assert that we have something to do.
114 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
115
116 // Compute the offset from the static and dynamic components.
117 llvm::Value *baseOffset;
118 if (!nonVirtualOffset.isZero()) {
119 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
120 nonVirtualOffset.getQuantity());
121 if (virtualOffset) {
122 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
123 }
124 } else {
125 baseOffset = virtualOffset;
126 }
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000127
128 // Apply the base offset.
John McCall7916c992012-08-01 05:04:58 +0000129 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
130 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
131 return ptr;
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000132}
133
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000134llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000135CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000136 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000137 CastExpr::path_const_iterator PathBegin,
138 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000140 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141
John McCallf871d0c2010-08-07 06:22:56 +0000142 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143 const CXXRecordDecl *VBase = 0;
144
John McCall7916c992012-08-01 05:04:58 +0000145 // Sema has done some convenient canonicalization here: if the
146 // access path involved any virtual steps, the conversion path will
147 // *start* with a step down to the correct virtual base subobject,
148 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000149 if ((*Start)->isVirtual()) {
150 VBase =
151 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
152 ++Start;
153 }
John McCall7916c992012-08-01 05:04:58 +0000154
155 // Compute the static offset of the ultimate destination within its
156 // allocating subobject (the virtual base, if there is one, or else
157 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000158 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000159 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000160 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000161
John McCall7916c992012-08-01 05:04:58 +0000162 // If there's a virtual step, we can sometimes "devirtualize" it.
163 // For now, that's limited to when the derived type is final.
164 // TODO: "devirtualize" this for accesses to known-complete objects.
165 if (VBase && Derived->hasAttr<FinalAttr>()) {
166 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
167 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
168 NonVirtualOffset += vBaseOffset;
169 VBase = 0; // we no longer have a virtual step
170 }
171
Anders Carlsson34a2d382010-04-24 21:06:20 +0000172 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000173 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000174 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000175
176 // If the static offset is zero and we don't have a virtual step,
177 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000178 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000179 return Builder.CreateBitCast(Value, BasePtrTy);
180 }
John McCall7916c992012-08-01 05:04:58 +0000181
182 llvm::BasicBlock *origBB = 0;
183 llvm::BasicBlock *endBB = 0;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000184
John McCall7916c992012-08-01 05:04:58 +0000185 // Skip over the offset (and the vtable load) if we're supposed to
186 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000187 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000188 origBB = Builder.GetInsertBlock();
189 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
190 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000191
John McCall7916c992012-08-01 05:04:58 +0000192 llvm::Value *isNull = Builder.CreateIsNull(Value);
193 Builder.CreateCondBr(isNull, endBB, notNullBB);
194 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000195 }
196
John McCall7916c992012-08-01 05:04:58 +0000197 // Compute the virtual offset.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000198 llvm::Value *VirtualOffset = 0;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000199 if (VBase) {
John McCall7916c992012-08-01 05:04:58 +0000200 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000201 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000202
John McCall7916c992012-08-01 05:04:58 +0000203 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000204 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000205 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000206 VirtualOffset);
207
John McCall7916c992012-08-01 05:04:58 +0000208 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000209 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000210
211 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000212 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000213 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
214 Builder.CreateBr(endBB);
215 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000216
John McCall7916c992012-08-01 05:04:58 +0000217 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
218 PHI->addIncoming(Value, notNullBB);
219 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000220 Value = PHI;
221 }
222
223 return Value;
224}
225
226llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000227CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000228 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000229 CastExpr::path_const_iterator PathBegin,
230 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000231 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000232 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000233
Anders Carlssona3697c92009-11-23 17:57:54 +0000234 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000235 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000236 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000237
Anders Carlssona552ea72010-01-31 01:43:37 +0000238 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000239 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000240
241 if (!NonVirtualOffset) {
242 // No offset, we can just cast back.
243 return Builder.CreateBitCast(Value, DerivedPtrTy);
244 }
245
Anders Carlssona3697c92009-11-23 17:57:54 +0000246 llvm::BasicBlock *CastNull = 0;
247 llvm::BasicBlock *CastNotNull = 0;
248 llvm::BasicBlock *CastEnd = 0;
249
250 if (NullCheckValue) {
251 CastNull = createBasicBlock("cast.null");
252 CastNotNull = createBasicBlock("cast.notnull");
253 CastEnd = createBasicBlock("cast.end");
254
Anders Carlssonb9241242011-04-11 00:30:07 +0000255 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000256 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
257 EmitBlock(CastNotNull);
258 }
259
Anders Carlssona552ea72010-01-31 01:43:37 +0000260 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000261 Value = Builder.CreateBitCast(Value, Int8PtrTy);
262 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
263 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000264
265 // Just cast.
266 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000267
268 if (NullCheckValue) {
269 Builder.CreateBr(CastEnd);
270 EmitBlock(CastNull);
271 Builder.CreateBr(CastEnd);
272 EmitBlock(CastEnd);
273
Jay Foadbbf3bac2011-03-30 11:28:58 +0000274 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000275 PHI->addIncoming(Value, CastNotNull);
276 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
277 CastNull);
278 Value = PHI;
279 }
280
281 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000282}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000283
Anders Carlssonc997d422010-01-02 01:01:18 +0000284/// GetVTTParameter - Return the VTT parameter that should be passed to a
285/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000286static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000287 bool ForVirtualBase,
288 bool Delegating) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000289 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000290 // This constructor/destructor does not need a VTT parameter.
291 return 0;
292 }
293
294 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
295 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000296
Anders Carlssonc997d422010-01-02 01:01:18 +0000297 llvm::Value *VTT;
298
John McCall3b477332010-02-18 19:59:28 +0000299 uint64_t SubVTTIndex;
300
Douglas Gregor378e1e72013-01-31 05:50:40 +0000301 if (Delegating) {
302 // If this is a delegating constructor call, just load the VTT.
303 return CGF.LoadCXXVTT();
304 } else if (RD == Base) {
305 // If the record matches the base, this is the complete ctor/dtor
306 // variant calling the base variant in a class with virtual bases.
Anders Carlssonaf440352010-03-23 04:11:45 +0000307 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000308 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000309 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000310 SubVTTIndex = 0;
311 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000312 const ASTRecordLayout &Layout =
313 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000314 CharUnits BaseOffset = ForVirtualBase ?
315 Layout.getVBaseClassOffset(Base) :
316 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000317
318 SubVTTIndex =
319 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000320 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
321 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000322
Anders Carlssonaf440352010-03-23 04:11:45 +0000323 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000324 // A VTT parameter was passed to the constructor, use it.
325 VTT = CGF.LoadCXXVTT();
326 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
327 } else {
328 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000329 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000330 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
331 }
332
333 return VTT;
334}
335
John McCall182ab512010-07-21 01:23:41 +0000336namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000337 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000338 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000339 const CXXRecordDecl *BaseClass;
340 bool BaseIsVirtual;
341 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
342 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000343
John McCallad346f42011-07-12 20:27:29 +0000344 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000345 const CXXRecordDecl *DerivedClass =
346 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
347
348 const CXXDestructorDecl *D = BaseClass->getDestructor();
349 llvm::Value *Addr =
350 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
351 DerivedClass, BaseClass,
352 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000353 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
354 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000355 }
356 };
John McCall7e1dff72010-09-17 02:31:44 +0000357
358 /// A visitor which checks whether an initializer uses 'this' in a
359 /// way which requires the vtable to be properly set.
360 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
361 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
362
363 bool UsesThis;
364
365 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
366
367 // Black-list all explicit and implicit references to 'this'.
368 //
369 // Do we need to worry about external references to 'this' derived
370 // from arbitrary code? If so, then anything which runs arbitrary
371 // external code might potentially access the vtable.
372 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
373 };
374}
375
376static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
377 DynamicThisUseChecker Checker(C);
378 Checker.Visit(const_cast<Expr*>(Init));
379 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000380}
381
Anders Carlsson607d0372009-12-24 22:46:43 +0000382static void EmitBaseInitializer(CodeGenFunction &CGF,
383 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000384 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000385 CXXCtorType CtorType) {
386 assert(BaseInit->isBaseInitializer() &&
387 "Must have base initializer!");
388
389 llvm::Value *ThisPtr = CGF.LoadCXXThis();
390
391 const Type *BaseType = BaseInit->getBaseClass();
392 CXXRecordDecl *BaseClassDecl =
393 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
394
Anders Carlsson80638c52010-04-12 00:51:03 +0000395 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000396
397 // The base constructor doesn't construct virtual bases.
398 if (CtorType == Ctor_Base && isBaseVirtual)
399 return;
400
John McCall7e1dff72010-09-17 02:31:44 +0000401 // If the initializer for the base (other than the constructor
402 // itself) accesses 'this' in any way, we need to initialize the
403 // vtables.
404 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
405 CGF.InitializeVTablePointers(ClassDecl);
406
John McCallbff225e2010-02-16 04:15:37 +0000407 // We can pretend to be a complete class because it only matters for
408 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000409 llvm::Value *V =
410 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000411 BaseClassDecl,
412 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000413 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000414 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000415 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000416 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000417 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000418 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000419
420 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000421
David Blaikie4e4d0842012-03-11 07:00:24 +0000422 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000423 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000424 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
425 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000426}
427
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000428static void EmitAggMemberInitializer(CodeGenFunction &CGF,
429 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000430 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000431 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000432 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000433 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000434 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000435 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000436 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000437 { // Scope for Cleanups.
438 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000439
Sebastian Redl924db712012-02-19 15:41:54 +0000440 if (ArrayIndexVar) {
441 // If we have an array index variable, load it and use it as an offset.
442 // Then, increment the value.
443 llvm::Value *Dest = LHS.getAddress();
444 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
445 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
446 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
447 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
448 CGF.Builder.CreateStore(Next, ArrayIndexVar);
449
450 // Update the LValue.
451 LV.setAddress(Dest);
452 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
453 LV.setAlignment(std::min(Align, LV.getAlignment()));
454 }
455
456 if (!CGF.hasAggregateLLVMType(T)) {
457 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
458 } else if (T->isAnyComplexType()) {
459 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
460 LV.isVolatileQualified());
461 } else {
462 AggValueSlot Slot =
463 AggValueSlot::forLValue(LV,
464 AggValueSlot::IsDestructed,
465 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000466 AggValueSlot::IsNotAliased);
Sebastian Redl924db712012-02-19 15:41:54 +0000467
468 CGF.EmitAggExpr(Init, Slot);
469 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000470 }
John McCall558d2ab2010-09-15 10:14:12 +0000471
Sebastian Redl924db712012-02-19 15:41:54 +0000472 // Now, outside of the initializer cleanup scope, destroy the backing array
473 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000474 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000475
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000476 return;
477 }
478
479 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
480 assert(Array && "Array initialization without the array type?");
481 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000482 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000483 assert(IndexVar && "Array index variable not loaded");
484
485 // Initialize this index variable to zero.
486 llvm::Value* Zero
487 = llvm::Constant::getNullValue(
488 CGF.ConvertType(CGF.getContext().getSizeType()));
489 CGF.Builder.CreateStore(Zero, IndexVar);
490
491 // Start the loop with a block that tests the condition.
492 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
493 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
494
495 CGF.EmitBlock(CondBlock);
496
497 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
498 // Generate: if (loop-index < number-of-elements) fall to the loop body,
499 // otherwise, go to the block after the for-loop.
500 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000501 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000502 llvm::Value *NumElementsPtr =
503 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000504 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
505 "isless");
506
507 // If the condition is true, execute the body.
508 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
509
510 CGF.EmitBlock(ForBody);
511 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
512
513 {
John McCallf1549f62010-07-06 01:34:17 +0000514 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000515
516 // Inside the loop body recurse to emit the inner loop or, eventually, the
517 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000518 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
519 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000520 }
521
522 CGF.EmitBlock(ContinueBlock);
523
524 // Emit the increment of the loop counter.
525 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
526 Counter = CGF.Builder.CreateLoad(IndexVar);
527 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
528 CGF.Builder.CreateStore(NextVal, IndexVar);
529
530 // Finally, branch back up to the condition for the next iteration.
531 CGF.EmitBranch(CondBlock);
532
533 // Emit the fall-through block.
534 CGF.EmitBlock(AfterFor, true);
535}
John McCall182ab512010-07-21 01:23:41 +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();
Eli Friedman377ecc72012-04-16 03:54:45 +0000551 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000552 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000553
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000555 // If we are initializing an anonymous union field, drill down to
556 // the field.
557 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
558 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
559 IEnd = IndirectField->chain_end();
560 for ( ; I != IEnd; ++I)
561 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000562 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000563 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000564 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000565 }
566
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000567 // Special case: if we are in a copy or move constructor, and we are copying
568 // an array of PODs or classes with trivial copy constructors, ignore the
569 // AST and perform the copy we know is equivalent.
570 // FIXME: This is hacky at best... if we had a bit more explicit information
571 // in the AST, we could generalize it more easily.
572 const ConstantArrayType *Array
573 = CGF.getContext().getAsConstantArrayType(FieldType);
574 if (Array && Constructor->isImplicitlyDefined() &&
575 Constructor->isCopyOrMoveConstructor()) {
576 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000577 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000578 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000579 (CE && CE->getConstructor()->isTrivial())) {
580 // Find the source pointer. We know it's the last argument because
581 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000582 unsigned SrcArgIndex = Args.size() - 1;
583 llvm::Value *SrcPtr
584 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000585 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
586 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000587
588 // Copy the aggregate.
589 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000590 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000591 return;
592 }
593 }
594
595 ArrayRef<VarDecl *> ArrayIndexes;
596 if (MemberInit->getNumArrayIndices())
597 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000598 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000599}
600
Eli Friedmanb74ed082012-02-14 02:31:03 +0000601void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
602 LValue LHS, Expr *Init,
603 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000604 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000605 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000606 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000607 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000608 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000609 RValue RHS = RValue::get(EmitScalarExpr(Init));
610 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000611 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000612 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000613 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000614 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000615 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000616 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000617 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000618
619 // The LHS is a pointer to the first object we'll be constructing, as
620 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000621 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
622 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000624 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
625 BasePtr);
626 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000627
628 // Create an array index that will be used to walk over all of the
629 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000630 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000631 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000634
635 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000636 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000637 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000638 }
639
Eli Friedmanb74ed082012-02-14 02:31:03 +0000640 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000641 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000642 }
John McCall074cae02013-02-01 05:11:40 +0000643
644 // Ensure that we destroy this object if an exception is thrown
645 // later in the constructor.
646 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
647 if (needsEHCleanup(dtorKind))
648 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000649}
650
John McCallc0bf4622010-02-23 00:48:20 +0000651/// Checks whether the given constructor is a valid subject for the
652/// complete-to-base constructor delegation optimization, i.e.
653/// emitting the complete constructor as a simple call to the base
654/// constructor.
655static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
656
657 // Currently we disable the optimization for classes with virtual
658 // bases because (1) the addresses of parameter variables need to be
659 // consistent across all initializers but (2) the delegate function
660 // call necessarily creates a second copy of the parameter variable.
661 //
662 // The limiting example (purely theoretical AFAIK):
663 // struct A { A(int &c) { c++; } };
664 // struct B : virtual A {
665 // B(int count) : A(count) { printf("%d\n", count); }
666 // };
667 // ...although even this example could in principle be emitted as a
668 // delegation since the address of the parameter doesn't escape.
669 if (Ctor->getParent()->getNumVBases()) {
670 // TODO: white-list trivial vbase initializers. This case wouldn't
671 // be subject to the restrictions below.
672
673 // TODO: white-list cases where:
674 // - there are no non-reference parameters to the constructor
675 // - the initializers don't access any non-reference parameters
676 // - the initializers don't take the address of non-reference
677 // parameters
678 // - etc.
679 // If we ever add any of the above cases, remember that:
680 // - function-try-blocks will always blacklist this optimization
681 // - we need to perform the constructor prologue and cleanup in
682 // EmitConstructorBody.
683
684 return false;
685 }
686
687 // We also disable the optimization for variadic functions because
688 // it's impossible to "re-pass" varargs.
689 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
690 return false;
691
Sean Hunt059ce0d2011-05-01 07:04:31 +0000692 // FIXME: Decide if we can do a delegation of a delegating constructor.
693 if (Ctor->isDelegatingConstructor())
694 return false;
695
John McCallc0bf4622010-02-23 00:48:20 +0000696 return true;
697}
698
John McCall9fc6a772010-02-19 09:25:03 +0000699/// EmitConstructorBody - Emits the body of the current constructor.
700void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
701 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
702 CXXCtorType CtorType = CurGD.getCtorType();
703
John McCallc0bf4622010-02-23 00:48:20 +0000704 // Before we go any further, try the complete->base constructor
705 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000706 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallb8b2c9d2013-01-25 22:30:49 +0000707 CGM.getContext().getTargetInfo().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000708 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000709 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000710 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
711 return;
712 }
713
John McCall9fc6a772010-02-19 09:25:03 +0000714 Stmt *Body = Ctor->getBody();
715
John McCallc0bf4622010-02-23 00:48:20 +0000716 // Enter the function-try-block before the constructor prologue if
717 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000718 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000719 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000720 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000721
John McCallf1549f62010-07-06 01:34:17 +0000722 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000723
John McCall56ea3772012-03-30 04:25:03 +0000724 // TODO: in restricted cases, we can emit the vbase initializers of
725 // a complete ctor and then delegate to the base ctor.
726
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
Lang Hames56c00c42013-02-17 07:22:09 +0000747namespace {
748 class FieldMemcpyizer {
749 public:
750 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
751 const VarDecl *SrcRec)
752 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
753 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
754 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
755 LastAddedFieldIndex(0) { }
756
757 static bool isMemcpyableField(FieldDecl *F) {
758 Qualifiers Qual = F->getType().getQualifiers();
759 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
760 return false;
761 return true;
762 }
763
764 void addMemcpyableField(FieldDecl *F) {
765 if (FirstField == 0)
766 addInitialField(F);
767 else
768 addNextField(F);
769 }
770
771 CharUnits getMemcpySize() const {
772 unsigned LastFieldSize =
773 LastField->isBitField() ?
774 LastField->getBitWidthValue(CGF.getContext()) :
775 CGF.getContext().getTypeSize(LastField->getType());
776 uint64_t MemcpySizeBits =
777 LastFieldOffset + LastFieldSize - FirstFieldOffset +
778 CGF.getContext().getCharWidth() - 1;
779 CharUnits MemcpySize =
780 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
781 return MemcpySize;
782 }
783
784 void emitMemcpy() {
785 // Give the subclass a chance to bail out if it feels the memcpy isn't
786 // worth it (e.g. Hasn't aggregated enough data).
787 if (FirstField == 0) {
788 return;
789 }
790
791 unsigned FirstFieldAlign = ~0U; // Set to invalid.
792
793 if (FirstField->isBitField()) {
794 const CGRecordLayout &RL =
795 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
796 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
797 FirstFieldAlign = BFInfo.StorageAlignment;
798 } else
799 FirstFieldAlign = CGF.getContext().getTypeAlign(FirstField->getType());
800
801 assert(FirstFieldOffset % FirstFieldAlign == 0 && "Bad field alignment.");
802 CharUnits Alignment =
803 CGF.getContext().toCharUnitsFromBits(FirstFieldAlign);
804 CharUnits MemcpySize = getMemcpySize();
805 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
806 llvm::Value *ThisPtr = CGF.LoadCXXThis();
807 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
808 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
809 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
810 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
811 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
812
813 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
814 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
815 MemcpySize, Alignment);
816 reset();
817 }
818
819 void reset() {
820 FirstField = 0;
821 }
822
823 protected:
824 CodeGenFunction &CGF;
825 const CXXRecordDecl *ClassDecl;
826
827 private:
828
829 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
830 CharUnits Size, CharUnits Alignment) {
831 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
832 llvm::Type *DBP =
833 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
834 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
835
836 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
837 llvm::Type *SBP =
838 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
839 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
840
841 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
842 Alignment.getQuantity());
843 }
844
845 void addInitialField(FieldDecl *F) {
846 FirstField = F;
847 LastField = F;
848 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
849 LastFieldOffset = FirstFieldOffset;
850 LastAddedFieldIndex = F->getFieldIndex();
851 return;
852 }
853
854 void addNextField(FieldDecl *F) {
855 assert(F->getFieldIndex() == LastAddedFieldIndex + 1 &&
856 "Cannot aggregate non-contiguous fields.");
857 LastAddedFieldIndex = F->getFieldIndex();
858
859 // The 'first' and 'last' fields are chosen by offset, rather than field
860 // index. This allows the code to support bitfields, as well as regular
861 // fields.
862 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
863 if (FOffset < FirstFieldOffset) {
864 FirstField = F;
865 FirstFieldOffset = FOffset;
866 } else if (FOffset > LastFieldOffset) {
867 LastField = F;
868 LastFieldOffset = FOffset;
869 }
870 }
871
872 const VarDecl *SrcRec;
873 const ASTRecordLayout &RecLayout;
874 FieldDecl *FirstField;
875 FieldDecl *LastField;
876 uint64_t FirstFieldOffset, LastFieldOffset;
877 unsigned LastAddedFieldIndex;
878 };
879
880 class ConstructorMemcpyizer : public FieldMemcpyizer {
881 private:
882
883 /// Get source argument for copy constructor. Returns null if not a copy
884 /// constructor.
885 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
886 FunctionArgList &Args) {
887 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
888 return Args[Args.size() - 1];
889 return 0;
890 }
891
892 // Returns true if a CXXCtorInitializer represents a member initialization
893 // that can be rolled into a memcpy.
894 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
895 if (!MemcpyableCtor)
896 return false;
897 FieldDecl *Field = MemberInit->getMember();
898 assert(Field != 0 && "No field for member init.");
899 QualType FieldType = Field->getType();
900 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
901
902 // Bail out on non-POD, not-trivially-constructable members.
903 if (!(CE && CE->getConstructor()->isTrivial()) &&
904 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
905 FieldType->isReferenceType()))
906 return false;
907
908 // Bail out on volatile fields.
909 if (!isMemcpyableField(Field))
910 return false;
911
912 // Otherwise we're good.
913 return true;
914 }
915
916 public:
917 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
918 FunctionArgList &Args)
919 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
920 ConstructorDecl(CD),
921 MemcpyableCtor(CD->isImplicitlyDefined() &&
922 CD->isCopyOrMoveConstructor() &&
923 CGF.getLangOpts().getGC() == LangOptions::NonGC),
924 Args(Args) { }
925
926 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
927 if (isMemberInitMemcpyable(MemberInit)) {
928 AggregatedInits.push_back(MemberInit);
929 addMemcpyableField(MemberInit->getMember());
930 } else {
931 emitAggregatedInits();
932 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
933 ConstructorDecl, Args);
934 }
935 }
936
937 void emitAggregatedInits() {
938 if (AggregatedInits.size() <= 1) {
939 // This memcpy is too small to be worthwhile. Fall back on default
940 // codegen.
941 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
942 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
943 AggregatedInits[i], ConstructorDecl, Args);
944 }
945 reset();
946 return;
947 }
948
949 pushEHDestructors();
950 emitMemcpy();
951 AggregatedInits.clear();
952 }
953
954 void pushEHDestructors() {
955 llvm::Value *ThisPtr = CGF.LoadCXXThis();
956 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
957 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
958
959 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
960 QualType FieldType = AggregatedInits[i]->getMember()->getType();
961 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
962 if (CGF.needsEHCleanup(dtorKind))
963 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
964 }
965 }
966
967 void finish() {
968 emitAggregatedInits();
969 }
970
971 private:
972 const CXXConstructorDecl *ConstructorDecl;
973 bool MemcpyableCtor;
974 FunctionArgList &Args;
975 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
976 };
977
978 class AssignmentMemcpyizer : public FieldMemcpyizer {
979 private:
980
981 // Returns the memcpyable field copied by the given statement, if one
982 // exists. Otherwise r
983 FieldDecl* getMemcpyableField(Stmt *S) {
984 if (!AssignmentsMemcpyable)
985 return 0;
986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
987 // Recognise trivial assignments.
988 if (BO->getOpcode() != BO_Assign)
989 return 0;
990 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
991 if (!ME)
992 return 0;
993 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
994 if (!Field || !isMemcpyableField(Field))
995 return 0;
996 Stmt *RHS = BO->getRHS();
997 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
998 RHS = EC->getSubExpr();
999 if (!RHS)
1000 return 0;
1001 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1002 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1003 return 0;
1004 return Field;
1005 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1006 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1007 if (!(MD && (MD->isCopyAssignmentOperator() ||
1008 MD->isMoveAssignmentOperator()) &&
1009 MD->isTrivial()))
1010 return 0;
1011 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1012 if (!IOA)
1013 return 0;
1014 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1015 if (!Field || !isMemcpyableField(Field))
1016 return 0;
1017 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1018 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1019 return 0;
1020 return Field;
1021 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1022 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1023 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1024 return 0;
1025 Expr *DstPtr = CE->getArg(0);
1026 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1027 DstPtr = DC->getSubExpr();
1028 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1029 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1030 return 0;
1031 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1032 if (!ME)
1033 return 0;
1034 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1035 if (!Field || !isMemcpyableField(Field))
1036 return 0;
1037 Expr *SrcPtr = CE->getArg(1);
1038 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1039 SrcPtr = SC->getSubExpr();
1040 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1041 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1042 return 0;
1043 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1044 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1045 return 0;
1046 return Field;
1047 }
1048
1049 return 0;
1050 }
1051
1052 bool AssignmentsMemcpyable;
1053 SmallVector<Stmt*, 16> AggregatedStmts;
1054
1055 public:
1056
1057 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1058 FunctionArgList &Args)
1059 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1060 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1061 assert(Args.size() == 2);
1062 }
1063
1064 void emitAssignment(Stmt *S) {
1065 FieldDecl *F = getMemcpyableField(S);
1066 if (F) {
1067 addMemcpyableField(F);
1068 AggregatedStmts.push_back(S);
1069 } else {
1070 emitAggregatedStmts();
1071 CGF.EmitStmt(S);
1072 }
1073 }
1074
1075 void emitAggregatedStmts() {
1076 if (AggregatedStmts.size() <= 1) {
1077 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1078 CGF.EmitStmt(AggregatedStmts[i]);
1079 reset();
1080 }
1081
1082 emitMemcpy();
1083 AggregatedStmts.clear();
1084 }
1085
1086 void finish() {
1087 emitAggregatedStmts();
1088 }
1089 };
1090
1091}
1092
Anders Carlsson607d0372009-12-24 22:46:43 +00001093/// EmitCtorPrologue - This routine generates necessary code to initialize
1094/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001095void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001096 CXXCtorType CtorType,
1097 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001098 if (CD->isDelegatingConstructor())
1099 return EmitDelegatingCXXConstructorCall(CD, Args);
1100
Anders Carlsson607d0372009-12-24 22:46:43 +00001101 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001102
Chris Lattner5f9e2722011-07-23 10:55:15 +00001103 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +00001104
Anders Carlsson607d0372009-12-24 22:46:43 +00001105 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1106 E = CD->init_end();
1107 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +00001108 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +00001109
Sean Huntd49bd552011-05-03 20:19:28 +00001110 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001111 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +00001112 } else {
1113 assert(Member->isAnyMemberInitializer() &&
1114 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001115 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +00001116 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001117 }
1118
Anders Carlsson603d6d12010-03-28 21:07:49 +00001119 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001120
Lang Hames56c00c42013-02-17 07:22:09 +00001121 ConstructorMemcpyizer CM(*this, CD, Args);
John McCallf1549f62010-07-06 01:34:17 +00001122 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Lang Hames56c00c42013-02-17 07:22:09 +00001123 CM.addMemberInitializer(MemberInitializers[I]);
1124 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001125}
1126
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001127static bool
1128FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1129
1130static bool
1131HasTrivialDestructorBody(ASTContext &Context,
1132 const CXXRecordDecl *BaseClassDecl,
1133 const CXXRecordDecl *MostDerivedClassDecl)
1134{
1135 // If the destructor is trivial we don't have to check anything else.
1136 if (BaseClassDecl->hasTrivialDestructor())
1137 return true;
1138
1139 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1140 return false;
1141
1142 // Check fields.
1143 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1144 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001145 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001146
1147 if (!FieldHasTrivialDestructorBody(Context, Field))
1148 return false;
1149 }
1150
1151 // Check non-virtual bases.
1152 for (CXXRecordDecl::base_class_const_iterator I =
1153 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1154 I != E; ++I) {
1155 if (I->isVirtual())
1156 continue;
1157
1158 const CXXRecordDecl *NonVirtualBase =
1159 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1160 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1161 MostDerivedClassDecl))
1162 return false;
1163 }
1164
1165 if (BaseClassDecl == MostDerivedClassDecl) {
1166 // Check virtual bases.
1167 for (CXXRecordDecl::base_class_const_iterator I =
1168 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1169 I != E; ++I) {
1170 const CXXRecordDecl *VirtualBase =
1171 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1172 if (!HasTrivialDestructorBody(Context, VirtualBase,
1173 MostDerivedClassDecl))
1174 return false;
1175 }
1176 }
1177
1178 return true;
1179}
1180
1181static bool
1182FieldHasTrivialDestructorBody(ASTContext &Context,
1183 const FieldDecl *Field)
1184{
1185 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1186
1187 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1188 if (!RT)
1189 return true;
1190
1191 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1192 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1193}
1194
Anders Carlssonffb945f2011-05-14 23:26:09 +00001195/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1196/// any vtable pointers before calling this destructor.
1197static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001198 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001199 if (!Dtor->hasTrivialBody())
1200 return false;
1201
1202 // Check the fields.
1203 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1204 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1205 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001206 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001207
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001208 if (!FieldHasTrivialDestructorBody(Context, Field))
1209 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001210 }
1211
1212 return true;
1213}
1214
John McCall9fc6a772010-02-19 09:25:03 +00001215/// EmitDestructorBody - Emits the body of the current destructor.
1216void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1217 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1218 CXXDtorType DtorType = CurGD.getDtorType();
1219
John McCall50da2ca2010-07-21 05:30:47 +00001220 // The call to operator delete in a deleting destructor happens
1221 // outside of the function-try-block, which means it's always
1222 // possible to delegate the destructor body to the complete
1223 // destructor. Do so.
1224 if (DtorType == Dtor_Deleting) {
1225 EnterDtorCleanups(Dtor, Dtor_Deleting);
1226 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001227 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001228 PopCleanupBlock();
1229 return;
1230 }
1231
John McCall9fc6a772010-02-19 09:25:03 +00001232 Stmt *Body = Dtor->getBody();
1233
1234 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001235 // anything else.
1236 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001237 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001238 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001239
John McCall50da2ca2010-07-21 05:30:47 +00001240 // Enter the epilogue cleanups.
1241 RunCleanupsScope DtorEpilogue(*this);
1242
John McCall9fc6a772010-02-19 09:25:03 +00001243 // If this is the complete variant, just invoke the base variant;
1244 // the epilogue will destruct the virtual bases. But we can't do
1245 // this optimization if the body is a function-try-block, because
1246 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001247 switch (DtorType) {
1248 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1249
1250 case Dtor_Complete:
1251 // Enter the cleanup scopes for virtual bases.
1252 EnterDtorCleanups(Dtor, Dtor_Complete);
1253
John McCallb8b2c9d2013-01-25 22:30:49 +00001254 if (!isTryBody &&
1255 CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001256 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001257 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001258 break;
1259 }
1260 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001261
John McCall50da2ca2010-07-21 05:30:47 +00001262 case Dtor_Base:
1263 // Enter the cleanup scopes for fields and non-virtual bases.
1264 EnterDtorCleanups(Dtor, Dtor_Base);
1265
1266 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001267 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1268 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001269
1270 if (isTryBody)
1271 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1272 else if (Body)
1273 EmitStmt(Body);
1274 else {
1275 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1276 // nothing to do besides what's in the epilogue
1277 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001278 // -fapple-kext must inline any call to this dtor into
1279 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001280 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001281 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001282 break;
John McCall9fc6a772010-02-19 09:25:03 +00001283 }
1284
John McCall50da2ca2010-07-21 05:30:47 +00001285 // Jump out through the epilogue cleanups.
1286 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001287
1288 // Exit the try if applicable.
1289 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001290 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001291}
1292
Lang Hames56c00c42013-02-17 07:22:09 +00001293void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1294 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1295 const Stmt *RootS = AssignOp->getBody();
1296 assert(isa<CompoundStmt>(RootS) &&
1297 "Body of an implicit assignment operator should be compound stmt.");
1298 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1299
1300 LexicalScope Scope(*this, RootCS->getSourceRange());
1301
1302 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1303 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1304 E = RootCS->body_end();
1305 I != E; ++I) {
1306 AM.emitAssignment(*I);
1307 }
1308 AM.finish();
1309}
1310
John McCall50da2ca2010-07-21 05:30:47 +00001311namespace {
1312 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001313 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001314 CallDtorDelete() {}
1315
John McCallad346f42011-07-12 20:27:29 +00001316 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001317 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1318 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1319 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1320 CGF.getContext().getTagDeclType(ClassDecl));
1321 }
1322 };
1323
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001324 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1325 llvm::Value *ShouldDeleteCondition;
1326 public:
1327 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1328 : ShouldDeleteCondition(ShouldDeleteCondition) {
1329 assert(ShouldDeleteCondition != NULL);
1330 }
1331
1332 void Emit(CodeGenFunction &CGF, Flags flags) {
1333 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1334 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1335 llvm::Value *ShouldCallDelete
1336 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1337 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1338
1339 CGF.EmitBlock(callDeleteBB);
1340 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1341 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1342 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1343 CGF.getContext().getTagDeclType(ClassDecl));
1344 CGF.Builder.CreateBr(continueBB);
1345
1346 CGF.EmitBlock(continueBB);
1347 }
1348 };
1349
John McCall9928c482011-07-12 16:41:08 +00001350 class DestroyField : public EHScopeStack::Cleanup {
1351 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001352 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001353 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001354
John McCall9928c482011-07-12 16:41:08 +00001355 public:
1356 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1357 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001358 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001359 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001360
John McCallad346f42011-07-12 20:27:29 +00001361 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001362 // Find the address of the field.
1363 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001364 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1365 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1366 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001367 assert(LV.isSimple());
1368
1369 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001370 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001371 }
1372 };
1373}
1374
Anders Carlsson607d0372009-12-24 22:46:43 +00001375/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1376/// destructor. This is to call destructors on members and base classes
1377/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001378void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1379 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001380 assert(!DD->isTrivial() &&
1381 "Should not emit dtor epilogue for trivial dtor!");
1382
John McCall50da2ca2010-07-21 05:30:47 +00001383 // The deleting-destructor phase just needs to call the appropriate
1384 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001385 if (DtorType == Dtor_Deleting) {
1386 assert(DD->getOperatorDelete() &&
1387 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001388 if (CXXStructorImplicitParamValue) {
1389 // If there is an implicit param to the deleting dtor, it's a boolean
1390 // telling whether we should call delete at the end of the dtor.
1391 EHStack.pushCleanup<CallDtorDeleteConditional>(
1392 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1393 } else {
1394 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1395 }
John McCall3b477332010-02-18 19:59:28 +00001396 return;
1397 }
1398
John McCall50da2ca2010-07-21 05:30:47 +00001399 const CXXRecordDecl *ClassDecl = DD->getParent();
1400
Richard Smith416f63e2011-09-18 12:11:43 +00001401 // Unions have no bases and do not call field destructors.
1402 if (ClassDecl->isUnion())
1403 return;
1404
John McCall50da2ca2010-07-21 05:30:47 +00001405 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001406 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001407
1408 // We push them in the forward order so that they'll be popped in
1409 // the reverse order.
1410 for (CXXRecordDecl::base_class_const_iterator I =
1411 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001412 I != E; ++I) {
1413 const CXXBaseSpecifier &Base = *I;
1414 CXXRecordDecl *BaseClassDecl
1415 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1416
1417 // Ignore trivial destructors.
1418 if (BaseClassDecl->hasTrivialDestructor())
1419 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001420
John McCall1f0fca52010-07-21 07:22:38 +00001421 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1422 BaseClassDecl,
1423 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001424 }
John McCall50da2ca2010-07-21 05:30:47 +00001425
John McCall3b477332010-02-18 19:59:28 +00001426 return;
1427 }
1428
1429 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001430
1431 // Destroy non-virtual bases.
1432 for (CXXRecordDecl::base_class_const_iterator I =
1433 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1434 const CXXBaseSpecifier &Base = *I;
1435
1436 // Ignore virtual bases.
1437 if (Base.isVirtual())
1438 continue;
1439
1440 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1441
1442 // Ignore trivial destructors.
1443 if (BaseClassDecl->hasTrivialDestructor())
1444 continue;
John McCall3b477332010-02-18 19:59:28 +00001445
John McCall1f0fca52010-07-21 07:22:38 +00001446 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1447 BaseClassDecl,
1448 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001449 }
1450
1451 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001452 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001453 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1454 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001455 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001456 QualType type = field->getType();
1457 QualType::DestructionKind dtorKind = type.isDestructedType();
1458 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001459
Richard Smith9a561d52012-02-26 09:11:52 +00001460 // Anonymous union members do not have their destructors called.
1461 const RecordType *RT = type->getAsUnionType();
1462 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1463
John McCall9928c482011-07-12 16:41:08 +00001464 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1465 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1466 getDestroyer(dtorKind),
1467 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001468 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001469}
1470
John McCallc3c07662011-07-13 06:10:41 +00001471/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1472/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001473///
John McCallc3c07662011-07-13 06:10:41 +00001474/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001475/// \param arrayType the type of the array to initialize
1476/// \param arrayBegin an arrayType*
1477/// \param zeroInitialize true if each element should be
1478/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001479void
John McCallc3c07662011-07-13 06:10:41 +00001480CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1481 const ConstantArrayType *arrayType,
1482 llvm::Value *arrayBegin,
1483 CallExpr::const_arg_iterator argBegin,
1484 CallExpr::const_arg_iterator argEnd,
1485 bool zeroInitialize) {
1486 QualType elementType;
1487 llvm::Value *numElements =
1488 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001489
John McCallc3c07662011-07-13 06:10:41 +00001490 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1491 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001492}
1493
John McCallc3c07662011-07-13 06:10:41 +00001494/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1495/// constructor for each of several members of an array.
1496///
1497/// \param ctor the constructor to call for each element
1498/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001499/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001500/// \param arrayBegin a T*, where T is the type constructed by ctor
1501/// \param zeroInitialize true if each element should be
1502/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001503void
John McCallc3c07662011-07-13 06:10:41 +00001504CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1505 llvm::Value *numElements,
1506 llvm::Value *arrayBegin,
1507 CallExpr::const_arg_iterator argBegin,
1508 CallExpr::const_arg_iterator argEnd,
1509 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001510
1511 // It's legal for numElements to be zero. This can happen both
1512 // dynamically, because x can be zero in 'new A[x]', and statically,
1513 // because of GCC extensions that permit zero-length arrays. There
1514 // are probably legitimate places where we could assume that this
1515 // doesn't happen, but it's not clear that it's worth it.
1516 llvm::BranchInst *zeroCheckBranch = 0;
1517
1518 // Optimize for a constant count.
1519 llvm::ConstantInt *constantCount
1520 = dyn_cast<llvm::ConstantInt>(numElements);
1521 if (constantCount) {
1522 // Just skip out if the constant count is zero.
1523 if (constantCount->isZero()) return;
1524
1525 // Otherwise, emit the check.
1526 } else {
1527 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1528 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1529 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1530 EmitBlock(loopBB);
1531 }
1532
John McCallc3c07662011-07-13 06:10:41 +00001533 // Find the end of the array.
1534 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1535 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001536
John McCallc3c07662011-07-13 06:10:41 +00001537 // Enter the loop, setting up a phi for the current location to initialize.
1538 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1539 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1540 EmitBlock(loopBB);
1541 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1542 "arrayctor.cur");
1543 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001544
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001545 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001546
1547 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001548
Douglas Gregor59174c02010-07-21 01:10:17 +00001549 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001550 if (zeroInitialize)
1551 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001552
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001553 // C++ [class.temporary]p4:
1554 // There are two contexts in which temporaries are destroyed at a different
1555 // point than the end of the full-expression. The first context is when a
1556 // default constructor is called to initialize an element of an array.
1557 // If the constructor has one or more default arguments, the destruction of
1558 // every temporary created in a default argument expression is sequenced
1559 // before the construction of the next array element, if any.
1560
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001561 {
John McCallf1549f62010-07-06 01:34:17 +00001562 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001563
John McCallc3c07662011-07-13 06:10:41 +00001564 // Evaluate the constructor and its arguments in a regular
1565 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001566 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001567 !ctor->getParent()->hasTrivialDestructor()) {
1568 Destroyer *destroyer = destroyCXXObject;
1569 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1570 }
1571
1572 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001573 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001574 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001575
John McCallc3c07662011-07-13 06:10:41 +00001576 // Go to the next element.
1577 llvm::Value *next =
1578 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1579 "arrayctor.next");
1580 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001581
John McCallc3c07662011-07-13 06:10:41 +00001582 // Check whether that's the end of the loop.
1583 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1584 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1585 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001586
John McCalldd376ca2011-07-13 07:37:11 +00001587 // Patch the earlier check to skip over the loop.
1588 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1589
John McCallc3c07662011-07-13 06:10:41 +00001590 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001591}
1592
John McCallbdc4d802011-07-09 01:37:26 +00001593void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1594 llvm::Value *addr,
1595 QualType type) {
1596 const RecordType *rtype = type->castAs<RecordType>();
1597 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1598 const CXXDestructorDecl *dtor = record->getDestructor();
1599 assert(!dtor->isTrivial());
1600 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001601 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001602}
1603
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001604void
1605CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001606 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001607 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001608 llvm::Value *This,
1609 CallExpr::const_arg_iterator ArgBeg,
1610 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001611
1612 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001613 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001614 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001615 // If debug info for this class has not been emitted then this is the
1616 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001617 const CXXRecordDecl *Parent = D->getParent();
1618 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1619 Parent->getLocation());
1620 }
1621
John McCall8b6bbeb2010-02-06 00:25:16 +00001622 if (D->isTrivial()) {
1623 if (ArgBeg == ArgEnd) {
1624 // Trivial default constructor, no codegen required.
1625 assert(D->isDefaultConstructor() &&
1626 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001627 return;
1628 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001629
1630 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001631 assert(D->isCopyOrMoveConstructor() &&
1632 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001633
John McCall8b6bbeb2010-02-06 00:25:16 +00001634 const Expr *E = (*ArgBeg);
1635 QualType Ty = E->getType();
1636 llvm::Value *Src = EmitLValue(E).getAddress();
1637 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001638 return;
1639 }
1640
Douglas Gregor378e1e72013-01-31 05:50:40 +00001641 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase,
1642 Delegating);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001643 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1644
Richard Smith4def70d2012-10-09 19:52:38 +00001645 // FIXME: Provide a source location here.
1646 EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001647 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1648 ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001649}
1650
John McCallc0bf4622010-02-23 00:48:20 +00001651void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001652CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1653 llvm::Value *This, llvm::Value *Src,
1654 CallExpr::const_arg_iterator ArgBeg,
1655 CallExpr::const_arg_iterator ArgEnd) {
1656 if (D->isTrivial()) {
1657 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001658 assert(D->isCopyOrMoveConstructor() &&
1659 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001660 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1661 return;
1662 }
1663 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1664 clang::Ctor_Complete);
1665 assert(D->isInstance() &&
1666 "Trying to emit a member call expr on a static method!");
1667
1668 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1669
1670 CallArgList Args;
1671
1672 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001673 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001674
1675
1676 // Push the src ptr.
1677 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001678 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001679 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001680 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001681
1682 // Skip over first argument (Src).
1683 ++ArgBeg;
1684 CallExpr::const_arg_iterator Arg = ArgBeg;
1685 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1686 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1687 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001688 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001689 }
1690 // Either we've emitted all the call args, or we have a call to a
1691 // variadic function.
1692 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1693 "Extra arguments in non-variadic function!");
1694 // If we still have any arguments, emit them using the type of the argument.
1695 for (; Arg != ArgEnd; ++Arg) {
1696 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001697 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001698 }
1699
John McCall0f3d0972012-07-07 06:41:13 +00001700 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1701 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001702}
1703
1704void
John McCallc0bf4622010-02-23 00:48:20 +00001705CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1706 CXXCtorType CtorType,
1707 const FunctionArgList &Args) {
1708 CallArgList DelegateArgs;
1709
1710 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1711 assert(I != E && "no parameters to constructor");
1712
1713 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001714 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001715 ++I;
1716
1717 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001718 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001719 /*ForVirtualBase=*/false,
1720 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001721 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001722 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001723
Anders Carlssonaf440352010-03-23 04:11:45 +00001724 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001725 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001726 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001727 ++I;
1728 }
1729 }
1730
1731 // Explicit arguments.
1732 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001733 const VarDecl *param = *I;
1734 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001735 }
1736
John McCallde5d3c72012-02-17 03:33:10 +00001737 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001738 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1739 ReturnValueSlot(), DelegateArgs, Ctor);
1740}
1741
Sean Huntb76af9c2011-05-03 23:05:34 +00001742namespace {
1743 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1744 const CXXDestructorDecl *Dtor;
1745 llvm::Value *Addr;
1746 CXXDtorType Type;
1747
1748 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1749 CXXDtorType Type)
1750 : Dtor(D), Addr(Addr), Type(Type) {}
1751
John McCallad346f42011-07-12 20:27:29 +00001752 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001753 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001754 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001755 }
1756 };
1757}
1758
Sean Hunt059ce0d2011-05-01 07:04:31 +00001759void
1760CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1761 const FunctionArgList &Args) {
1762 assert(Ctor->isDelegatingConstructor());
1763
1764 llvm::Value *ThisPtr = LoadCXXThis();
1765
Eli Friedmanf3940782011-12-03 00:54:26 +00001766 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001767 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001768 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001769 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001770 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001771 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001772 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001773
1774 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001775
Sean Huntb76af9c2011-05-03 23:05:34 +00001776 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001777 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001778 CXXDtorType Type =
1779 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1780
1781 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1782 ClassDecl->getDestructor(),
1783 ThisPtr, Type);
1784 }
1785}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001786
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001787void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1788 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001789 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001790 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001791 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001792 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001793 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001794 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001795 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001796 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1797 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001798
1799 if (!Callee)
1800 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001801
Richard Smith4def70d2012-10-09 19:52:38 +00001802 // FIXME: Provide a source location here.
1803 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001804 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1805 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001806}
1807
John McCall291ae942010-07-21 01:41:18 +00001808namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001809 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001810 const CXXDestructorDecl *Dtor;
1811 llvm::Value *Addr;
1812
1813 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1814 : Dtor(D), Addr(Addr) {}
1815
John McCallad346f42011-07-12 20:27:29 +00001816 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001817 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001818 /*ForVirtualBase=*/false,
1819 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001820 }
1821 };
1822}
1823
John McCall81407d42010-07-21 06:29:51 +00001824void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1825 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001826 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001827}
1828
John McCallf1549f62010-07-06 01:34:17 +00001829void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1830 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1831 if (!ClassDecl) return;
1832 if (ClassDecl->hasTrivialDestructor()) return;
1833
1834 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001835 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001836 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001837}
1838
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001839llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001840CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1841 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001842 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001843 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001844 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001845 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001846
1847 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001848 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1849 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001850 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001851 ConvertType(getContext().getPointerDiffType());
1852
1853 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1854 PtrDiffTy->getPointerTo());
1855
1856 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1857
1858 return VBaseOffset;
1859}
1860
Anders Carlssond103f9f2010-03-28 19:40:00 +00001861void
1862CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001863 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001864 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001865 llvm::Constant *VTable,
1866 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001867 const CXXRecordDecl *RD = Base.getBase();
1868
Anders Carlssond103f9f2010-03-28 19:40:00 +00001869 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001870 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001871
Anders Carlssonc83f1062010-03-29 01:08:49 +00001872 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001873 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001874 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001875 // Get the secondary vpointer index.
1876 uint64_t VirtualPointerIndex =
1877 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1878
1879 /// Load the VTT.
1880 llvm::Value *VTT = LoadCXXVTT();
1881 if (VirtualPointerIndex)
1882 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1883
1884 // And load the address point from the VTT.
1885 VTableAddressPoint = Builder.CreateLoad(VTT);
1886 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001887 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001888 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001889 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001890 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001891 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001892
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001893 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001894 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001895 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001896
1897 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1898 // We need to use the virtual base offset offset because the virtual base
1899 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001900 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1901 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001902 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001903 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001904 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001905 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001906 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001907
1908 // Apply the offsets.
1909 llvm::Value *VTableField = LoadCXXThis();
1910
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001911 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001912 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1913 NonVirtualOffset,
1914 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001915
Anders Carlssond103f9f2010-03-28 19:40:00 +00001916 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001917 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001918 VTableAddressPoint->getType()->getPointerTo();
1919 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001920 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1921 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001922}
1923
Anders Carlsson603d6d12010-03-28 21:07:49 +00001924void
1925CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001926 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001927 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001928 bool BaseIsNonVirtualPrimaryBase,
1929 llvm::Constant *VTable,
1930 const CXXRecordDecl *VTableClass,
1931 VisitedVirtualBasesSetTy& VBases) {
1932 // If this base is a non-virtual primary base the address point has already
1933 // been set.
1934 if (!BaseIsNonVirtualPrimaryBase) {
1935 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001936 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1937 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001938 }
1939
1940 const CXXRecordDecl *RD = Base.getBase();
1941
1942 // Traverse bases.
1943 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1944 E = RD->bases_end(); I != E; ++I) {
1945 CXXRecordDecl *BaseDecl
1946 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1947
1948 // Ignore classes without a vtable.
1949 if (!BaseDecl->isDynamicClass())
1950 continue;
1951
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001952 CharUnits BaseOffset;
1953 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001954 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001955
1956 if (I->isVirtual()) {
1957 // Check if we've visited this virtual base before.
1958 if (!VBases.insert(BaseDecl))
1959 continue;
1960
1961 const ASTRecordLayout &Layout =
1962 getContext().getASTRecordLayout(VTableClass);
1963
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001964 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1965 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001966 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001967 } else {
1968 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1969
Ken Dyck4230d522011-03-24 01:21:01 +00001970 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001971 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001972 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001973 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001974 }
1975
Ken Dyck4230d522011-03-24 01:21:01 +00001976 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001977 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001978 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001979 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001980 VTable, VTableClass, VBases);
1981 }
1982}
1983
1984void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1985 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001986 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001987 return;
1988
Anders Carlsson07036902010-03-26 04:39:42 +00001989 // Get the VTable.
1990 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001991
Anders Carlsson603d6d12010-03-28 21:07:49 +00001992 // Initialize the vtable pointers for this class and all of its bases.
1993 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001994 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1995 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001996 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001997 /*BaseIsNonVirtualPrimaryBase=*/false,
1998 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001999}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002000
2001llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002002 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002003 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002004 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2005 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2006 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002007}
Anders Carlssona2447e02011-05-08 20:32:23 +00002008
2009static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2010 const Expr *E = Base;
2011
2012 while (true) {
2013 E = E->IgnoreParens();
2014 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2015 if (CE->getCastKind() == CK_DerivedToBase ||
2016 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2017 CE->getCastKind() == CK_NoOp) {
2018 E = CE->getSubExpr();
2019 continue;
2020 }
2021 }
2022
2023 break;
2024 }
2025
2026 QualType DerivedType = E->getType();
2027 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2028 DerivedType = PTy->getPointeeType();
2029
2030 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2031}
2032
2033// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2034// quite what we want.
2035static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2036 while (true) {
2037 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2038 E = PE->getSubExpr();
2039 continue;
2040 }
2041
2042 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2043 if (CE->getCastKind() == CK_NoOp) {
2044 E = CE->getSubExpr();
2045 continue;
2046 }
2047 }
2048 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2049 if (UO->getOpcode() == UO_Extension) {
2050 E = UO->getSubExpr();
2051 continue;
2052 }
2053 }
2054 return E;
2055 }
2056}
2057
2058/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2059/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002060static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2061 const CXXMethodDecl *MD) {
2062 // If the most derived class is marked final, we know that no subclass can
2063 // override this member function and so we can devirtualize it. For example:
2064 //
2065 // struct A { virtual void f(); }
2066 // struct B final : A { };
2067 //
2068 // void f(B *b) {
2069 // b->f();
2070 // }
2071 //
2072 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2073 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2074 return true;
2075
2076 // If the member function is marked 'final', we know that it can't be
2077 // overridden and can therefore devirtualize it.
2078 if (MD->hasAttr<FinalAttr>())
2079 return true;
2080
2081 // Similarly, if the class itself is marked 'final' it can't be overridden
2082 // and we can therefore devirtualize the member function call.
2083 if (MD->getParent()->hasAttr<FinalAttr>())
2084 return true;
2085
2086 Base = skipNoOpCastsAndParens(Base);
2087 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2088 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2089 // This is a record decl. We know the type and can devirtualize it.
2090 return VD->getType()->isRecordType();
2091 }
2092
2093 return false;
2094 }
2095
2096 // We can always devirtualize calls on temporary object expressions.
2097 if (isa<CXXConstructExpr>(Base))
2098 return true;
2099
2100 // And calls on bound temporaries.
2101 if (isa<CXXBindTemporaryExpr>(Base))
2102 return true;
2103
2104 // Check if this is a call expr that returns a record type.
2105 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2106 return CE->getCallReturnType()->isRecordType();
2107
2108 // We can't devirtualize the call.
2109 return false;
2110}
2111
2112static bool UseVirtualCall(ASTContext &Context,
2113 const CXXOperatorCallExpr *CE,
2114 const CXXMethodDecl *MD) {
2115 if (!MD->isVirtual())
2116 return false;
2117
2118 // When building with -fapple-kext, all calls must go through the vtable since
2119 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002120 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002121 return true;
2122
2123 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2124}
2125
2126llvm::Value *
2127CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2128 const CXXMethodDecl *MD,
2129 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002130 llvm::FunctionType *fnType =
2131 CGM.getTypes().GetFunctionType(
2132 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002133
2134 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002135 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002136
John McCallde5d3c72012-02-17 03:33:10 +00002137 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002138}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002139
John McCall0f3d0972012-07-07 06:41:13 +00002140void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2141 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002142 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002143 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002144 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002145 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002146 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002147
Eli Friedman21f6ed92012-02-16 03:47:28 +00002148 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002149 const CGFunctionInfo &calleeFnInfo =
2150 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2151 llvm::Value *callee =
2152 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2153 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002154
John McCall0f3d0972012-07-07 06:41:13 +00002155 // Prepare the return slot.
2156 const FunctionProtoType *FPT =
2157 callOperator->getType()->castAs<FunctionProtoType>();
2158 QualType resultType = FPT->getResultType();
2159 ReturnValueSlot returnSlot;
2160 if (!resultType->isVoidType() &&
2161 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2162 hasAggregateLLVMType(calleeFnInfo.getReturnType()))
2163 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2164
2165 // We don't need to separately arrange the call arguments because
2166 // the call can't be variadic anyway --- it's impossible to forward
2167 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002168
2169 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002170 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2171 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002172
John McCall0f3d0972012-07-07 06:41:13 +00002173 // If necessary, copy the returned value into the slot.
2174 if (!resultType->isVoidType() && returnSlot.isNull())
2175 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002176 else
2177 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002178}
2179
Eli Friedman64bee652012-02-25 02:48:22 +00002180void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2181 const BlockDecl *BD = BlockInfo->getBlockDecl();
2182 const VarDecl *variable = BD->capture_begin()->getVariable();
2183 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2184
2185 // Start building arguments for forwarding call
2186 CallArgList CallArgs;
2187
2188 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2189 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2190 CallArgs.add(RValue::get(ThisPtr), ThisType);
2191
2192 // Add the rest of the parameters.
2193 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2194 E = BD->param_end(); I != E; ++I) {
2195 ParmVarDecl *param = *I;
2196 EmitDelegateCallArg(CallArgs, param);
2197 }
2198
2199 EmitForwardingCallToLambda(Lambda, CallArgs);
2200}
2201
2202void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2203 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
2204 // FIXME: Making this work correctly is nasty because it requires either
2205 // cloning the body of the call operator or making the call operator forward.
2206 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
2207 return;
2208 }
2209
Eli Friedman64bee652012-02-25 02:48:22 +00002210 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002211}
2212
2213void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2214 const CXXRecordDecl *Lambda = MD->getParent();
2215
2216 // Start building arguments for forwarding call
2217 CallArgList CallArgs;
2218
2219 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2220 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2221 CallArgs.add(RValue::get(ThisPtr), ThisType);
2222
2223 // Add the rest of the parameters.
2224 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2225 E = MD->param_end(); I != E; ++I) {
2226 ParmVarDecl *param = *I;
2227 EmitDelegateCallArg(CallArgs, param);
2228 }
2229
2230 EmitForwardingCallToLambda(Lambda, CallArgs);
2231}
2232
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002233void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2234 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002235 // FIXME: Making this work correctly is nasty because it requires either
2236 // cloning the body of the call operator or making the call operator forward.
2237 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002238 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002239 }
2240
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002241 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002242}