blob: ce32acd0da1f141a0825c7875403cda3838f5129 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson9a57c5a2009-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 Friedman2495ab02012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000016#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000017#include "clang/AST/CXXInheritance.h"
John McCall769250e2010-09-17 02:31:44 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000019#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000020#include "clang/AST/StmtCXX.h"
Devang Patelb6ed3692011-02-22 20:55:26 +000021#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000022
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000023using namespace clang;
24using namespace CodeGen;
25
Ken Dycka1a4ae32011-03-22 00:53:26 +000026static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000027ComputeNonVirtualBaseClassOffset(ASTContext &Context,
28 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000029 CastExpr::path_const_iterator Start,
30 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000031 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000032
33 const CXXRecordDecl *RD = DerivedClass;
34
John McCallcf142162010-08-07 06:22:56 +000035 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000036 const CXXBaseSpecifier *Base = *I;
37 assert(!Base->isVirtual() && "Should not see virtual bases here!");
38
39 // Get the layout.
40 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
41
42 const CXXRecordDecl *BaseDecl =
43 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
44
45 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000046 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000047
48 RD = BaseDecl;
49 }
50
Ken Dycka1a4ae32011-03-22 00:53:26 +000051 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000052}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000053
Anders Carlsson9150a2a2009-09-29 03:13:20 +000054llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000055CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000056 CastExpr::path_const_iterator PathBegin,
57 CastExpr::path_const_iterator PathEnd) {
58 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000059
Ken Dycka1a4ae32011-03-22 00:53:26 +000060 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000061 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
62 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000063 if (Offset.isZero())
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000064 return 0;
65
Chris Lattner2192fe52011-07-18 04:24:23 +000066 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000067 Types.ConvertType(getContext().getPointerDiffType());
68
Ken Dycka1a4ae32011-03-22 00:53:26 +000069 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000070}
71
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000072/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000073/// This should only be used for (1) non-virtual bases or (2) virtual bases
74/// when the type is known to be complete (e.g. in complete destructors).
75///
76/// The object pointed to by 'This' is assumed to be non-null.
77llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000078CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
79 const CXXRecordDecl *Derived,
80 const CXXRecordDecl *Base,
81 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000082 // 'this' must be a pointer (in some address space) to Derived.
83 assert(This->getType()->isPointerTy() &&
84 cast<llvm::PointerType>(This->getType())->getElementType()
85 == ConvertType(Derived));
86
87 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000088 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000089 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000090 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000091 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000092 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000093 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000094
95 // Shift and cast down to the base type.
96 // TODO: for complete types, this should be possible with a GEP.
97 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +000098 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +000099 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000105}
John McCall6ce74722010-02-16 04:15:37 +0000106
Anders Carlsson53cebd12010-04-20 16:03:35 +0000107static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
109 CharUnits nonVirtualOffset,
110 llvm::Value *virtualOffset) {
111 // Assert that we have something to do.
112 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
113
114 // Compute the offset from the static and dynamic components.
115 llvm::Value *baseOffset;
116 if (!nonVirtualOffset.isZero()) {
117 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
118 nonVirtualOffset.getQuantity());
119 if (virtualOffset) {
120 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
121 }
122 } else {
123 baseOffset = virtualOffset;
124 }
Anders Carlsson53cebd12010-04-20 16:03:35 +0000125
126 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000127 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
128 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
129 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000130}
131
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000132llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000133CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000134 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000135 CastExpr::path_const_iterator PathBegin,
136 CastExpr::path_const_iterator PathEnd,
Anders Carlssond829a022010-04-24 21:06:20 +0000137 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000138 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000139
John McCallcf142162010-08-07 06:22:56 +0000140 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlssond829a022010-04-24 21:06:20 +0000141 const CXXRecordDecl *VBase = 0;
142
John McCall13a39c62012-08-01 05:04:58 +0000143 // Sema has done some convenient canonicalization here: if the
144 // access path involved any virtual steps, the conversion path will
145 // *start* with a step down to the correct virtual base subobject,
146 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
John McCall13a39c62012-08-01 05:04:58 +0000152
153 // Compute the static offset of the ultimate destination within its
154 // allocating subobject (the virtual base, if there is one, or else
155 // the "complete" object that we see).
Ken Dycka1a4ae32011-03-22 00:53:26 +0000156 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000157 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000158 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000159
John McCall13a39c62012-08-01 05:04:58 +0000160 // If there's a virtual step, we can sometimes "devirtualize" it.
161 // For now, that's limited to when the derived type is final.
162 // TODO: "devirtualize" this for accesses to known-complete objects.
163 if (VBase && Derived->hasAttr<FinalAttr>()) {
164 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
165 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
166 NonVirtualOffset += vBaseOffset;
167 VBase = 0; // we no longer have a virtual step
168 }
169
Anders Carlssond829a022010-04-24 21:06:20 +0000170 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000171 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000172 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000173
174 // If the static offset is zero and we don't have a virtual step,
175 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000176 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlssond829a022010-04-24 21:06:20 +0000177 return Builder.CreateBitCast(Value, BasePtrTy);
178 }
John McCall13a39c62012-08-01 05:04:58 +0000179
180 llvm::BasicBlock *origBB = 0;
181 llvm::BasicBlock *endBB = 0;
Anders Carlssond829a022010-04-24 21:06:20 +0000182
John McCall13a39c62012-08-01 05:04:58 +0000183 // Skip over the offset (and the vtable load) if we're supposed to
184 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000185 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000186 origBB = Builder.GetInsertBlock();
187 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
188 endBB = createBasicBlock("cast.end");
Anders Carlssond829a022010-04-24 21:06:20 +0000189
John McCall13a39c62012-08-01 05:04:58 +0000190 llvm::Value *isNull = Builder.CreateIsNull(Value);
191 Builder.CreateCondBr(isNull, endBB, notNullBB);
192 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000193 }
194
John McCall13a39c62012-08-01 05:04:58 +0000195 // Compute the virtual offset.
Anders Carlssond829a022010-04-24 21:06:20 +0000196 llvm::Value *VirtualOffset = 0;
Anders Carlssona376b532011-01-29 03:18:56 +0000197 if (VBase) {
John McCall13a39c62012-08-01 05:04:58 +0000198 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000199 }
Anders Carlssond829a022010-04-24 21:06:20 +0000200
John McCall13a39c62012-08-01 05:04:58 +0000201 // Apply both offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000202 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000203 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000204 VirtualOffset);
205
John McCall13a39c62012-08-01 05:04:58 +0000206 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000207 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000208
209 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000210 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000211 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
212 Builder.CreateBr(endBB);
213 EmitBlock(endBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000214
John McCall13a39c62012-08-01 05:04:58 +0000215 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
216 PHI->addIncoming(Value, notNullBB);
217 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000218 Value = PHI;
219 }
220
221 return Value;
222}
223
224llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000225CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000226 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000227 CastExpr::path_const_iterator PathBegin,
228 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000229 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000230 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000231
Anders Carlsson8c793172009-11-23 17:57:54 +0000232 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000233 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000234 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlsson8c793172009-11-23 17:57:54 +0000235
Anders Carlsson600f7372010-01-31 01:43:37 +0000236 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000237 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000238
239 if (!NonVirtualOffset) {
240 // No offset, we can just cast back.
241 return Builder.CreateBitCast(Value, DerivedPtrTy);
242 }
243
Anders Carlsson8c793172009-11-23 17:57:54 +0000244 llvm::BasicBlock *CastNull = 0;
245 llvm::BasicBlock *CastNotNull = 0;
246 llvm::BasicBlock *CastEnd = 0;
247
248 if (NullCheckValue) {
249 CastNull = createBasicBlock("cast.null");
250 CastNotNull = createBasicBlock("cast.notnull");
251 CastEnd = createBasicBlock("cast.end");
252
Anders Carlsson98981b12011-04-11 00:30:07 +0000253 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000254 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
255 EmitBlock(CastNotNull);
256 }
257
Anders Carlsson600f7372010-01-31 01:43:37 +0000258 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000259 Value = Builder.CreateBitCast(Value, Int8PtrTy);
260 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
261 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000262
263 // Just cast.
264 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000265
266 if (NullCheckValue) {
267 Builder.CreateBr(CastEnd);
268 EmitBlock(CastNull);
269 Builder.CreateBr(CastEnd);
270 EmitBlock(CastEnd);
271
Jay Foad20c0f022011-03-30 11:28:58 +0000272 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000273 PHI->addIncoming(Value, CastNotNull);
274 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
275 CastNull);
276 Value = PHI;
277 }
278
279 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000280}
Anders Carlsson093bdff2010-03-30 03:27:09 +0000281
Anders Carlssone36a6b32010-01-02 01:01:18 +0000282/// GetVTTParameter - Return the VTT parameter that should be passed to a
283/// base constructor/destructor with virtual bases.
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000284static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
Douglas Gregor61535002013-01-31 05:50:40 +0000285 bool ForVirtualBase,
286 bool Delegating) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000287 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000288 // This constructor/destructor does not need a VTT parameter.
289 return 0;
290 }
291
292 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
293 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000294
Anders Carlssone36a6b32010-01-02 01:01:18 +0000295 llvm::Value *VTT;
296
John McCall5c60a6f2010-02-18 19:59:28 +0000297 uint64_t SubVTTIndex;
298
Douglas Gregor61535002013-01-31 05:50:40 +0000299 if (Delegating) {
300 // If this is a delegating constructor call, just load the VTT.
301 return CGF.LoadCXXVTT();
302 } else if (RD == Base) {
303 // If the record matches the base, this is the complete ctor/dtor
304 // variant calling the base variant in a class with virtual bases.
Anders Carlssona864caf2010-03-23 04:11:45 +0000305 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000306 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000307 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000308 SubVTTIndex = 0;
309 } else {
Anders Carlsson859b3062010-05-02 23:53:25 +0000310 const ASTRecordLayout &Layout =
311 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000312 CharUnits BaseOffset = ForVirtualBase ?
313 Layout.getVBaseClassOffset(Base) :
314 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000315
316 SubVTTIndex =
317 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000318 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
319 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000320
Anders Carlssona864caf2010-03-23 04:11:45 +0000321 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000322 // A VTT parameter was passed to the constructor, use it.
323 VTT = CGF.LoadCXXVTT();
324 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
325 } else {
326 // We're the complete constructor, so get the VTT by name.
Anders Carlsson883fc722011-01-29 19:16:51 +0000327 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000328 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
329 }
330
331 return VTT;
332}
333
John McCall1d987562010-07-21 01:23:41 +0000334namespace {
John McCallf99a6312010-07-21 05:30:47 +0000335 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000336 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000337 const CXXRecordDecl *BaseClass;
338 bool BaseIsVirtual;
339 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
340 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000341
John McCall30317fd2011-07-12 20:27:29 +0000342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000343 const CXXRecordDecl *DerivedClass =
344 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
345
346 const CXXDestructorDecl *D = BaseClass->getDestructor();
347 llvm::Value *Addr =
348 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
349 DerivedClass, BaseClass,
350 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000351 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
352 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000353 }
354 };
John McCall769250e2010-09-17 02:31:44 +0000355
356 /// A visitor which checks whether an initializer uses 'this' in a
357 /// way which requires the vtable to be properly set.
358 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
359 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
360
361 bool UsesThis;
362
363 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
364
365 // Black-list all explicit and implicit references to 'this'.
366 //
367 // Do we need to worry about external references to 'this' derived
368 // from arbitrary code? If so, then anything which runs arbitrary
369 // external code might potentially access the vtable.
370 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
371 };
372}
373
374static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
375 DynamicThisUseChecker Checker(C);
376 Checker.Visit(const_cast<Expr*>(Init));
377 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000378}
379
Anders Carlssonfb404882009-12-24 22:46:43 +0000380static void EmitBaseInitializer(CodeGenFunction &CGF,
381 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000382 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000383 CXXCtorType CtorType) {
384 assert(BaseInit->isBaseInitializer() &&
385 "Must have base initializer!");
386
387 llvm::Value *ThisPtr = CGF.LoadCXXThis();
388
389 const Type *BaseType = BaseInit->getBaseClass();
390 CXXRecordDecl *BaseClassDecl =
391 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
392
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000393 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000394
395 // The base constructor doesn't construct virtual bases.
396 if (CtorType == Ctor_Base && isBaseVirtual)
397 return;
398
John McCall769250e2010-09-17 02:31:44 +0000399 // If the initializer for the base (other than the constructor
400 // itself) accesses 'this' in any way, we need to initialize the
401 // vtables.
402 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
403 CGF.InitializeVTablePointers(ClassDecl);
404
John McCall6ce74722010-02-16 04:15:37 +0000405 // We can pretend to be a complete class because it only matters for
406 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000407 llvm::Value *V =
408 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000409 BaseClassDecl,
410 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000411 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000412 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000413 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000414 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000415 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000416 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000417
418 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000421 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000422 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
423 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000424}
425
Douglas Gregor94f9a482010-05-05 05:51:00 +0000426static void EmitAggMemberInitializer(CodeGenFunction &CGF,
427 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000428 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000429 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000430 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000431 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000432 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000433 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000434 LValue LV = LHS;
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000435 { // Scope for Cleanups.
436 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000437
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000438 if (ArrayIndexVar) {
439 // If we have an array index variable, load it and use it as an offset.
440 // Then, increment the value.
441 llvm::Value *Dest = LHS.getAddress();
442 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
443 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
444 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
445 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
446 CGF.Builder.CreateStore(Next, ArrayIndexVar);
447
448 // Update the LValue.
449 LV.setAddress(Dest);
450 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
451 LV.setAlignment(std::min(Align, LV.getAlignment()));
452 }
453
454 if (!CGF.hasAggregateLLVMType(T)) {
455 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
456 } else if (T->isAnyComplexType()) {
457 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
458 LV.isVolatileQualified());
459 } else {
460 AggValueSlot Slot =
461 AggValueSlot::forLValue(LV,
462 AggValueSlot::IsDestructed,
463 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000464 AggValueSlot::IsNotAliased);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000465
466 CGF.EmitAggExpr(Init, Slot);
467 }
Douglas Gregor94f9a482010-05-05 05:51:00 +0000468 }
John McCall7a626f62010-09-15 10:14:12 +0000469
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000470 // Now, outside of the initializer cleanup scope, destroy the backing array
471 // for a std::initializer_list member.
Sebastian Redld026dc42012-02-19 16:03:09 +0000472 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000473
Douglas Gregor94f9a482010-05-05 05:51:00 +0000474 return;
475 }
476
477 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
478 assert(Array && "Array initialization without the array type?");
479 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000480 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000481 assert(IndexVar && "Array index variable not loaded");
482
483 // Initialize this index variable to zero.
484 llvm::Value* Zero
485 = llvm::Constant::getNullValue(
486 CGF.ConvertType(CGF.getContext().getSizeType()));
487 CGF.Builder.CreateStore(Zero, IndexVar);
488
489 // Start the loop with a block that tests the condition.
490 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
491 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
492
493 CGF.EmitBlock(CondBlock);
494
495 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
496 // Generate: if (loop-index < number-of-elements) fall to the loop body,
497 // otherwise, go to the block after the for-loop.
498 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000499 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000500 llvm::Value *NumElementsPtr =
501 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000502 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
503 "isless");
504
505 // If the condition is true, execute the body.
506 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
507
508 CGF.EmitBlock(ForBody);
509 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
510
511 {
John McCallbd309292010-07-06 01:34:17 +0000512 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000513
514 // Inside the loop body recurse to emit the inner loop or, eventually, the
515 // constructor call.
Eli Friedman6ae63022012-02-14 02:15:49 +0000516 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
517 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000518 }
519
520 CGF.EmitBlock(ContinueBlock);
521
522 // Emit the increment of the loop counter.
523 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
524 Counter = CGF.Builder.CreateLoad(IndexVar);
525 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
526 CGF.Builder.CreateStore(NextVal, IndexVar);
527
528 // Finally, branch back up to the condition for the next iteration.
529 CGF.EmitBranch(CondBlock);
530
531 // Emit the fall-through block.
532 CGF.EmitBlock(AfterFor, true);
533}
John McCall1d987562010-07-21 01:23:41 +0000534
Anders Carlssonfb404882009-12-24 22:46:43 +0000535static void EmitMemberInitializer(CodeGenFunction &CGF,
536 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000537 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000538 const CXXConstructorDecl *Constructor,
539 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000540 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000541 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000542 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000543
544 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000545 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000546 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000547
548 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000549 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000550 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000551
Francois Pichetd583da02010-12-04 09:14:42 +0000552 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000553 // If we are initializing an anonymous union field, drill down to
554 // the field.
555 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
556 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
557 IEnd = IndirectField->chain_end();
558 for ( ; I != IEnd; ++I)
559 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichetd583da02010-12-04 09:14:42 +0000560 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000561 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000562 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000563 }
564
Eli Friedman6ae63022012-02-14 02:15:49 +0000565 // Special case: if we are in a copy or move constructor, and we are copying
566 // an array of PODs or classes with trivial copy constructors, ignore the
567 // AST and perform the copy we know is equivalent.
568 // FIXME: This is hacky at best... if we had a bit more explicit information
569 // in the AST, we could generalize it more easily.
570 const ConstantArrayType *Array
571 = CGF.getContext().getAsConstantArrayType(FieldType);
572 if (Array && Constructor->isImplicitlyDefined() &&
573 Constructor->isCopyOrMoveConstructor()) {
574 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000575 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000576 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith993f25a2012-11-07 23:56:21 +0000577 (CE && CE->getConstructor()->isTrivial())) {
578 // Find the source pointer. We know it's the last argument because
579 // we know we're in an implicit copy constructor.
Eli Friedman6ae63022012-02-14 02:15:49 +0000580 unsigned SrcArgIndex = Args.size() - 1;
581 llvm::Value *SrcPtr
582 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000583 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
584 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman6ae63022012-02-14 02:15:49 +0000585
586 // Copy the aggregate.
587 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000588 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000589 return;
590 }
591 }
592
593 ArrayRef<VarDecl *> ArrayIndexes;
594 if (MemberInit->getNumArrayIndices())
595 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000596 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000597}
598
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000599void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
600 LValue LHS, Expr *Init,
601 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000602 QualType FieldType = Field->getType();
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000603 if (!hasAggregateLLVMType(FieldType)) {
John McCall31168b02011-06-15 23:02:42 +0000604 if (LHS.isSimple()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000605 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000606 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000607 RValue RHS = RValue::get(EmitScalarExpr(Init));
608 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000609 }
Eli Friedman6ae63022012-02-14 02:15:49 +0000610 } else if (FieldType->isAnyComplexType()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000611 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlssonfb404882009-12-24 22:46:43 +0000612 } else {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000613 llvm::Value *ArrayIndexVar = 0;
Eli Friedman6ae63022012-02-14 02:15:49 +0000614 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000615 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000616
617 // The LHS is a pointer to the first object we'll be constructing, as
618 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000619 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
620 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000621 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000622 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
623 BasePtr);
624 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000625
626 // Create an array index that will be used to walk over all of the
627 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000628 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000629 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000630 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000631
Douglas Gregor94f9a482010-05-05 05:51:00 +0000632
633 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000634 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000635 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000636 }
637
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000638 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000639 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000640 }
John McCall12cc42a2013-02-01 05:11:40 +0000641
642 // Ensure that we destroy this object if an exception is thrown
643 // later in the constructor.
644 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
645 if (needsEHCleanup(dtorKind))
646 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000647}
648
John McCallf8ff7b92010-02-23 00:48:20 +0000649/// Checks whether the given constructor is a valid subject for the
650/// complete-to-base constructor delegation optimization, i.e.
651/// emitting the complete constructor as a simple call to the base
652/// constructor.
653static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
654
655 // Currently we disable the optimization for classes with virtual
656 // bases because (1) the addresses of parameter variables need to be
657 // consistent across all initializers but (2) the delegate function
658 // call necessarily creates a second copy of the parameter variable.
659 //
660 // The limiting example (purely theoretical AFAIK):
661 // struct A { A(int &c) { c++; } };
662 // struct B : virtual A {
663 // B(int count) : A(count) { printf("%d\n", count); }
664 // };
665 // ...although even this example could in principle be emitted as a
666 // delegation since the address of the parameter doesn't escape.
667 if (Ctor->getParent()->getNumVBases()) {
668 // TODO: white-list trivial vbase initializers. This case wouldn't
669 // be subject to the restrictions below.
670
671 // TODO: white-list cases where:
672 // - there are no non-reference parameters to the constructor
673 // - the initializers don't access any non-reference parameters
674 // - the initializers don't take the address of non-reference
675 // parameters
676 // - etc.
677 // If we ever add any of the above cases, remember that:
678 // - function-try-blocks will always blacklist this optimization
679 // - we need to perform the constructor prologue and cleanup in
680 // EmitConstructorBody.
681
682 return false;
683 }
684
685 // We also disable the optimization for variadic functions because
686 // it's impossible to "re-pass" varargs.
687 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
688 return false;
689
Alexis Hunt61bc1732011-05-01 07:04:31 +0000690 // FIXME: Decide if we can do a delegation of a delegating constructor.
691 if (Ctor->isDelegatingConstructor())
692 return false;
693
John McCallf8ff7b92010-02-23 00:48:20 +0000694 return true;
695}
696
John McCallb81884d2010-02-19 09:25:03 +0000697/// EmitConstructorBody - Emits the body of the current constructor.
698void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
699 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
700 CXXCtorType CtorType = CurGD.getCtorType();
701
John McCallf8ff7b92010-02-23 00:48:20 +0000702 // Before we go any further, try the complete->base constructor
703 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000704 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall359b8852013-01-25 22:30:49 +0000705 CGM.getContext().getTargetInfo().getCXXABI().hasConstructorVariants()) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000706 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher7cdf9482011-10-13 21:45:18 +0000707 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000708 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
709 return;
710 }
711
John McCallb81884d2010-02-19 09:25:03 +0000712 Stmt *Body = Ctor->getBody();
713
John McCallf8ff7b92010-02-23 00:48:20 +0000714 // Enter the function-try-block before the constructor prologue if
715 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000716 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000717 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000718 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000719
John McCallbd309292010-07-06 01:34:17 +0000720 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCallb81884d2010-02-19 09:25:03 +0000721
John McCall88313032012-03-30 04:25:03 +0000722 // TODO: in restricted cases, we can emit the vbase initializers of
723 // a complete ctor and then delegate to the base ctor.
724
John McCallf8ff7b92010-02-23 00:48:20 +0000725 // Emit the constructor prologue, i.e. the base and member
726 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000727 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000728
729 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000730 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000731 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
732 else if (Body)
733 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000734
735 // Emit any cleanup blocks associated with the member or base
736 // initializers, which includes (along the exceptional path) the
737 // destructors for those members and bases that were fully
738 // constructed.
John McCallbd309292010-07-06 01:34:17 +0000739 PopCleanupBlocks(CleanupDepth);
John McCallb81884d2010-02-19 09:25:03 +0000740
John McCallf8ff7b92010-02-23 00:48:20 +0000741 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000742 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000743}
744
Anders Carlssonfb404882009-12-24 22:46:43 +0000745/// EmitCtorPrologue - This routine generates necessary code to initialize
746/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +0000747void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000748 CXXCtorType CtorType,
749 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +0000750 if (CD->isDelegatingConstructor())
751 return EmitDelegatingCXXConstructorCall(CD, Args);
752
Anders Carlssonfb404882009-12-24 22:46:43 +0000753 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +0000754
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000755 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlssonfb404882009-12-24 22:46:43 +0000756
Anders Carlssonfb404882009-12-24 22:46:43 +0000757 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
758 E = CD->init_end();
759 B != E; ++B) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000760 CXXCtorInitializer *Member = (*B);
Anders Carlssonfb404882009-12-24 22:46:43 +0000761
Alexis Hunt271c3682011-05-03 20:19:28 +0000762 if (Member->isBaseInitializer()) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000763 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Alexis Hunt271c3682011-05-03 20:19:28 +0000764 } else {
765 assert(Member->isAnyMemberInitializer() &&
766 "Delegating initializer on non-delegating constructor");
Anders Carlsson5dc86332010-02-02 19:58:43 +0000767 MemberInitializers.push_back(Member);
Alexis Hunt271c3682011-05-03 20:19:28 +0000768 }
Anders Carlssonfb404882009-12-24 22:46:43 +0000769 }
770
Anders Carlssond5895932010-03-28 21:07:49 +0000771 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +0000772
John McCallbd309292010-07-06 01:34:17 +0000773 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregor94f9a482010-05-05 05:51:00 +0000774 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlssonfb404882009-12-24 22:46:43 +0000775}
776
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000777static bool
778FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
779
780static bool
781HasTrivialDestructorBody(ASTContext &Context,
782 const CXXRecordDecl *BaseClassDecl,
783 const CXXRecordDecl *MostDerivedClassDecl)
784{
785 // If the destructor is trivial we don't have to check anything else.
786 if (BaseClassDecl->hasTrivialDestructor())
787 return true;
788
789 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
790 return false;
791
792 // Check fields.
793 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
794 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000795 const FieldDecl *Field = *I;
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000796
797 if (!FieldHasTrivialDestructorBody(Context, Field))
798 return false;
799 }
800
801 // Check non-virtual bases.
802 for (CXXRecordDecl::base_class_const_iterator I =
803 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
804 I != E; ++I) {
805 if (I->isVirtual())
806 continue;
807
808 const CXXRecordDecl *NonVirtualBase =
809 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
810 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
811 MostDerivedClassDecl))
812 return false;
813 }
814
815 if (BaseClassDecl == MostDerivedClassDecl) {
816 // Check virtual bases.
817 for (CXXRecordDecl::base_class_const_iterator I =
818 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
819 I != E; ++I) {
820 const CXXRecordDecl *VirtualBase =
821 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
822 if (!HasTrivialDestructorBody(Context, VirtualBase,
823 MostDerivedClassDecl))
824 return false;
825 }
826 }
827
828 return true;
829}
830
831static bool
832FieldHasTrivialDestructorBody(ASTContext &Context,
833 const FieldDecl *Field)
834{
835 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
836
837 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
838 if (!RT)
839 return true;
840
841 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
842 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
843}
844
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000845/// CanSkipVTablePointerInitialization - Check whether we need to initialize
846/// any vtable pointers before calling this destructor.
847static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +0000848 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000849 if (!Dtor->hasTrivialBody())
850 return false;
851
852 // Check the fields.
853 const CXXRecordDecl *ClassDecl = Dtor->getParent();
854 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
855 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000856 const FieldDecl *Field = *I;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000857
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000858 if (!FieldHasTrivialDestructorBody(Context, Field))
859 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000860 }
861
862 return true;
863}
864
John McCallb81884d2010-02-19 09:25:03 +0000865/// EmitDestructorBody - Emits the body of the current destructor.
866void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
867 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
868 CXXDtorType DtorType = CurGD.getDtorType();
869
John McCallf99a6312010-07-21 05:30:47 +0000870 // The call to operator delete in a deleting destructor happens
871 // outside of the function-try-block, which means it's always
872 // possible to delegate the destructor body to the complete
873 // destructor. Do so.
874 if (DtorType == Dtor_Deleting) {
875 EnterDtorCleanups(Dtor, Dtor_Deleting);
876 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +0000877 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +0000878 PopCleanupBlock();
879 return;
880 }
881
John McCallb81884d2010-02-19 09:25:03 +0000882 Stmt *Body = Dtor->getBody();
883
884 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +0000885 // anything else.
886 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +0000887 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000888 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000889
John McCallf99a6312010-07-21 05:30:47 +0000890 // Enter the epilogue cleanups.
891 RunCleanupsScope DtorEpilogue(*this);
892
John McCallb81884d2010-02-19 09:25:03 +0000893 // If this is the complete variant, just invoke the base variant;
894 // the epilogue will destruct the virtual bases. But we can't do
895 // this optimization if the body is a function-try-block, because
896 // we'd introduce *two* handler blocks.
John McCallf99a6312010-07-21 05:30:47 +0000897 switch (DtorType) {
898 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
899
900 case Dtor_Complete:
901 // Enter the cleanup scopes for virtual bases.
902 EnterDtorCleanups(Dtor, Dtor_Complete);
903
John McCall359b8852013-01-25 22:30:49 +0000904 if (!isTryBody &&
905 CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
John McCallf99a6312010-07-21 05:30:47 +0000906 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +0000907 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +0000908 break;
909 }
910 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +0000911
John McCallf99a6312010-07-21 05:30:47 +0000912 case Dtor_Base:
913 // Enter the cleanup scopes for fields and non-virtual bases.
914 EnterDtorCleanups(Dtor, Dtor_Base);
915
916 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000917 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
918 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +0000919
920 if (isTryBody)
921 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
922 else if (Body)
923 EmitStmt(Body);
924 else {
925 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
926 // nothing to do besides what's in the epilogue
927 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +0000928 // -fapple-kext must inline any call to this dtor into
929 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +0000930 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +0000931 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +0000932 break;
John McCallb81884d2010-02-19 09:25:03 +0000933 }
934
John McCallf99a6312010-07-21 05:30:47 +0000935 // Jump out through the epilogue cleanups.
936 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000937
938 // Exit the try if applicable.
939 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000940 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000941}
942
John McCallf99a6312010-07-21 05:30:47 +0000943namespace {
944 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +0000945 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000946 CallDtorDelete() {}
947
John McCall30317fd2011-07-12 20:27:29 +0000948 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000949 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
950 const CXXRecordDecl *ClassDecl = Dtor->getParent();
951 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
952 CGF.getContext().getTagDeclType(ClassDecl));
953 }
954 };
955
John McCall4bd0fb12011-07-12 16:41:08 +0000956 class DestroyField : public EHScopeStack::Cleanup {
957 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000958 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +0000959 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +0000960
John McCall4bd0fb12011-07-12 16:41:08 +0000961 public:
962 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
963 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000964 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +0000965 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +0000966
John McCall30317fd2011-07-12 20:27:29 +0000967 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +0000968 // Find the address of the field.
969 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000970 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
971 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
972 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +0000973 assert(LV.isSimple());
974
975 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +0000976 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +0000977 }
978 };
979}
980
Anders Carlssonfb404882009-12-24 22:46:43 +0000981/// EmitDtorEpilogue - Emit all code that comes at the end of class's
982/// destructor. This is to call destructors on members and base classes
983/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +0000984void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
985 CXXDtorType DtorType) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000986 assert(!DD->isTrivial() &&
987 "Should not emit dtor epilogue for trivial dtor!");
988
John McCallf99a6312010-07-21 05:30:47 +0000989 // The deleting-destructor phase just needs to call the appropriate
990 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +0000991 if (DtorType == Dtor_Deleting) {
992 assert(DD->getOperatorDelete() &&
993 "operator delete missing - EmitDtorEpilogue");
John McCallcda666c2010-07-21 07:22:38 +0000994 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall5c60a6f2010-02-18 19:59:28 +0000995 return;
996 }
997
John McCallf99a6312010-07-21 05:30:47 +0000998 const CXXRecordDecl *ClassDecl = DD->getParent();
999
Richard Smith20104042011-09-18 12:11:43 +00001000 // Unions have no bases and do not call field destructors.
1001 if (ClassDecl->isUnion())
1002 return;
1003
John McCallf99a6312010-07-21 05:30:47 +00001004 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001005 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001006
1007 // We push them in the forward order so that they'll be popped in
1008 // the reverse order.
1009 for (CXXRecordDecl::base_class_const_iterator I =
1010 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall5c60a6f2010-02-18 19:59:28 +00001011 I != E; ++I) {
1012 const CXXBaseSpecifier &Base = *I;
1013 CXXRecordDecl *BaseClassDecl
1014 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1015
1016 // Ignore trivial destructors.
1017 if (BaseClassDecl->hasTrivialDestructor())
1018 continue;
John McCallf99a6312010-07-21 05:30:47 +00001019
John McCallcda666c2010-07-21 07:22:38 +00001020 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1021 BaseClassDecl,
1022 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001023 }
John McCallf99a6312010-07-21 05:30:47 +00001024
John McCall5c60a6f2010-02-18 19:59:28 +00001025 return;
1026 }
1027
1028 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001029
1030 // Destroy non-virtual bases.
1031 for (CXXRecordDecl::base_class_const_iterator I =
1032 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1033 const CXXBaseSpecifier &Base = *I;
1034
1035 // Ignore virtual bases.
1036 if (Base.isVirtual())
1037 continue;
1038
1039 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1040
1041 // Ignore trivial destructors.
1042 if (BaseClassDecl->hasTrivialDestructor())
1043 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001044
John McCallcda666c2010-07-21 07:22:38 +00001045 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1046 BaseClassDecl,
1047 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001048 }
1049
1050 // Destroy direct fields.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001051 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlssonfb404882009-12-24 22:46:43 +00001052 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1053 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001054 const FieldDecl *field = *I;
John McCall4bd0fb12011-07-12 16:41:08 +00001055 QualType type = field->getType();
1056 QualType::DestructionKind dtorKind = type.isDestructedType();
1057 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001058
Richard Smith921bd202012-02-26 09:11:52 +00001059 // Anonymous union members do not have their destructors called.
1060 const RecordType *RT = type->getAsUnionType();
1061 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1062
John McCall4bd0fb12011-07-12 16:41:08 +00001063 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1064 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1065 getDestroyer(dtorKind),
1066 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001067 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001068}
1069
John McCallf677a8e2011-07-13 06:10:41 +00001070/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1071/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001072///
John McCallf677a8e2011-07-13 06:10:41 +00001073/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001074/// \param arrayType the type of the array to initialize
1075/// \param arrayBegin an arrayType*
1076/// \param zeroInitialize true if each element should be
1077/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001078void
John McCallf677a8e2011-07-13 06:10:41 +00001079CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1080 const ConstantArrayType *arrayType,
1081 llvm::Value *arrayBegin,
1082 CallExpr::const_arg_iterator argBegin,
1083 CallExpr::const_arg_iterator argEnd,
1084 bool zeroInitialize) {
1085 QualType elementType;
1086 llvm::Value *numElements =
1087 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001088
John McCallf677a8e2011-07-13 06:10:41 +00001089 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1090 argBegin, argEnd, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001091}
1092
John McCallf677a8e2011-07-13 06:10:41 +00001093/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1094/// constructor for each of several members of an array.
1095///
1096/// \param ctor the constructor to call for each element
1097/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001098/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001099/// \param arrayBegin a T*, where T is the type constructed by ctor
1100/// \param zeroInitialize true if each element should be
1101/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001102void
John McCallf677a8e2011-07-13 06:10:41 +00001103CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1104 llvm::Value *numElements,
1105 llvm::Value *arrayBegin,
1106 CallExpr::const_arg_iterator argBegin,
1107 CallExpr::const_arg_iterator argEnd,
1108 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001109
1110 // It's legal for numElements to be zero. This can happen both
1111 // dynamically, because x can be zero in 'new A[x]', and statically,
1112 // because of GCC extensions that permit zero-length arrays. There
1113 // are probably legitimate places where we could assume that this
1114 // doesn't happen, but it's not clear that it's worth it.
1115 llvm::BranchInst *zeroCheckBranch = 0;
1116
1117 // Optimize for a constant count.
1118 llvm::ConstantInt *constantCount
1119 = dyn_cast<llvm::ConstantInt>(numElements);
1120 if (constantCount) {
1121 // Just skip out if the constant count is zero.
1122 if (constantCount->isZero()) return;
1123
1124 // Otherwise, emit the check.
1125 } else {
1126 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1127 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1128 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1129 EmitBlock(loopBB);
1130 }
1131
John McCallf677a8e2011-07-13 06:10:41 +00001132 // Find the end of the array.
1133 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1134 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001135
John McCallf677a8e2011-07-13 06:10:41 +00001136 // Enter the loop, setting up a phi for the current location to initialize.
1137 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1138 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1139 EmitBlock(loopBB);
1140 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1141 "arrayctor.cur");
1142 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001143
Anders Carlsson27da15b2010-01-01 20:29:01 +00001144 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001145
1146 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001147
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001148 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001149 if (zeroInitialize)
1150 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001151
Anders Carlsson27da15b2010-01-01 20:29:01 +00001152 // C++ [class.temporary]p4:
1153 // There are two contexts in which temporaries are destroyed at a different
1154 // point than the end of the full-expression. The first context is when a
1155 // default constructor is called to initialize an element of an array.
1156 // If the constructor has one or more default arguments, the destruction of
1157 // every temporary created in a default argument expression is sequenced
1158 // before the construction of the next array element, if any.
1159
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001160 {
John McCallbd309292010-07-06 01:34:17 +00001161 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001162
John McCallf677a8e2011-07-13 06:10:41 +00001163 // Evaluate the constructor and its arguments in a regular
1164 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001165 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001166 !ctor->getParent()->hasTrivialDestructor()) {
1167 Destroyer *destroyer = destroyCXXObject;
1168 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1169 }
1170
1171 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001172 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001173 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001174
John McCallf677a8e2011-07-13 06:10:41 +00001175 // Go to the next element.
1176 llvm::Value *next =
1177 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1178 "arrayctor.next");
1179 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001180
John McCallf677a8e2011-07-13 06:10:41 +00001181 // Check whether that's the end of the loop.
1182 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1183 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1184 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001185
John McCall6549b312011-07-13 07:37:11 +00001186 // Patch the earlier check to skip over the loop.
1187 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1188
John McCallf677a8e2011-07-13 06:10:41 +00001189 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001190}
1191
John McCall82fe67b2011-07-09 01:37:26 +00001192void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1193 llvm::Value *addr,
1194 QualType type) {
1195 const RecordType *rtype = type->castAs<RecordType>();
1196 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1197 const CXXDestructorDecl *dtor = record->getDestructor();
1198 assert(!dtor->isTrivial());
1199 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001200 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001201}
1202
Anders Carlsson27da15b2010-01-01 20:29:01 +00001203void
1204CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlssone11f9ce2010-05-02 23:20:53 +00001205 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001206 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001207 llvm::Value *This,
1208 CallExpr::const_arg_iterator ArgBeg,
1209 CallExpr::const_arg_iterator ArgEnd) {
Devang Patelb6ed3692011-02-22 20:55:26 +00001210
1211 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +00001212 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001213 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopher034ba7e2012-02-01 21:44:56 +00001214 // If debug info for this class has not been emitted then this is the
1215 // right time to do so.
Devang Patelb6ed3692011-02-22 20:55:26 +00001216 const CXXRecordDecl *Parent = D->getParent();
1217 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1218 Parent->getLocation());
1219 }
1220
John McCallca972cd2010-02-06 00:25:16 +00001221 if (D->isTrivial()) {
1222 if (ArgBeg == ArgEnd) {
1223 // Trivial default constructor, no codegen required.
1224 assert(D->isDefaultConstructor() &&
1225 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001226 return;
1227 }
John McCallca972cd2010-02-06 00:25:16 +00001228
1229 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001230 assert(D->isCopyOrMoveConstructor() &&
1231 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001232
John McCallca972cd2010-02-06 00:25:16 +00001233 const Expr *E = (*ArgBeg);
1234 QualType Ty = E->getType();
1235 llvm::Value *Src = EmitLValue(E).getAddress();
1236 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001237 return;
1238 }
1239
Douglas Gregor61535002013-01-31 05:50:40 +00001240 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase,
1241 Delegating);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001242 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1243
Richard Smithe30752c2012-10-09 19:52:38 +00001244 // FIXME: Provide a source location here.
1245 EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
1246 VTT, ArgBeg, ArgEnd);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001247}
1248
John McCallf8ff7b92010-02-23 00:48:20 +00001249void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001250CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1251 llvm::Value *This, llvm::Value *Src,
1252 CallExpr::const_arg_iterator ArgBeg,
1253 CallExpr::const_arg_iterator ArgEnd) {
1254 if (D->isTrivial()) {
1255 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001256 assert(D->isCopyOrMoveConstructor() &&
1257 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001258 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1259 return;
1260 }
1261 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1262 clang::Ctor_Complete);
1263 assert(D->isInstance() &&
1264 "Trying to emit a member call expr on a static method!");
1265
1266 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1267
1268 CallArgList Args;
1269
1270 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001271 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001272
1273
1274 // Push the src ptr.
1275 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001276 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001277 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001278 Args.add(RValue::get(Src), QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001279
1280 // Skip over first argument (Src).
1281 ++ArgBeg;
1282 CallExpr::const_arg_iterator Arg = ArgBeg;
1283 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1284 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1285 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall32ea9692011-03-11 20:59:21 +00001286 EmitCallArg(Args, *Arg, *I);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001287 }
1288 // Either we've emitted all the call args, or we have a call to a
1289 // variadic function.
1290 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1291 "Extra arguments in non-variadic function!");
1292 // If we still have any arguments, emit them using the type of the argument.
1293 for (; Arg != ArgEnd; ++Arg) {
1294 QualType ArgType = Arg->getType();
John McCall32ea9692011-03-11 20:59:21 +00001295 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001296 }
1297
John McCall8dda7b22012-07-07 06:41:13 +00001298 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1299 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001300}
1301
1302void
John McCallf8ff7b92010-02-23 00:48:20 +00001303CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1304 CXXCtorType CtorType,
1305 const FunctionArgList &Args) {
1306 CallArgList DelegateArgs;
1307
1308 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1309 assert(I != E && "no parameters to constructor");
1310
1311 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001312 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001313 ++I;
1314
1315 // vtt
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001316 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001317 /*ForVirtualBase=*/false,
1318 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001319 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001320 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001321
Anders Carlssona864caf2010-03-23 04:11:45 +00001322 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001323 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001324 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001325 ++I;
1326 }
1327 }
1328
1329 // Explicit arguments.
1330 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001331 const VarDecl *param = *I;
1332 EmitDelegateCallArg(DelegateArgs, param);
John McCallf8ff7b92010-02-23 00:48:20 +00001333 }
1334
John McCalla729c622012-02-17 03:33:10 +00001335 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallf8ff7b92010-02-23 00:48:20 +00001336 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1337 ReturnValueSlot(), DelegateArgs, Ctor);
1338}
1339
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001340namespace {
1341 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1342 const CXXDestructorDecl *Dtor;
1343 llvm::Value *Addr;
1344 CXXDtorType Type;
1345
1346 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1347 CXXDtorType Type)
1348 : Dtor(D), Addr(Addr), Type(Type) {}
1349
John McCall30317fd2011-07-12 20:27:29 +00001350 void Emit(CodeGenFunction &CGF, Flags flags) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001351 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001352 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001353 }
1354 };
1355}
1356
Alexis Hunt61bc1732011-05-01 07:04:31 +00001357void
1358CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1359 const FunctionArgList &Args) {
1360 assert(Ctor->isDelegatingConstructor());
1361
1362 llvm::Value *ThisPtr = LoadCXXThis();
1363
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001364 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001365 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001366 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001367 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001368 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001369 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001370 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001371
1372 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001373
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001374 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001375 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001376 CXXDtorType Type =
1377 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1378
1379 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1380 ClassDecl->getDestructor(),
1381 ThisPtr, Type);
1382 }
1383}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001384
Anders Carlsson27da15b2010-01-01 20:29:01 +00001385void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1386 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001387 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001388 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001389 llvm::Value *This) {
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001390 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
Douglas Gregor61535002013-01-31 05:50:40 +00001391 ForVirtualBase, Delegating);
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001392 llvm::Value *Callee = 0;
Richard Smith9c6890a2012-11-01 22:30:59 +00001393 if (getLangOpts().AppleKext)
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +00001394 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1395 DD->getParent());
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001396
1397 if (!Callee)
1398 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001399
Richard Smithe30752c2012-10-09 19:52:38 +00001400 // FIXME: Provide a source location here.
1401 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1402 VTT, 0, 0);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001403}
1404
John McCall53cad2e2010-07-21 01:41:18 +00001405namespace {
John McCallcda666c2010-07-21 07:22:38 +00001406 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001407 const CXXDestructorDecl *Dtor;
1408 llvm::Value *Addr;
1409
1410 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1411 : Dtor(D), Addr(Addr) {}
1412
John McCall30317fd2011-07-12 20:27:29 +00001413 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall53cad2e2010-07-21 01:41:18 +00001414 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001415 /*ForVirtualBase=*/false,
1416 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001417 }
1418 };
1419}
1420
John McCall8680f872010-07-21 06:29:51 +00001421void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1422 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001423 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001424}
1425
John McCallbd309292010-07-06 01:34:17 +00001426void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1427 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1428 if (!ClassDecl) return;
1429 if (ClassDecl->hasTrivialDestructor()) return;
1430
1431 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001432 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001433 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001434}
1435
Anders Carlsson27da15b2010-01-01 20:29:01 +00001436llvm::Value *
Anders Carlsson84673e22010-01-31 01:36:53 +00001437CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1438 const CXXRecordDecl *ClassDecl,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001439 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001440 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyckbb4e9772011-04-07 12:37:09 +00001441 CharUnits VBaseOffsetOffset =
Peter Collingbournea8341662011-09-26 01:56:30 +00001442 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001443
1444 llvm::Value *VBaseOffsetPtr =
Ken Dyckbb4e9772011-04-07 12:37:09 +00001445 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1446 "vbase.offset.ptr");
Chris Lattner2192fe52011-07-18 04:24:23 +00001447 llvm::Type *PtrDiffTy =
Anders Carlsson27da15b2010-01-01 20:29:01 +00001448 ConvertType(getContext().getPointerDiffType());
1449
1450 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1451 PtrDiffTy->getPointerTo());
1452
1453 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1454
1455 return VBaseOffset;
1456}
1457
Anders Carlssone87fae92010-03-28 19:40:00 +00001458void
1459CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001460 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001461 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001462 llvm::Constant *VTable,
1463 const CXXRecordDecl *VTableClass) {
Anders Carlsson58890272010-03-29 01:08:49 +00001464 const CXXRecordDecl *RD = Base.getBase();
1465
Anders Carlssone87fae92010-03-28 19:40:00 +00001466 // Compute the address point.
Anders Carlsson58890272010-03-29 01:08:49 +00001467 llvm::Value *VTableAddressPoint;
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001468
Anders Carlsson58890272010-03-29 01:08:49 +00001469 // Check if we need to use a vtable from the VTT.
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001470 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlsson652758c2010-04-20 05:22:15 +00001471 (RD->getNumVBases() || NearestVBase)) {
Anders Carlsson58890272010-03-29 01:08:49 +00001472 // Get the secondary vpointer index.
1473 uint64_t VirtualPointerIndex =
1474 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1475
1476 /// Load the VTT.
1477 llvm::Value *VTT = LoadCXXVTT();
1478 if (VirtualPointerIndex)
1479 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1480
1481 // And load the address point from the VTT.
1482 VTableAddressPoint = Builder.CreateLoad(VTT);
1483 } else {
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +00001484 uint64_t AddressPoint =
Peter Collingbourneaffe1112011-09-26 01:56:50 +00001485 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlsson58890272010-03-29 01:08:49 +00001486 VTableAddressPoint =
Anders Carlssone87fae92010-03-28 19:40:00 +00001487 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlsson58890272010-03-29 01:08:49 +00001488 }
Anders Carlssone87fae92010-03-28 19:40:00 +00001489
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001490 // Compute where to store the address point.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001491 llvm::Value *VirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001492 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001493
1494 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1495 // We need to use the virtual base offset offset because the virtual base
1496 // might have a different offset in the most derived class.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001497 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1498 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001499 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001500 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001501 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001502 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001503 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001504
1505 // Apply the offsets.
1506 llvm::Value *VTableField = LoadCXXThis();
1507
Ken Dyckcfc332c2011-03-23 00:45:26 +00001508 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001509 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1510 NonVirtualOffset,
1511 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001512
Anders Carlssone87fae92010-03-28 19:40:00 +00001513 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001514 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001515 VTableAddressPoint->getType()->getPointerTo();
1516 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001517 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1518 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00001519}
1520
Anders Carlssond5895932010-03-28 21:07:49 +00001521void
1522CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001523 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001524 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001525 bool BaseIsNonVirtualPrimaryBase,
1526 llvm::Constant *VTable,
1527 const CXXRecordDecl *VTableClass,
1528 VisitedVirtualBasesSetTy& VBases) {
1529 // If this base is a non-virtual primary base the address point has already
1530 // been set.
1531 if (!BaseIsNonVirtualPrimaryBase) {
1532 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001533 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1534 VTable, VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001535 }
1536
1537 const CXXRecordDecl *RD = Base.getBase();
1538
1539 // Traverse bases.
1540 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1541 E = RD->bases_end(); I != E; ++I) {
1542 CXXRecordDecl *BaseDecl
1543 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1544
1545 // Ignore classes without a vtable.
1546 if (!BaseDecl->isDynamicClass())
1547 continue;
1548
Ken Dyck3fb4c892011-03-23 01:04:18 +00001549 CharUnits BaseOffset;
1550 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001551 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001552
1553 if (I->isVirtual()) {
1554 // Check if we've visited this virtual base before.
1555 if (!VBases.insert(BaseDecl))
1556 continue;
1557
1558 const ASTRecordLayout &Layout =
1559 getContext().getASTRecordLayout(VTableClass);
1560
Ken Dyck3fb4c892011-03-23 01:04:18 +00001561 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1562 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00001563 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001564 } else {
1565 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1566
Ken Dyck16ffcac2011-03-24 01:21:01 +00001567 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001568 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00001569 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001570 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001571 }
1572
Ken Dyck16ffcac2011-03-24 01:21:01 +00001573 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001574 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001575 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001576 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001577 VTable, VTableClass, VBases);
1578 }
1579}
1580
1581void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1582 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001583 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001584 return;
1585
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001586 // Get the VTable.
1587 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlssonb35ea552010-03-24 03:57:14 +00001588
Anders Carlssond5895932010-03-28 21:07:49 +00001589 // Initialize the vtable pointers for this class and all of its bases.
1590 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00001591 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1592 /*NearestVBase=*/0,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001593 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlssond5895932010-03-28 21:07:49 +00001594 /*BaseIsNonVirtualPrimaryBase=*/false,
1595 VTable, RD, VBases);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001596}
Dan Gohman8fc50c22010-10-26 18:44:08 +00001597
1598llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00001599 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001600 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001601 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1602 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1603 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001604}
Anders Carlssonc36783e2011-05-08 20:32:23 +00001605
1606static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1607 const Expr *E = Base;
1608
1609 while (true) {
1610 E = E->IgnoreParens();
1611 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1612 if (CE->getCastKind() == CK_DerivedToBase ||
1613 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1614 CE->getCastKind() == CK_NoOp) {
1615 E = CE->getSubExpr();
1616 continue;
1617 }
1618 }
1619
1620 break;
1621 }
1622
1623 QualType DerivedType = E->getType();
1624 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1625 DerivedType = PTy->getPointeeType();
1626
1627 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1628}
1629
1630// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1631// quite what we want.
1632static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1633 while (true) {
1634 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1635 E = PE->getSubExpr();
1636 continue;
1637 }
1638
1639 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1640 if (CE->getCastKind() == CK_NoOp) {
1641 E = CE->getSubExpr();
1642 continue;
1643 }
1644 }
1645 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1646 if (UO->getOpcode() == UO_Extension) {
1647 E = UO->getSubExpr();
1648 continue;
1649 }
1650 }
1651 return E;
1652 }
1653}
1654
1655/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1656/// function call on the given expr can be devirtualized.
Anders Carlssonc36783e2011-05-08 20:32:23 +00001657static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1658 const CXXMethodDecl *MD) {
1659 // If the most derived class is marked final, we know that no subclass can
1660 // override this member function and so we can devirtualize it. For example:
1661 //
1662 // struct A { virtual void f(); }
1663 // struct B final : A { };
1664 //
1665 // void f(B *b) {
1666 // b->f();
1667 // }
1668 //
1669 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1670 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1671 return true;
1672
1673 // If the member function is marked 'final', we know that it can't be
1674 // overridden and can therefore devirtualize it.
1675 if (MD->hasAttr<FinalAttr>())
1676 return true;
1677
1678 // Similarly, if the class itself is marked 'final' it can't be overridden
1679 // and we can therefore devirtualize the member function call.
1680 if (MD->getParent()->hasAttr<FinalAttr>())
1681 return true;
1682
1683 Base = skipNoOpCastsAndParens(Base);
1684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1685 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1686 // This is a record decl. We know the type and can devirtualize it.
1687 return VD->getType()->isRecordType();
1688 }
1689
1690 return false;
1691 }
1692
1693 // We can always devirtualize calls on temporary object expressions.
1694 if (isa<CXXConstructExpr>(Base))
1695 return true;
1696
1697 // And calls on bound temporaries.
1698 if (isa<CXXBindTemporaryExpr>(Base))
1699 return true;
1700
1701 // Check if this is a call expr that returns a record type.
1702 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1703 return CE->getCallReturnType()->isRecordType();
1704
1705 // We can't devirtualize the call.
1706 return false;
1707}
1708
1709static bool UseVirtualCall(ASTContext &Context,
1710 const CXXOperatorCallExpr *CE,
1711 const CXXMethodDecl *MD) {
1712 if (!MD->isVirtual())
1713 return false;
1714
1715 // When building with -fapple-kext, all calls must go through the vtable since
1716 // the kernel linker can do runtime patching of vtables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001717 if (Context.getLangOpts().AppleKext)
Anders Carlssonc36783e2011-05-08 20:32:23 +00001718 return true;
1719
1720 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1721}
1722
1723llvm::Value *
1724CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1725 const CXXMethodDecl *MD,
1726 llvm::Value *This) {
John McCalla729c622012-02-17 03:33:10 +00001727 llvm::FunctionType *fnType =
1728 CGM.getTypes().GetFunctionType(
1729 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssonc36783e2011-05-08 20:32:23 +00001730
1731 if (UseVirtualCall(getContext(), E, MD))
John McCalla729c622012-02-17 03:33:10 +00001732 return BuildVirtualCall(MD, This, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00001733
John McCalla729c622012-02-17 03:33:10 +00001734 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00001735}
Eli Friedman5a6d5072012-02-16 01:37:33 +00001736
John McCall8dda7b22012-07-07 06:41:13 +00001737void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
1738 CallArgList &callArgs) {
Eli Friedman2495ab02012-02-25 02:48:22 +00001739 // Lookup the call operator
John McCall8dda7b22012-07-07 06:41:13 +00001740 DeclarationName operatorName
Eli Friedman5b446882012-02-16 03:47:28 +00001741 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall8dda7b22012-07-07 06:41:13 +00001742 CXXMethodDecl *callOperator =
David Blaikieff7d47a2012-12-19 00:45:41 +00001743 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman5b446882012-02-16 03:47:28 +00001744
Eli Friedman5b446882012-02-16 03:47:28 +00001745 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00001746 const CGFunctionInfo &calleeFnInfo =
1747 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
1748 llvm::Value *callee =
1749 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
1750 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00001751
John McCall8dda7b22012-07-07 06:41:13 +00001752 // Prepare the return slot.
1753 const FunctionProtoType *FPT =
1754 callOperator->getType()->castAs<FunctionProtoType>();
1755 QualType resultType = FPT->getResultType();
1756 ReturnValueSlot returnSlot;
1757 if (!resultType->isVoidType() &&
1758 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
1759 hasAggregateLLVMType(calleeFnInfo.getReturnType()))
1760 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
1761
1762 // We don't need to separately arrange the call arguments because
1763 // the call can't be variadic anyway --- it's impossible to forward
1764 // variadic arguments.
Eli Friedman5b446882012-02-16 03:47:28 +00001765
1766 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00001767 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
1768 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00001769
John McCall8dda7b22012-07-07 06:41:13 +00001770 // If necessary, copy the returned value into the slot.
1771 if (!resultType->isVoidType() && returnSlot.isNull())
1772 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00001773 else
1774 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00001775}
1776
Eli Friedman2495ab02012-02-25 02:48:22 +00001777void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1778 const BlockDecl *BD = BlockInfo->getBlockDecl();
1779 const VarDecl *variable = BD->capture_begin()->getVariable();
1780 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1781
1782 // Start building arguments for forwarding call
1783 CallArgList CallArgs;
1784
1785 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1786 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1787 CallArgs.add(RValue::get(ThisPtr), ThisType);
1788
1789 // Add the rest of the parameters.
1790 for (BlockDecl::param_const_iterator I = BD->param_begin(),
1791 E = BD->param_end(); I != E; ++I) {
1792 ParmVarDecl *param = *I;
1793 EmitDelegateCallArg(CallArgs, param);
1794 }
1795
1796 EmitForwardingCallToLambda(Lambda, CallArgs);
1797}
1798
1799void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1800 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1801 // FIXME: Making this work correctly is nasty because it requires either
1802 // cloning the body of the call operator or making the call operator forward.
1803 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1804 return;
1805 }
1806
Eli Friedman2495ab02012-02-25 02:48:22 +00001807 EmitFunctionBody(Args);
Eli Friedman2495ab02012-02-25 02:48:22 +00001808}
1809
1810void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1811 const CXXRecordDecl *Lambda = MD->getParent();
1812
1813 // Start building arguments for forwarding call
1814 CallArgList CallArgs;
1815
1816 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1817 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1818 CallArgs.add(RValue::get(ThisPtr), ThisType);
1819
1820 // Add the rest of the parameters.
1821 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1822 E = MD->param_end(); I != E; ++I) {
1823 ParmVarDecl *param = *I;
1824 EmitDelegateCallArg(CallArgs, param);
1825 }
1826
1827 EmitForwardingCallToLambda(Lambda, CallArgs);
1828}
1829
Douglas Gregor355efbb2012-02-17 03:02:34 +00001830void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1831 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00001832 // FIXME: Making this work correctly is nasty because it requires either
1833 // cloning the body of the call operator or making the call operator forward.
1834 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00001835 return;
Eli Friedman5b446882012-02-16 03:47:28 +00001836 }
1837
Douglas Gregor355efbb2012-02-17 03:02:34 +00001838 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00001839}