blob: 05894465d2a07b25a46f3b45886781b03a1aaf3b [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
Lang Hames5e8577e2013-02-27 04:14:49 +0000791 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000792
793 if (FirstField->isBitField()) {
794 const CGRecordLayout &RL =
795 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
796 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000797 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
798 } else {
799 unsigned AlignBits =
800 CGF.getContext().getTypeAlign(FirstField->getType());
801 Alignment = CGF.getContext().toCharUnitsFromBits(AlignBits);
802 }
Lang Hames56c00c42013-02-17 07:22:09 +0000803
Lang Hames5e8577e2013-02-27 04:14:49 +0000804 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
805 Alignment) == 0 && "Bad field alignment.");
806
Lang Hames56c00c42013-02-17 07:22:09 +0000807 CharUnits MemcpySize = getMemcpySize();
808 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
809 llvm::Value *ThisPtr = CGF.LoadCXXThis();
810 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
811 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
812 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
813 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
814 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
815
816 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
817 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
818 MemcpySize, Alignment);
819 reset();
820 }
821
822 void reset() {
823 FirstField = 0;
824 }
825
826 protected:
827 CodeGenFunction &CGF;
828 const CXXRecordDecl *ClassDecl;
829
830 private:
831
832 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
833 CharUnits Size, CharUnits Alignment) {
834 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
835 llvm::Type *DBP =
836 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
837 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
838
839 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
840 llvm::Type *SBP =
841 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
842 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
843
844 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
845 Alignment.getQuantity());
846 }
847
848 void addInitialField(FieldDecl *F) {
849 FirstField = F;
850 LastField = F;
851 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
852 LastFieldOffset = FirstFieldOffset;
853 LastAddedFieldIndex = F->getFieldIndex();
854 return;
855 }
856
857 void addNextField(FieldDecl *F) {
858 assert(F->getFieldIndex() == LastAddedFieldIndex + 1 &&
859 "Cannot aggregate non-contiguous fields.");
860 LastAddedFieldIndex = F->getFieldIndex();
861
862 // The 'first' and 'last' fields are chosen by offset, rather than field
863 // index. This allows the code to support bitfields, as well as regular
864 // fields.
865 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
866 if (FOffset < FirstFieldOffset) {
867 FirstField = F;
868 FirstFieldOffset = FOffset;
869 } else if (FOffset > LastFieldOffset) {
870 LastField = F;
871 LastFieldOffset = FOffset;
872 }
873 }
874
875 const VarDecl *SrcRec;
876 const ASTRecordLayout &RecLayout;
877 FieldDecl *FirstField;
878 FieldDecl *LastField;
879 uint64_t FirstFieldOffset, LastFieldOffset;
880 unsigned LastAddedFieldIndex;
881 };
882
883 class ConstructorMemcpyizer : public FieldMemcpyizer {
884 private:
885
886 /// Get source argument for copy constructor. Returns null if not a copy
887 /// constructor.
888 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
889 FunctionArgList &Args) {
890 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
891 return Args[Args.size() - 1];
892 return 0;
893 }
894
895 // Returns true if a CXXCtorInitializer represents a member initialization
896 // that can be rolled into a memcpy.
897 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
898 if (!MemcpyableCtor)
899 return false;
900 FieldDecl *Field = MemberInit->getMember();
901 assert(Field != 0 && "No field for member init.");
902 QualType FieldType = Field->getType();
903 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
904
905 // Bail out on non-POD, not-trivially-constructable members.
906 if (!(CE && CE->getConstructor()->isTrivial()) &&
907 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
908 FieldType->isReferenceType()))
909 return false;
910
911 // Bail out on volatile fields.
912 if (!isMemcpyableField(Field))
913 return false;
914
915 // Otherwise we're good.
916 return true;
917 }
918
919 public:
920 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
921 FunctionArgList &Args)
922 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
923 ConstructorDecl(CD),
924 MemcpyableCtor(CD->isImplicitlyDefined() &&
925 CD->isCopyOrMoveConstructor() &&
926 CGF.getLangOpts().getGC() == LangOptions::NonGC),
927 Args(Args) { }
928
929 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
930 if (isMemberInitMemcpyable(MemberInit)) {
931 AggregatedInits.push_back(MemberInit);
932 addMemcpyableField(MemberInit->getMember());
933 } else {
934 emitAggregatedInits();
935 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
936 ConstructorDecl, Args);
937 }
938 }
939
940 void emitAggregatedInits() {
941 if (AggregatedInits.size() <= 1) {
942 // This memcpy is too small to be worthwhile. Fall back on default
943 // codegen.
944 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
945 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
946 AggregatedInits[i], ConstructorDecl, Args);
947 }
948 reset();
949 return;
950 }
951
952 pushEHDestructors();
953 emitMemcpy();
954 AggregatedInits.clear();
955 }
956
957 void pushEHDestructors() {
958 llvm::Value *ThisPtr = CGF.LoadCXXThis();
959 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
960 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
961
962 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
963 QualType FieldType = AggregatedInits[i]->getMember()->getType();
964 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
965 if (CGF.needsEHCleanup(dtorKind))
966 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
967 }
968 }
969
970 void finish() {
971 emitAggregatedInits();
972 }
973
974 private:
975 const CXXConstructorDecl *ConstructorDecl;
976 bool MemcpyableCtor;
977 FunctionArgList &Args;
978 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
979 };
980
981 class AssignmentMemcpyizer : public FieldMemcpyizer {
982 private:
983
984 // Returns the memcpyable field copied by the given statement, if one
985 // exists. Otherwise r
986 FieldDecl* getMemcpyableField(Stmt *S) {
987 if (!AssignmentsMemcpyable)
988 return 0;
989 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
990 // Recognise trivial assignments.
991 if (BO->getOpcode() != BO_Assign)
992 return 0;
993 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
994 if (!ME)
995 return 0;
996 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
997 if (!Field || !isMemcpyableField(Field))
998 return 0;
999 Stmt *RHS = BO->getRHS();
1000 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1001 RHS = EC->getSubExpr();
1002 if (!RHS)
1003 return 0;
1004 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1005 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1006 return 0;
1007 return Field;
1008 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1009 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1010 if (!(MD && (MD->isCopyAssignmentOperator() ||
1011 MD->isMoveAssignmentOperator()) &&
1012 MD->isTrivial()))
1013 return 0;
1014 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1015 if (!IOA)
1016 return 0;
1017 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1018 if (!Field || !isMemcpyableField(Field))
1019 return 0;
1020 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1021 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1022 return 0;
1023 return Field;
1024 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1025 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1026 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1027 return 0;
1028 Expr *DstPtr = CE->getArg(0);
1029 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1030 DstPtr = DC->getSubExpr();
1031 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1032 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1033 return 0;
1034 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1035 if (!ME)
1036 return 0;
1037 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1038 if (!Field || !isMemcpyableField(Field))
1039 return 0;
1040 Expr *SrcPtr = CE->getArg(1);
1041 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1042 SrcPtr = SC->getSubExpr();
1043 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1044 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1045 return 0;
1046 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1047 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1048 return 0;
1049 return Field;
1050 }
1051
1052 return 0;
1053 }
1054
1055 bool AssignmentsMemcpyable;
1056 SmallVector<Stmt*, 16> AggregatedStmts;
1057
1058 public:
1059
1060 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1061 FunctionArgList &Args)
1062 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1063 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1064 assert(Args.size() == 2);
1065 }
1066
1067 void emitAssignment(Stmt *S) {
1068 FieldDecl *F = getMemcpyableField(S);
1069 if (F) {
1070 addMemcpyableField(F);
1071 AggregatedStmts.push_back(S);
1072 } else {
1073 emitAggregatedStmts();
1074 CGF.EmitStmt(S);
1075 }
1076 }
1077
1078 void emitAggregatedStmts() {
1079 if (AggregatedStmts.size() <= 1) {
1080 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1081 CGF.EmitStmt(AggregatedStmts[i]);
1082 reset();
1083 }
1084
1085 emitMemcpy();
1086 AggregatedStmts.clear();
1087 }
1088
1089 void finish() {
1090 emitAggregatedStmts();
1091 }
1092 };
1093
1094}
1095
Anders Carlsson607d0372009-12-24 22:46:43 +00001096/// EmitCtorPrologue - This routine generates necessary code to initialize
1097/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001098void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001099 CXXCtorType CtorType,
1100 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001101 if (CD->isDelegatingConstructor())
1102 return EmitDelegatingCXXConstructorCall(CD, Args);
1103
Anders Carlsson607d0372009-12-24 22:46:43 +00001104 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001105
Chris Lattner5f9e2722011-07-23 10:55:15 +00001106 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +00001107
Anders Carlsson607d0372009-12-24 22:46:43 +00001108 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1109 E = CD->init_end();
1110 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +00001111 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +00001112
Sean Huntd49bd552011-05-03 20:19:28 +00001113 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001114 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +00001115 } else {
1116 assert(Member->isAnyMemberInitializer() &&
1117 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001118 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +00001119 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001120 }
1121
Anders Carlsson603d6d12010-03-28 21:07:49 +00001122 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001123
Lang Hames56c00c42013-02-17 07:22:09 +00001124 ConstructorMemcpyizer CM(*this, CD, Args);
John McCallf1549f62010-07-06 01:34:17 +00001125 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Lang Hames56c00c42013-02-17 07:22:09 +00001126 CM.addMemberInitializer(MemberInitializers[I]);
1127 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001128}
1129
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001130static bool
1131FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1132
1133static bool
1134HasTrivialDestructorBody(ASTContext &Context,
1135 const CXXRecordDecl *BaseClassDecl,
1136 const CXXRecordDecl *MostDerivedClassDecl)
1137{
1138 // If the destructor is trivial we don't have to check anything else.
1139 if (BaseClassDecl->hasTrivialDestructor())
1140 return true;
1141
1142 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1143 return false;
1144
1145 // Check fields.
1146 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1147 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001148 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001149
1150 if (!FieldHasTrivialDestructorBody(Context, Field))
1151 return false;
1152 }
1153
1154 // Check non-virtual bases.
1155 for (CXXRecordDecl::base_class_const_iterator I =
1156 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1157 I != E; ++I) {
1158 if (I->isVirtual())
1159 continue;
1160
1161 const CXXRecordDecl *NonVirtualBase =
1162 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1163 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1164 MostDerivedClassDecl))
1165 return false;
1166 }
1167
1168 if (BaseClassDecl == MostDerivedClassDecl) {
1169 // Check virtual bases.
1170 for (CXXRecordDecl::base_class_const_iterator I =
1171 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1172 I != E; ++I) {
1173 const CXXRecordDecl *VirtualBase =
1174 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1175 if (!HasTrivialDestructorBody(Context, VirtualBase,
1176 MostDerivedClassDecl))
1177 return false;
1178 }
1179 }
1180
1181 return true;
1182}
1183
1184static bool
1185FieldHasTrivialDestructorBody(ASTContext &Context,
1186 const FieldDecl *Field)
1187{
1188 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1189
1190 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1191 if (!RT)
1192 return true;
1193
1194 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1195 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1196}
1197
Anders Carlssonffb945f2011-05-14 23:26:09 +00001198/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1199/// any vtable pointers before calling this destructor.
1200static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001201 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001202 if (!Dtor->hasTrivialBody())
1203 return false;
1204
1205 // Check the fields.
1206 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1207 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1208 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001209 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001210
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001211 if (!FieldHasTrivialDestructorBody(Context, Field))
1212 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001213 }
1214
1215 return true;
1216}
1217
John McCall9fc6a772010-02-19 09:25:03 +00001218/// EmitDestructorBody - Emits the body of the current destructor.
1219void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1220 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1221 CXXDtorType DtorType = CurGD.getDtorType();
1222
John McCall50da2ca2010-07-21 05:30:47 +00001223 // The call to operator delete in a deleting destructor happens
1224 // outside of the function-try-block, which means it's always
1225 // possible to delegate the destructor body to the complete
1226 // destructor. Do so.
1227 if (DtorType == Dtor_Deleting) {
1228 EnterDtorCleanups(Dtor, Dtor_Deleting);
1229 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001230 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001231 PopCleanupBlock();
1232 return;
1233 }
1234
John McCall9fc6a772010-02-19 09:25:03 +00001235 Stmt *Body = Dtor->getBody();
1236
1237 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001238 // anything else.
1239 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001240 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001241 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001242
John McCall50da2ca2010-07-21 05:30:47 +00001243 // Enter the epilogue cleanups.
1244 RunCleanupsScope DtorEpilogue(*this);
1245
John McCall9fc6a772010-02-19 09:25:03 +00001246 // If this is the complete variant, just invoke the base variant;
1247 // the epilogue will destruct the virtual bases. But we can't do
1248 // this optimization if the body is a function-try-block, because
1249 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001250 switch (DtorType) {
1251 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1252
1253 case Dtor_Complete:
1254 // Enter the cleanup scopes for virtual bases.
1255 EnterDtorCleanups(Dtor, Dtor_Complete);
1256
John McCallb8b2c9d2013-01-25 22:30:49 +00001257 if (!isTryBody &&
1258 CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001259 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001260 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001261 break;
1262 }
1263 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001264
John McCall50da2ca2010-07-21 05:30:47 +00001265 case Dtor_Base:
1266 // Enter the cleanup scopes for fields and non-virtual bases.
1267 EnterDtorCleanups(Dtor, Dtor_Base);
1268
1269 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001270 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1271 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001272
1273 if (isTryBody)
1274 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1275 else if (Body)
1276 EmitStmt(Body);
1277 else {
1278 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1279 // nothing to do besides what's in the epilogue
1280 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001281 // -fapple-kext must inline any call to this dtor into
1282 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001283 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001284 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001285 break;
John McCall9fc6a772010-02-19 09:25:03 +00001286 }
1287
John McCall50da2ca2010-07-21 05:30:47 +00001288 // Jump out through the epilogue cleanups.
1289 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001290
1291 // Exit the try if applicable.
1292 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001293 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001294}
1295
Lang Hames56c00c42013-02-17 07:22:09 +00001296void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1297 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1298 const Stmt *RootS = AssignOp->getBody();
1299 assert(isa<CompoundStmt>(RootS) &&
1300 "Body of an implicit assignment operator should be compound stmt.");
1301 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1302
1303 LexicalScope Scope(*this, RootCS->getSourceRange());
1304
1305 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1306 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1307 E = RootCS->body_end();
1308 I != E; ++I) {
1309 AM.emitAssignment(*I);
1310 }
1311 AM.finish();
1312}
1313
John McCall50da2ca2010-07-21 05:30:47 +00001314namespace {
1315 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001316 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001317 CallDtorDelete() {}
1318
John McCallad346f42011-07-12 20:27:29 +00001319 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001320 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1321 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1322 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1323 CGF.getContext().getTagDeclType(ClassDecl));
1324 }
1325 };
1326
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001327 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1328 llvm::Value *ShouldDeleteCondition;
1329 public:
1330 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1331 : ShouldDeleteCondition(ShouldDeleteCondition) {
1332 assert(ShouldDeleteCondition != NULL);
1333 }
1334
1335 void Emit(CodeGenFunction &CGF, Flags flags) {
1336 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1337 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1338 llvm::Value *ShouldCallDelete
1339 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1340 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1341
1342 CGF.EmitBlock(callDeleteBB);
1343 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1344 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1345 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1346 CGF.getContext().getTagDeclType(ClassDecl));
1347 CGF.Builder.CreateBr(continueBB);
1348
1349 CGF.EmitBlock(continueBB);
1350 }
1351 };
1352
John McCall9928c482011-07-12 16:41:08 +00001353 class DestroyField : public EHScopeStack::Cleanup {
1354 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001355 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001356 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001357
John McCall9928c482011-07-12 16:41:08 +00001358 public:
1359 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1360 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001361 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001362 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001363
John McCallad346f42011-07-12 20:27:29 +00001364 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001365 // Find the address of the field.
1366 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001367 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1368 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1369 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001370 assert(LV.isSimple());
1371
1372 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001373 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001374 }
1375 };
1376}
1377
Anders Carlsson607d0372009-12-24 22:46:43 +00001378/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1379/// destructor. This is to call destructors on members and base classes
1380/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001381void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1382 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001383 assert(!DD->isTrivial() &&
1384 "Should not emit dtor epilogue for trivial dtor!");
1385
John McCall50da2ca2010-07-21 05:30:47 +00001386 // The deleting-destructor phase just needs to call the appropriate
1387 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001388 if (DtorType == Dtor_Deleting) {
1389 assert(DD->getOperatorDelete() &&
1390 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001391 if (CXXStructorImplicitParamValue) {
1392 // If there is an implicit param to the deleting dtor, it's a boolean
1393 // telling whether we should call delete at the end of the dtor.
1394 EHStack.pushCleanup<CallDtorDeleteConditional>(
1395 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1396 } else {
1397 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1398 }
John McCall3b477332010-02-18 19:59:28 +00001399 return;
1400 }
1401
John McCall50da2ca2010-07-21 05:30:47 +00001402 const CXXRecordDecl *ClassDecl = DD->getParent();
1403
Richard Smith416f63e2011-09-18 12:11:43 +00001404 // Unions have no bases and do not call field destructors.
1405 if (ClassDecl->isUnion())
1406 return;
1407
John McCall50da2ca2010-07-21 05:30:47 +00001408 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001409 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001410
1411 // We push them in the forward order so that they'll be popped in
1412 // the reverse order.
1413 for (CXXRecordDecl::base_class_const_iterator I =
1414 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001415 I != E; ++I) {
1416 const CXXBaseSpecifier &Base = *I;
1417 CXXRecordDecl *BaseClassDecl
1418 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1419
1420 // Ignore trivial destructors.
1421 if (BaseClassDecl->hasTrivialDestructor())
1422 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001423
John McCall1f0fca52010-07-21 07:22:38 +00001424 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1425 BaseClassDecl,
1426 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001427 }
John McCall50da2ca2010-07-21 05:30:47 +00001428
John McCall3b477332010-02-18 19:59:28 +00001429 return;
1430 }
1431
1432 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001433
1434 // Destroy non-virtual bases.
1435 for (CXXRecordDecl::base_class_const_iterator I =
1436 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1437 const CXXBaseSpecifier &Base = *I;
1438
1439 // Ignore virtual bases.
1440 if (Base.isVirtual())
1441 continue;
1442
1443 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1444
1445 // Ignore trivial destructors.
1446 if (BaseClassDecl->hasTrivialDestructor())
1447 continue;
John McCall3b477332010-02-18 19:59:28 +00001448
John McCall1f0fca52010-07-21 07:22:38 +00001449 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1450 BaseClassDecl,
1451 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001452 }
1453
1454 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001455 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001456 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1457 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001458 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001459 QualType type = field->getType();
1460 QualType::DestructionKind dtorKind = type.isDestructedType();
1461 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001462
Richard Smith9a561d52012-02-26 09:11:52 +00001463 // Anonymous union members do not have their destructors called.
1464 const RecordType *RT = type->getAsUnionType();
1465 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1466
John McCall9928c482011-07-12 16:41:08 +00001467 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1468 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1469 getDestroyer(dtorKind),
1470 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001471 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001472}
1473
John McCallc3c07662011-07-13 06:10:41 +00001474/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1475/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001476///
John McCallc3c07662011-07-13 06:10:41 +00001477/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001478/// \param arrayType the type of the array to initialize
1479/// \param arrayBegin an arrayType*
1480/// \param zeroInitialize true if each element should be
1481/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001482void
John McCallc3c07662011-07-13 06:10:41 +00001483CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1484 const ConstantArrayType *arrayType,
1485 llvm::Value *arrayBegin,
1486 CallExpr::const_arg_iterator argBegin,
1487 CallExpr::const_arg_iterator argEnd,
1488 bool zeroInitialize) {
1489 QualType elementType;
1490 llvm::Value *numElements =
1491 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001492
John McCallc3c07662011-07-13 06:10:41 +00001493 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1494 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001495}
1496
John McCallc3c07662011-07-13 06:10:41 +00001497/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1498/// constructor for each of several members of an array.
1499///
1500/// \param ctor the constructor to call for each element
1501/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001502/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001503/// \param arrayBegin a T*, where T is the type constructed by ctor
1504/// \param zeroInitialize true if each element should be
1505/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001506void
John McCallc3c07662011-07-13 06:10:41 +00001507CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1508 llvm::Value *numElements,
1509 llvm::Value *arrayBegin,
1510 CallExpr::const_arg_iterator argBegin,
1511 CallExpr::const_arg_iterator argEnd,
1512 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001513
1514 // It's legal for numElements to be zero. This can happen both
1515 // dynamically, because x can be zero in 'new A[x]', and statically,
1516 // because of GCC extensions that permit zero-length arrays. There
1517 // are probably legitimate places where we could assume that this
1518 // doesn't happen, but it's not clear that it's worth it.
1519 llvm::BranchInst *zeroCheckBranch = 0;
1520
1521 // Optimize for a constant count.
1522 llvm::ConstantInt *constantCount
1523 = dyn_cast<llvm::ConstantInt>(numElements);
1524 if (constantCount) {
1525 // Just skip out if the constant count is zero.
1526 if (constantCount->isZero()) return;
1527
1528 // Otherwise, emit the check.
1529 } else {
1530 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1531 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1532 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1533 EmitBlock(loopBB);
1534 }
1535
John McCallc3c07662011-07-13 06:10:41 +00001536 // Find the end of the array.
1537 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1538 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001539
John McCallc3c07662011-07-13 06:10:41 +00001540 // Enter the loop, setting up a phi for the current location to initialize.
1541 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1542 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1543 EmitBlock(loopBB);
1544 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1545 "arrayctor.cur");
1546 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001547
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001548 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001549
1550 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001551
Douglas Gregor59174c02010-07-21 01:10:17 +00001552 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001553 if (zeroInitialize)
1554 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001555
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001556 // C++ [class.temporary]p4:
1557 // There are two contexts in which temporaries are destroyed at a different
1558 // point than the end of the full-expression. The first context is when a
1559 // default constructor is called to initialize an element of an array.
1560 // If the constructor has one or more default arguments, the destruction of
1561 // every temporary created in a default argument expression is sequenced
1562 // before the construction of the next array element, if any.
1563
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001564 {
John McCallf1549f62010-07-06 01:34:17 +00001565 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001566
John McCallc3c07662011-07-13 06:10:41 +00001567 // Evaluate the constructor and its arguments in a regular
1568 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001569 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001570 !ctor->getParent()->hasTrivialDestructor()) {
1571 Destroyer *destroyer = destroyCXXObject;
1572 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1573 }
1574
1575 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001576 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001577 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001578
John McCallc3c07662011-07-13 06:10:41 +00001579 // Go to the next element.
1580 llvm::Value *next =
1581 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1582 "arrayctor.next");
1583 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001584
John McCallc3c07662011-07-13 06:10:41 +00001585 // Check whether that's the end of the loop.
1586 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1587 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1588 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001589
John McCalldd376ca2011-07-13 07:37:11 +00001590 // Patch the earlier check to skip over the loop.
1591 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1592
John McCallc3c07662011-07-13 06:10:41 +00001593 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001594}
1595
John McCallbdc4d802011-07-09 01:37:26 +00001596void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1597 llvm::Value *addr,
1598 QualType type) {
1599 const RecordType *rtype = type->castAs<RecordType>();
1600 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1601 const CXXDestructorDecl *dtor = record->getDestructor();
1602 assert(!dtor->isTrivial());
1603 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001604 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001605}
1606
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001607void
1608CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001609 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001610 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001611 llvm::Value *This,
1612 CallExpr::const_arg_iterator ArgBeg,
1613 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001614
1615 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001616 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001617 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001618 // If debug info for this class has not been emitted then this is the
1619 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001620 const CXXRecordDecl *Parent = D->getParent();
1621 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1622 Parent->getLocation());
1623 }
1624
John McCall8b6bbeb2010-02-06 00:25:16 +00001625 if (D->isTrivial()) {
1626 if (ArgBeg == ArgEnd) {
1627 // Trivial default constructor, no codegen required.
1628 assert(D->isDefaultConstructor() &&
1629 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001630 return;
1631 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001632
1633 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001634 assert(D->isCopyOrMoveConstructor() &&
1635 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001636
John McCall8b6bbeb2010-02-06 00:25:16 +00001637 const Expr *E = (*ArgBeg);
1638 QualType Ty = E->getType();
1639 llvm::Value *Src = EmitLValue(E).getAddress();
1640 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001641 return;
1642 }
1643
Douglas Gregor378e1e72013-01-31 05:50:40 +00001644 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase,
1645 Delegating);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001646 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1647
Richard Smith4def70d2012-10-09 19:52:38 +00001648 // FIXME: Provide a source location here.
1649 EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001650 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1651 ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001652}
1653
John McCallc0bf4622010-02-23 00:48:20 +00001654void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001655CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1656 llvm::Value *This, llvm::Value *Src,
1657 CallExpr::const_arg_iterator ArgBeg,
1658 CallExpr::const_arg_iterator ArgEnd) {
1659 if (D->isTrivial()) {
1660 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001661 assert(D->isCopyOrMoveConstructor() &&
1662 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001663 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1664 return;
1665 }
1666 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1667 clang::Ctor_Complete);
1668 assert(D->isInstance() &&
1669 "Trying to emit a member call expr on a static method!");
1670
1671 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1672
1673 CallArgList Args;
1674
1675 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001676 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001677
1678
1679 // Push the src ptr.
1680 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001681 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001682 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001683 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001684
1685 // Skip over first argument (Src).
1686 ++ArgBeg;
1687 CallExpr::const_arg_iterator Arg = ArgBeg;
1688 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1689 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1690 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001691 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001692 }
1693 // Either we've emitted all the call args, or we have a call to a
1694 // variadic function.
1695 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1696 "Extra arguments in non-variadic function!");
1697 // If we still have any arguments, emit them using the type of the argument.
1698 for (; Arg != ArgEnd; ++Arg) {
1699 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001700 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001701 }
1702
John McCall0f3d0972012-07-07 06:41:13 +00001703 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1704 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001705}
1706
1707void
John McCallc0bf4622010-02-23 00:48:20 +00001708CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1709 CXXCtorType CtorType,
1710 const FunctionArgList &Args) {
1711 CallArgList DelegateArgs;
1712
1713 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1714 assert(I != E && "no parameters to constructor");
1715
1716 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001717 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001718 ++I;
1719
1720 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001721 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001722 /*ForVirtualBase=*/false,
1723 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001724 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001725 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001726
Anders Carlssonaf440352010-03-23 04:11:45 +00001727 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001728 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001729 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001730 ++I;
1731 }
1732 }
1733
1734 // Explicit arguments.
1735 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001736 const VarDecl *param = *I;
1737 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001738 }
1739
John McCallde5d3c72012-02-17 03:33:10 +00001740 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001741 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1742 ReturnValueSlot(), DelegateArgs, Ctor);
1743}
1744
Sean Huntb76af9c2011-05-03 23:05:34 +00001745namespace {
1746 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1747 const CXXDestructorDecl *Dtor;
1748 llvm::Value *Addr;
1749 CXXDtorType Type;
1750
1751 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1752 CXXDtorType Type)
1753 : Dtor(D), Addr(Addr), Type(Type) {}
1754
John McCallad346f42011-07-12 20:27:29 +00001755 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001756 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001757 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001758 }
1759 };
1760}
1761
Sean Hunt059ce0d2011-05-01 07:04:31 +00001762void
1763CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1764 const FunctionArgList &Args) {
1765 assert(Ctor->isDelegatingConstructor());
1766
1767 llvm::Value *ThisPtr = LoadCXXThis();
1768
Eli Friedmanf3940782011-12-03 00:54:26 +00001769 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001770 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001771 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001772 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001773 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001774 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001775 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001776
1777 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001778
Sean Huntb76af9c2011-05-03 23:05:34 +00001779 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001780 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001781 CXXDtorType Type =
1782 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1783
1784 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1785 ClassDecl->getDestructor(),
1786 ThisPtr, Type);
1787 }
1788}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001789
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001790void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1791 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001792 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001793 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001794 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001795 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001796 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001797 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001798 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001799 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1800 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001801
1802 if (!Callee)
1803 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001804
Richard Smith4def70d2012-10-09 19:52:38 +00001805 // FIXME: Provide a source location here.
1806 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001807 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1808 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001809}
1810
John McCall291ae942010-07-21 01:41:18 +00001811namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001812 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001813 const CXXDestructorDecl *Dtor;
1814 llvm::Value *Addr;
1815
1816 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1817 : Dtor(D), Addr(Addr) {}
1818
John McCallad346f42011-07-12 20:27:29 +00001819 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001820 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001821 /*ForVirtualBase=*/false,
1822 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001823 }
1824 };
1825}
1826
John McCall81407d42010-07-21 06:29:51 +00001827void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1828 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001829 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001830}
1831
John McCallf1549f62010-07-06 01:34:17 +00001832void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1833 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1834 if (!ClassDecl) return;
1835 if (ClassDecl->hasTrivialDestructor()) return;
1836
1837 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001838 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001839 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001840}
1841
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001842llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001843CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1844 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001845 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001846 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001847 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001848 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001849
1850 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001851 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1852 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001853 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001854 ConvertType(getContext().getPointerDiffType());
1855
1856 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1857 PtrDiffTy->getPointerTo());
1858
1859 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1860
1861 return VBaseOffset;
1862}
1863
Anders Carlssond103f9f2010-03-28 19:40:00 +00001864void
1865CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001866 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001867 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001868 llvm::Constant *VTable,
1869 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001870 const CXXRecordDecl *RD = Base.getBase();
1871
Anders Carlssond103f9f2010-03-28 19:40:00 +00001872 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001873 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001874
Anders Carlssonc83f1062010-03-29 01:08:49 +00001875 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001876 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001877 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001878 // Get the secondary vpointer index.
1879 uint64_t VirtualPointerIndex =
1880 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1881
1882 /// Load the VTT.
1883 llvm::Value *VTT = LoadCXXVTT();
1884 if (VirtualPointerIndex)
1885 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1886
1887 // And load the address point from the VTT.
1888 VTableAddressPoint = Builder.CreateLoad(VTT);
1889 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001890 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001891 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001892 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001893 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001894 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001895
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001896 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001897 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001898 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001899
1900 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1901 // We need to use the virtual base offset offset because the virtual base
1902 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001903 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1904 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001905 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001906 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001907 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001908 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001909 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001910
1911 // Apply the offsets.
1912 llvm::Value *VTableField = LoadCXXThis();
1913
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001914 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001915 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1916 NonVirtualOffset,
1917 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001918
Anders Carlssond103f9f2010-03-28 19:40:00 +00001919 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001920 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001921 VTableAddressPoint->getType()->getPointerTo();
1922 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001923 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1924 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001925}
1926
Anders Carlsson603d6d12010-03-28 21:07:49 +00001927void
1928CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001929 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001930 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001931 bool BaseIsNonVirtualPrimaryBase,
1932 llvm::Constant *VTable,
1933 const CXXRecordDecl *VTableClass,
1934 VisitedVirtualBasesSetTy& VBases) {
1935 // If this base is a non-virtual primary base the address point has already
1936 // been set.
1937 if (!BaseIsNonVirtualPrimaryBase) {
1938 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001939 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1940 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001941 }
1942
1943 const CXXRecordDecl *RD = Base.getBase();
1944
1945 // Traverse bases.
1946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1947 E = RD->bases_end(); I != E; ++I) {
1948 CXXRecordDecl *BaseDecl
1949 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1950
1951 // Ignore classes without a vtable.
1952 if (!BaseDecl->isDynamicClass())
1953 continue;
1954
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001955 CharUnits BaseOffset;
1956 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001957 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001958
1959 if (I->isVirtual()) {
1960 // Check if we've visited this virtual base before.
1961 if (!VBases.insert(BaseDecl))
1962 continue;
1963
1964 const ASTRecordLayout &Layout =
1965 getContext().getASTRecordLayout(VTableClass);
1966
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001967 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1968 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001969 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001970 } else {
1971 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1972
Ken Dyck4230d522011-03-24 01:21:01 +00001973 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001974 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001975 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001976 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001977 }
1978
Ken Dyck4230d522011-03-24 01:21:01 +00001979 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001980 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001981 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001982 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001983 VTable, VTableClass, VBases);
1984 }
1985}
1986
1987void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1988 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001989 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001990 return;
1991
Anders Carlsson07036902010-03-26 04:39:42 +00001992 // Get the VTable.
1993 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001994
Anders Carlsson603d6d12010-03-28 21:07:49 +00001995 // Initialize the vtable pointers for this class and all of its bases.
1996 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001997 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1998 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001999 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00002000 /*BaseIsNonVirtualPrimaryBase=*/false,
2001 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002002}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002003
2004llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002005 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002006 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002007 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2008 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2009 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002010}
Anders Carlssona2447e02011-05-08 20:32:23 +00002011
2012static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2013 const Expr *E = Base;
2014
2015 while (true) {
2016 E = E->IgnoreParens();
2017 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2018 if (CE->getCastKind() == CK_DerivedToBase ||
2019 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2020 CE->getCastKind() == CK_NoOp) {
2021 E = CE->getSubExpr();
2022 continue;
2023 }
2024 }
2025
2026 break;
2027 }
2028
2029 QualType DerivedType = E->getType();
2030 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2031 DerivedType = PTy->getPointeeType();
2032
2033 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2034}
2035
2036// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2037// quite what we want.
2038static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2039 while (true) {
2040 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2041 E = PE->getSubExpr();
2042 continue;
2043 }
2044
2045 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2046 if (CE->getCastKind() == CK_NoOp) {
2047 E = CE->getSubExpr();
2048 continue;
2049 }
2050 }
2051 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2052 if (UO->getOpcode() == UO_Extension) {
2053 E = UO->getSubExpr();
2054 continue;
2055 }
2056 }
2057 return E;
2058 }
2059}
2060
2061/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2062/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002063static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2064 const CXXMethodDecl *MD) {
2065 // If the most derived class is marked final, we know that no subclass can
2066 // override this member function and so we can devirtualize it. For example:
2067 //
2068 // struct A { virtual void f(); }
2069 // struct B final : A { };
2070 //
2071 // void f(B *b) {
2072 // b->f();
2073 // }
2074 //
2075 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2076 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2077 return true;
2078
2079 // If the member function is marked 'final', we know that it can't be
2080 // overridden and can therefore devirtualize it.
2081 if (MD->hasAttr<FinalAttr>())
2082 return true;
2083
2084 // Similarly, if the class itself is marked 'final' it can't be overridden
2085 // and we can therefore devirtualize the member function call.
2086 if (MD->getParent()->hasAttr<FinalAttr>())
2087 return true;
2088
2089 Base = skipNoOpCastsAndParens(Base);
2090 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2091 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2092 // This is a record decl. We know the type and can devirtualize it.
2093 return VD->getType()->isRecordType();
2094 }
2095
2096 return false;
2097 }
2098
2099 // We can always devirtualize calls on temporary object expressions.
2100 if (isa<CXXConstructExpr>(Base))
2101 return true;
2102
2103 // And calls on bound temporaries.
2104 if (isa<CXXBindTemporaryExpr>(Base))
2105 return true;
2106
2107 // Check if this is a call expr that returns a record type.
2108 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2109 return CE->getCallReturnType()->isRecordType();
2110
2111 // We can't devirtualize the call.
2112 return false;
2113}
2114
2115static bool UseVirtualCall(ASTContext &Context,
2116 const CXXOperatorCallExpr *CE,
2117 const CXXMethodDecl *MD) {
2118 if (!MD->isVirtual())
2119 return false;
2120
2121 // When building with -fapple-kext, all calls must go through the vtable since
2122 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002123 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002124 return true;
2125
2126 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2127}
2128
2129llvm::Value *
2130CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2131 const CXXMethodDecl *MD,
2132 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002133 llvm::FunctionType *fnType =
2134 CGM.getTypes().GetFunctionType(
2135 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002136
2137 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002138 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002139
John McCallde5d3c72012-02-17 03:33:10 +00002140 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002141}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002142
John McCall0f3d0972012-07-07 06:41:13 +00002143void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2144 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002145 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002146 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002147 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002148 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002149 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002150
Eli Friedman21f6ed92012-02-16 03:47:28 +00002151 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002152 const CGFunctionInfo &calleeFnInfo =
2153 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2154 llvm::Value *callee =
2155 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2156 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002157
John McCall0f3d0972012-07-07 06:41:13 +00002158 // Prepare the return slot.
2159 const FunctionProtoType *FPT =
2160 callOperator->getType()->castAs<FunctionProtoType>();
2161 QualType resultType = FPT->getResultType();
2162 ReturnValueSlot returnSlot;
2163 if (!resultType->isVoidType() &&
2164 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2165 hasAggregateLLVMType(calleeFnInfo.getReturnType()))
2166 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2167
2168 // We don't need to separately arrange the call arguments because
2169 // the call can't be variadic anyway --- it's impossible to forward
2170 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002171
2172 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002173 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2174 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002175
John McCall0f3d0972012-07-07 06:41:13 +00002176 // If necessary, copy the returned value into the slot.
2177 if (!resultType->isVoidType() && returnSlot.isNull())
2178 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002179 else
2180 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002181}
2182
Eli Friedman64bee652012-02-25 02:48:22 +00002183void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2184 const BlockDecl *BD = BlockInfo->getBlockDecl();
2185 const VarDecl *variable = BD->capture_begin()->getVariable();
2186 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2187
2188 // Start building arguments for forwarding call
2189 CallArgList CallArgs;
2190
2191 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2192 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2193 CallArgs.add(RValue::get(ThisPtr), ThisType);
2194
2195 // Add the rest of the parameters.
2196 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2197 E = BD->param_end(); I != E; ++I) {
2198 ParmVarDecl *param = *I;
2199 EmitDelegateCallArg(CallArgs, param);
2200 }
2201
2202 EmitForwardingCallToLambda(Lambda, CallArgs);
2203}
2204
2205void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2206 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
2207 // FIXME: Making this work correctly is nasty because it requires either
2208 // cloning the body of the call operator or making the call operator forward.
2209 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
2210 return;
2211 }
2212
Eli Friedman64bee652012-02-25 02:48:22 +00002213 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002214}
2215
2216void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2217 const CXXRecordDecl *Lambda = MD->getParent();
2218
2219 // Start building arguments for forwarding call
2220 CallArgList CallArgs;
2221
2222 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2223 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2224 CallArgs.add(RValue::get(ThisPtr), ThisType);
2225
2226 // Add the rest of the parameters.
2227 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2228 E = MD->param_end(); I != E; ++I) {
2229 ParmVarDecl *param = *I;
2230 EmitDelegateCallArg(CallArgs, param);
2231 }
2232
2233 EmitForwardingCallToLambda(Lambda, CallArgs);
2234}
2235
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002236void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2237 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002238 // FIXME: Making this work correctly is nasty because it requires either
2239 // cloning the body of the call operator or making the call operator forward.
2240 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002241 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002242 }
2243
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002244 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002245}